repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
riggsd/guano-py
guano.py
Python
mit
19,292
0.003421
""" This is the Python reference implementation for reading and writing GUANO metadata. GUANO is the "Grand Unified Acoustic Notation Ontology", an extensible metadata format for representing bat acoustics data. Import this Python module as:: import guano This module utilizes the Python :mod:`logging` framework...
ct import os.path import shutil from datetime import datetime, tzinfo, timedelta from contextlib import closing from tempfile import NamedTemporaryFile from collections import OrderedDict, namedtuple from
base64 import standard_b64encode as base64encode from base64 import standard_b64decode as base64decode import logging log = logging.Logger(__name__) if sys.version_info[0] > 2: unicode = str basestring = str __version__ = '1.0.15.dev0' __all__ = 'GuanoFile', WHITESPACE = ' \t\n\x0b\x0c\r\0' wavparams =...
pgrm/project-euler
0001-0050/35-Circular_primes.py
Python
apache-2.0
831
0.00361
""" The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ from collections import deque import pr...
imes: isCircularPrime = True digits = deque(permutations.split_into_digits(prime)) for i in xrange(0, len(digits)): digits.rotate(1) newPrime = permutations.combine_numbers(digits) if newPrime not in allPrimes:
isCircularPrime = False break if isCircularPrime: countOfCircularPrimes += 1 print str(countOfCircularPrimes)
thomas-hori/Repuge-NG
prelevula/SimpleDungeonLevel.py
Python
mpl-2.0
6,565
0.037928
from ludicrous.GeneratedLevel import GeneratedLevel import random,math __copying__=""" Written by Thomas Hori This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.""" c...
om_[0]-to[0])) vector_angle*=180 vector_angle/=math.pi vector_angle=int(vector_angle+0.5) if vector_angle>45: from_[1]-=(from_[1]-to[1])/abs(from_[1]-to[1]) else:
from_[0]-=(from_[0]-to[0])/abs(from_[0]-to[0]) block="\n".join(["".join(i) for i in block]) # self._ag=(xoffset+1,yoffset+1) gamut=[] gamutx=range(xoffset+1,xoffset+1+iwidth) gamuty=range(yoffset+1,yoffset+1+iheight) for x in gamutx: for y in g...
keras-team/keras
keras/models/__init__.py
Python
apache-2.0
1,704
0.000587
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ne.sequential import Sequential from keras.engine.training import Model from keras.models.cloning import clone_and_build_model from keras.models.cloning import clone_model from keras.models.cloning import share_weights from keras.models.sharpness_aware_minimization import SharpnessAwareMinimization from keras.saving.mo...
keras.saving.save import save_model # Private symbols that are used in tests. # TODO(b/221261361): Clean up private symbols usage and remove these imports. from keras.models.cloning import _clone_functional_model from keras.models.cloning import _clone_layer from keras.models.cloning import _clone_layers_and_model_con...
wangming28/syzygy
syzygy/scripts/test_bot/log_helper.py
Python
apache-2.0
4,510
0.008426
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
AddCommandLineOptions(option_parser): """Adds the group of logging related options to the given option_pars
er. Args: option_parser: the option parser object to update. This is expected to be an instance of optparse.OptionParser. """ group = optparse.OptionGroup(option_parser, 'Logging Options') group.add_option('--log-verbose', action='store_true', default=False, help='Log verbosely'...
jchuang1977/openwrt
package/lean/mt/drivers/wifi-l1profile/make-l1profile.py
Python
gpl-2.0
3,812
0.033578
#!/usr/bin/env python # Hua Shao <[email protected]> import sys import re import random l1conf = [] def parseconfig(conf): global l1conf l1conf.extend([[],[],[]]) with open(conf, "r") as fp: for line in fp: if line.startswith("CONFIG_first_card_"): kv = line.split("=") l1conf[0].append((kv[0][l...
e, random.
random()) if3 = d3.get(name, random.random()) assert len(set([if1, if2, if3])) == 3, "duplication found in "+name # main_ifname should end with "0" if1 = [ x.strip() for x in d1.get("main_ifname","").split(";") if x] if2 = [ x.strip() for x in d2.get("main_ifname","").split(";") if x] if3 = [ x.strip() for x i...
digitalfox/MAGE
ref/templatetags/filter.py
Python
apache-2.0
2,371
0.005905
# coding: utf-8 from django import template from django.db import models from ref.models import ExtendedParameterDict from django.utils.safestring import mark_safe register = template.Library() @r
egister.filter def verbose_name(value): return value._meta.verbose_name @register.filter def ksh_protect_and_quote(value): if isinstance(value, bool) and value: return "1" elif isinstance(value, bool) and not value: return "0" if isinstance(value, int): return value if isi...
'.join([a.name for a in value.all()]) + '"' if value is None: return '""' if isinstance(value, models.Model): return '"%s"' % value.pk res = ("%s" % value).replace('"', '\\"').replace('$', '\$') return ('"%s"' % res) @register.filter def apply_field_template(component_instance, compu...
hungpham2511/toppra
tests/tests/constraint/test_joint_acceleration.py
Python
mit
3,595
0.002782
import pytest import numpy as np import numpy.testing as npt import toppra as ta import toppra.constraint as constraint
from toppra.constants import JACC_MAXU @pytest.fixture(params=[1, 2, 6, '6d'], name='accel_constraint_setup') def create_acceleration_pc
_fixtures(request): """ Parameterized Acceleration path constraint. Return: ------- data: A tuple. Contains path, ss, alim. pc: A `PathConstraint`. """ dof = request.param if dof == 1: # Scalar pi = ta.PolynomialPath([1, 2, 3]) # 1 + 2s + 3s^2 ss = np.linspace(0, 1...
simplecrypto/powerpool
powerpool/main.py
Python
bsd-2-clause
15,154
0.001254
import yaml import socket import argparse import datetime import setproctitle import gevent import gevent.hub import signal import subprocess import powerpool import time import logging import sys from gevent_helpers import BlockingDetector from gevent import sleep from gevent.monkey import patch_all from gevent.serve...
raw config and distributes it to each module, as well as loading dynamic
modules. It also handles logging facilities by being the central logging registry. Each module can "register" a logger with the main object, which attaches it to configured handlers. """ manager = None gl_methods = ['_tick_stats'] defaults = dict(procname="powerpool", t...
AdminTL/gestion_personnage_TL
src/web/py_class/config.py
Python
gpl-3.0
2,676
0.001868
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from sys import stderr class Config(object): """Contains general configuration.""" def __init__(self, parser): self._db_config_path = parser.db_config_path self._keys = {} try: with open(self._db_config_path, enco...
if result is None: result = default return result def update(self, key, value, save=False): """ Update set of key with value. :param key: string of value separate by dot :param value: The
value to insert. :param save: Option to save on file :return: """ # Search and replace value for key lst_key = key.split(".") result = None for i in range(len(lst_key)): a_key = lst_key[i] if i == 0: if a_key in self._keys: ...
strava/thrift
tutorial/py.twisted/PythonServer.py
Python
apache-2.0
2,652
0.00264
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
um2 elif work.op == Operation.SUBTRACT: val = work.num1 - work.num2 elif work.op == Operation.MULTIPLY: val = work.num1 * work.num2 elif work.op == Operation.DIVIDE: if work.num2 == 0: raise InvalidOperation(work.op, 'Cannot divide by 0') ...
work.num2 else: raise InvalidOperation(work.op, 'Invalid operation') log = SharedStruct() log.key = logid log.value = '%d' % (val) self.log[logid] = log return val def getStruct(self, key): print('getStruct(%d)' % (key)) return self.log[...
CloverHealth/airflow
airflow/contrib/hooks/bigquery_hook.py
Python
apache-2.0
63,861
0.00119
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
erbose=False, dialect='legacy'): super(BigQueryPandasConnector, self).__init__(project_id) gb
q_check_google_client_version() gbq_test_google_api_imports() self.project_id = project_id self.reauth = reauth self.service = service self.verbose = verbose self.dialect = dialect class BigQueryConnection(object): """ BigQuery does not have a notion of a persis...
mittya/duoclub
duoclub/accounts/admin.py
Python
mit
528
0
# -*- coding: utf-8 -*- from django.contrib im
port admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Profile class ProfileInline(admin.StackedInline): model = Profile verbose_name = '用户' verbose_name_plural = '用户扩展' class UserAdmin(BaseUserAdmin): inlines = (P...
shaggytwodope/rtv
rtv/objects.py
Python
mit
24,783
0.000161
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import os import time import signal import inspect import weakref import logging import threading import curses import curses.ascii from contextlib import contextmanager import six import praw import requests from . import exceptions _logger...
window message_len = len(message) + len(trail) n_rows, n_cols = self._terminal.stdscr.getmaxyx() s_row = (n_rows - 3) // 2 s_col = (n_cols - message_le
n - 1) // 2 window = curses.newwin(3, message_len + 2, s_row, s_col) # Animate the loading prompt until the stopping condition is triggered # when the context manager exits. with self._terminal.no_delay(): while True: for i in range(len(trail) + 1): ...
piohhmy/euler
p003.py
Python
mit
448
0.037946
import math def find_factors(num): return set([factor for x in range(1, int((math.sqrt(num)+1))) for factor in (x, num//x) if num % x == 0]) def is_prime(num): for x in range(2, int(math.sqrt(num)) +1): if num%x ==
0: return False return True def find_prime_factors(num): return list(filter(is_prime, find_factors(num))) def solve_p3(): return max(find_prime_factors(600851475143))
if __name__ == '__main__': print(solve_p3())
ardi69/pyload-0.4.10
tests/test_json.py
Python
gpl-3.0
1,322
0.006051
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import logging import urllib import urllib2 url = "http://localhost:8001/api/%s" class TestJson(object): def call(self, name, post=None): if not post: post = {} post['session'] = self.key u = urllib2.urlopen
(url % name, data=urlencode(post)) return json.loads(u.read()) def setUp(self): u = urllib2.urlopen(url % "login", data=urlencode({"username": "TestUser", "password": "pwhere"})) self.key = json.loads(u.read()) assert self.key is not False def test_wronglogin(self): u...
({"username": "crap", "password": "wrongpw"})) assert json.loads(u.read()) is False def test_access(self): try: urllib2.urlopen(url % "getServerVersion") except urllib2.HTTPError, e: assert e.code == 403 else: assert False def test_status(s...
tcalmant/ipopo
tests/shell/test_report.py
Python
apache-2.0
7,965
0
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Tests the shell report module :author: Thomas Calmant """ # Standard library import json import os try: from StringIO import StringIO except ImportError: from io import StringIO # Tests try: import unittest2 as unittest except ImportError: imp...
ttest.TestCase): """ Tests the shell report commands """ def setUp(self): """ Starts a framework and install the shell bundle """ # Start the framework self.framework = create_framework( ['pelix.shell.core', 'pelix.shell.report'])
self.framework.start() self.context = self.framework.get_bundle_context() # Shell service svc_ref = self.context.get_service_reference(SERVICE_SHELL) self.shell = self.context.get_service(svc_ref) # Report service svc_ref = self.context.get_service_reference(SERVIC...
has2k1/travis_doc
travis_doc/travis_doc.py
Python
bsd-3-clause
120
0
def function1(): """ Return 1 """ return 1 def function2(): """ Return 2 """ return 2
theboocock/fine_mapping_pipeline
tests/test_run_finemap.py
Python
mit
1,755
0.009687
# Copyright (c) 2015 Boocock James <[email protected]> # Author: Boocock James <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"),
to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit pers
ons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDIN...
kreopt/aioweb
wyrm/modules/help/orator/types.py
Python
mit
2,556
0.00431
import os, sys import shutil brief = "output field types" def execute(argv, argv0, engine): print(""" table.big_increments('id') Incrementing ID using a “big integer” equivalent table.big_integer('votes') BIGINT equivalent to the table table.binary('data') ...
imal('amount', 5, 2) DECIMAL equivalent to the table with a precision and scale table.double('column', 15, 8) DOUBLE equivalent to the table with precision, 15 digits in total and 8 after the decimal point table.enum('choices', ['fo
o', 'bar']) ENUM equivalent to the table table.float('amount') FLOAT equivalent to the table table.increments('id') Incrementing ID to the table (primary key) table.integer('votes') INTEGER equivalent to the table table.json('options') ...
marcosbontempo/inatelos
poky-daisy/scripts/lib/mic/3rdparty/pykickstart/commands/mouse.py
Python
mit
2,610
0.002299
# # Chris Lumens <[email protected]> # # Copyright 2005, 2006, 2007 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # ...
port * import gettext _ = lambda x: gettext.ldgettext("pykickstart", x) class RHEL3_Mouse(KickstartCommand): removedKeywords = KickstartCommand.removedKe
ywords removedAttrs = KickstartCommand.removedAttrs def __init__(self, writePriority=0, *args, **kwargs): KickstartCommand.__init__(self, writePriority, *args, **kwargs) self.op = self._getParser() self.device = kwargs.get("device", "") self.emulthree = kwargs.get("emulthree", ...
Tomin1/sudoku-solver
sudoku/solver.py
Python
gpl-3.0
7,465
0.007905
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Solver object # Copyright (C) 2011-2012, Tomi Leppänen (aka Tomin) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of t...
oku[r_n][c_n] if sumc != 45: return False return True def isgood(self): """Checks if a partial (or complete) sudoku is correct This is slower than isgood_final """ for a in range(0,9): numbersa = [] num...
numbersa.index(self.sudoku[a][b]) except ValueError: numbersa.append(self.sudoku[a][b]) else: return False if self.sudoku[b][a] != "": try: numbersb.inde...
OCA/purchase-workflow
purchase_order_line_deep_sort/models/res_company.py
Python
agpl-3.0
948
0
# Copyright 2018 Tecnativa - Vicent Cubells <[email protected]>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3 from odoo import fields, models SORTING_CRITERIA = [ ("name", "By name"), ("product_id.name", "By product name"), ("product_id.default_code", "By product reference"), ("date_planned", "By date planned"), ("price_unit", "By price"), ("pr...
_DIRECTION = [ ("asc", "Ascending"), ("desc", "Descending"), ] class ResCompany(models.Model): _inherit = "res.company" default_po_line_order = fields.Selection( selection=SORTING_CRITERIA, string="Line Order", help="Select a sorting criteria for purchase order lines.", ) ...
palaniyappanBala/rekall
rekall-core/rekall/plugins/linux/address_resolver.py
Python
gpl-2.0
2,567
0.00039
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later ver...
common.LinuxPlugin): """A Linux specific address resolver plugin.""" def _EnsureInitialized(self): if self._initialized: return # Insert a psuedo module for the kernel self.AddModule(KernelModule(session=self.session)) # Add LKMs.
for kmod in self.session.plugins.lsmod().get_module_list(): self.AddModule(LKMModule(kmod, session=self.session)) self._initialized = True
therve/twotp
twotp/test/util.py
Python
mit
320
0.003125
# Copyright (c) 2007-2009 Thomas Herve <[email protected]>. # See LICENSE for details. """ Test utilities. """ from twisted.trial.unitte
st import TestCase as TrialTestCase class TestCase(TrialTestCase): """ Specific TestCase class to add some specific functionalities or backpor
t recent additions. """
kyleaoman/simfiles
simfiles/_simfiles.py
Python
gpl-3.0
10,409
0
import warnings from importlib.util import spec_from_file_location, module_from_spec from os.path import expanduser, dirname, join from ._hdf5_io import hdf5_get # SimFiles is a dict with added features, notably __getattr__ and __setattr__, # and automatic loading of data from simulation files as defined using a confi...
'Aliases exist for unknown keys:\n {:s}.'.format( '\n '.join(unknown) ),
RuntimeWarning ) return @dealias def __setattr__(self, key, value): return self.__setitem__(key, value) @dealias def __getattr__(self, key): try: return self.__getitem__(key) except KeyError: raise AttributeError("'SimFile...
clebergnu/autotest
client/profilers/perf/perf.py
Python
gpl-2.0
2,846
0.001757
""" perf is a tool included in the linux kernel tree that supports functionality similar to oprofile and more. @see: http://lwn.net/Articles/310260/ """ import time, os, stat, subprocess, signal i
mport logging from autotest_lib.client.bin import profiler, os_dep, utils
class perf(profiler.profiler): version = 1 def initialize(self, events=["cycles","instructions"], trace=False): if type(events) == str: self.events = [events] else: self.events = events self.trace = trace self.perf_bin = os_dep.command('perf') p...
zyga/plainbox
plainbox/impl/__init__.py
Python
gpl-3.0
4,500
0
# This file is part of Checkbox. # # Copyright 2012 Canonical Ltd. # Written by: # Zygmunt Krynicki <[email protected]> # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either versio...
ch function will be decommissioned. This is visible in the generated documentation and at runtime. Each ini
tial call to a deprecated function will cause a PendingDeprecationWarnings to be logged. The actual implementation of the function must be in in a module specified by import_path. It can be a module name or a module name and a function name, when separated by a colon. """ # Crea...
wuga214/Django-Wuga
env/bin/player.py
Python
apache-2.0
2,120
0.000472
#!/Users/wuga/Documents/website/wuga/env/bin/python2.7 # # The Python Imaging Library # $Id$ # from __future__ import print_function import sys if sys.version_info[0] > 2: import tkinter else: import Tkinter as tkinter from PIL import Image, ImageTk # ------------------------------------------------------...
if isinstance(im, list): # list of images self.im = im[1:] im = self.im[0] else: # sequence self.im = im if im.mode == "1": self.image = ImageTk.BitmapImage(im, foreground="white") else: self.image = ImageTk.Pho...
o.get("duration", 100) self.after(duration, self.next) def next(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: return # end of list e...
andymckay/zamboni
mkt/api/v2/urls.py
Python
bsd-3-clause
2,541
0.000787
from django.conf.urls import include, patterns, url from rest_framework.routers import SimpleRouter import mkt.feed.views as views from mkt.api.base import SubRouterWithFormat from mkt.
api.v1.urls import urlpatterns as v1_urls from mkt.api.views import endpoint_removed from mkt.search.views import RocketbarViewV2 feed = SimpleRouter() feed.register(r'apps', views.FeedAppViewSet, base_name='feedapps') feed.register(r'brands', views.FeedBrandViewSet, base_name='feedbrands') feed.register(r'collection...
eed.register(r'items', views.FeedItemViewSet, base_name='feeditems') subfeedapp = SubRouterWithFormat() subfeedapp.register('image', views.FeedAppImageViewSet, base_name='feed-app-image') subfeedcollection = SubRouterWithFormat() subfeedcollection.register('image', views.FeedCollectionImageViewSet...
emilydolson/forestcat
pyrobot/plugins/brains/BraitenbergVehicle2b.py
Python
agpl-3.0
789
0.020279
""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): sel...
t[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value fo
r s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine)
initios/hackvg-cityreport-backend
core/serializers.py
Python
gpl-2.0
798
0.002506
from rest_framework import serializers, fields from . import models class TypeSerializer(serializers.ModelSerializer): class Meta: model = models.Type class IssueSerializer(serializers.ModelSerializer): class Meta: model = models.Issue address = fields.CharField(read_only=True) pos...
y=True) city = fields.CharField(read_only=True) state = fields.CharField(read_only=True) county = fi
elds.CharField(read_only=True) country = fields.CharField(read_only=True) type = serializers.PrimaryKeyRelatedField(queryset=models.Type.objects.all()) type_nested = TypeSerializer(read_only=True, source='type') class PopulateExternalSerializer(serializers.Serializer): city = fields.CharField(write_on...
procamora/Wiki-Personal
pelican-plugins/liquid_tags/test_data/pelicanconf.py
Python
gpl-3.0
892
0.001121
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'The Tester' SITENAME = 'Testing site' SITEURL = 'http://example.com/test' # to make the test suite portable TIMEZONE = 'UTC' PATH = 'content' READERS = {'html': None} # Generate only one feed FEED_ALL_ATOM = None CATEG...
ecessary pages CATEGORY_SAVE_AS = '' TAG_SAVE_AS = '' AUTHOR_SAVE_AS = '' ARCHIVES_SAVE_AS = '' AUTHORS_SAVE_AS = '' CATEGORIES_SAVE_AS = '' TAGS_SAVE_AS = '' PLUGIN_PATHS = ['../../'] PLUGINS = ['liquid_tags.notebook', 'liquid_tags.generic'] NOTEBOOK_DIR = 'notebooks' LIQUID_CONFIGS = (('PATH', '.', "The default pat...
OR', '', 'Name of the blog author'))
mannion9/Intro-to-Python
ListComprehension.py
Python
mit
430
0.013953
''' Exp
lains list comprehension which is much faster than looping through list ''' ''' The general method is this ' mylist = [ SOME_EXPRESION_WITH_i for i in ITERABLE_LIST ] ' ''' # Loop (slow) iterer = list(range(10)) double = list(range(10)) mylist = [] for i in iterer: mylist.append(i+1) print('Loop result',mylist) #...
(fast) mylist = [ i+1 for i in iterer] print('List comprehension result',mylist)
geodashio/geodash-server
geodashserver/data.py
Python
bsd-3-clause
1,085
0.003687
import errno import psycopg2 from socket import error as socket_error #from jenks import jenks from django.conf import settings from django.template.loader import get_template from geodash.enumerations import MONTHS_SHORT3 from geodash.cache import provision_memcached_client from geodash.data import data_local_coun...
ance': '.01', 'iso_alpha3': iso_alpha3}) cursor.execute(q) res = cursor.fetchone() results = json.loads(res[0]) if (type
(res[0]) is not dict) else res[0] return results
GregMilway/Exercism
python/circular-buffer/circular_buffer_test.py
Python
gpl-3.0
3,084
0
import unittest from circular_buffer import ( CircularBuffer, BufferFullException, BufferEmptyException ) class CircularBufferTest(unittest.TestCase): def test_read_empty_buffer(self): buf = CircularBuffer(1) with self.assertRaises(BufferEmptyException): buf.read() d...
sertRaises(BufferEmptyException): buf.read() def test_clearing_buffer(self): buf = CircularBuffer(3) for c in '123': buf.write(c) buf.clear() with self.assertR
aises(BufferEmptyException): buf.read() buf.write('1') buf.write('2') self.assertEqual('1', buf.read()) buf.write('3') self.assertEqual('2', buf.read()) def test_alternate_write_and_read(self): buf = CircularBuffer(2) buf.write('1') self.a...
joneskoo/sikteeri
services/admin.py
Python
mit
1,213
0
from django.contrib import admin from django.contrib.admin import SimpleListFilter from django.utils.translation import ugettext_lazy as _ from services.models import Service, ServiceType, Alias # See # <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter> # for documen...
admin): def first_two(s): s = unicode(s) if len(s) < 2: return s else: return s[:2] prefixes = [first_two(alias.name) for alias in model_admin.model.objects.only('name')] prefixes = sorted(set(prefixes)) ...
return [(prefix, prefix) for prefix in prefixes] def queryset(self, request, queryset): if self.value(): return queryset.filter(name__istartswith=self.value()) else: return queryset class AliasAdmin(admin.ModelAdmin): list_filter = (StartsWithListFilter,) admin.sit...
UTSA-ICS/keystone-SID
keystone/common/dependency.py
Python
apache-2.0
10,620
0.000188
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
nal dependencies on the object for later injection. The dependencies of the parent class are combined with that of the child class to create a new set of dependencies. """ existing_optionals = getattr(cls, '_optionals', set()) cls._optionals = existing_optionals.union(dependenc...
t__ cls.__init__ = wrapper return cls return wrapped def resolve_future_dependencies(provider_name=None): """'resolve_future_dependencies' forces injection of all dependencies. Before this function is called, circular dependencies may not have been injected. This function should ...
diging/tethne-tests
tests/test_persistence_hdf5_tapmodel.py
Python
gpl-3.0
4,806
0.000624
from settings import * import unittest from tethne.model.social import tapmodel from tethne.persistence.hdf5.tapmodel import HDF5TAPModel, from_hdf5, to_hdf5 from tethne.persistence.hdf5.graphcollection import HDF5Graph import numpy import networkx import os import cPickle as pickle with open(picklepath + '/test_TA...
ys(): self.assertEqual(hmodel.g[i].all(), T_.g[i].all()) for i in hmodel.b.keys(): self.assertEqual(hmodel.b[i]
.all(), T_.b[i].all()) for i in hmodel.theta.keys(): self.assertEqual(hmodel.theta[i].all(), T_.theta[i].all()) self.assertEqual(hmodel.N_d, T_.N_d) self.assertIsInstance(hmodel.G, HDF5Graph) self.assertEqual(hmodel.G.nodes(data=True), T_.G.nodes(data=True)) self.asse...
laurenbarker/SHARE
share/robot.py
Python
apache-2.0
4,632
0.001511
import abc import json from django.apps import apps from django.db import migrations from django.apps import AppConfig from django.utils.functional import cached_property class RobotAppConfig(AppConfig, metaclass=abc.ABCMeta): disabled = False @abc.abstractproperty def version(self): raise NotI...
te() except PeriodicTask.DoesNotExist: pass class DisableRobotScheduleMigration(AbstractRobotMigration): def __call__(self, apps, schema_editor): Periodi
cTask = apps.get_model('djcelery', 'PeriodicTask') PeriodicTask.objects.filter( task=self.config.task, args=json.dumps([1, self.config.label]), # Note 1 should always be the system user ).update(enabled=False)
Lehych/iktomi
iktomi/unstable/db/sqla/images.py
Python
mit
5,666
0.001059
import os, logging from PIL import Image from sqlalchemy.orm.session import object_session from sqlalchemy.orm.util import identity_key from iktomi.unstable.utils.image_resizers import ResizeFit from iktomi.utils import cached_property from ..files import TransientFile, PersistentFile from .files import FileEventHandle...
self.prop.fill_from) if base is None: return if not os.path.isfile(base.path): logger.warn('Original file is absent %s %s %s', identity_key(instance=target), self.prop.fill_from, ...
os.path.splitext(base.name)[1] session = object_session(target) image_attr = getattr(target.__class__, self.prop.key) name = session.find_file_manager(image_attr).new_file_name( self.prop.name_template, target, ext, '') setattr(targ...
beddit/sleep-musicalization-web
webapp/urls.py
Python
bsd-2-clause
806
0.004963
from djan
go.conf.urls.defaults import patterns, url urlpatterns = patterns('webapp', url(r'^/?$', 'views.home', name='home'), url(r'^auth_redirect$', 'views.auth_redirect', name='auth_redirect'), url(r'^nights$', 'views.night_index', name='night_index
'), url(r'^song$', 'views.song_index', name='song_index'), url(r'^create_song$', 'views.song_create', name='song_create'), url(r'^song/(?P<key>[\w\d]+)$', 'views.song', name='song'), url(r'^song/(?P<key>[\w\d]+).mp3$', 'views.song_mp3', name='song_mp3'), url(r'^song/(?P<key>[\w\d]+)/edit$', 'views....
vyral/bombardier
networking/grunt.py
Python
mit
598
0.038462
import socket import poormanslogging as log LISTENPORT = 6666 class Grunt(object): def __init__(self): try: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.bind(('', LISTENPORT)) self.s.listen(1
) log.info('Waiting for orders on port {}'.format(LISTENPORT)) (c, a) = self.s.accept() self._receive_orders(c) finally: log.info('Shutting down') self.s.close() def _receive_orders(self, sock): chunks = [] while 1: try: chunks.append(self.s.recv(1024)) except OSErro
r: break msg = b''.join(chunks) print("Message:") print(msg)
nemumu/whoispy
whoispy/whoispy.py
Python
gpl-3.0
1,198
0.013356
import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(
domainName): rawMsg = "" tldNa
me = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: t...
thelabnyc/django-oscar-cybersource
sandbox/order/migrations/0001_initial.py
Python
isc
40,289
0.000819
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import oscar.models.fields.autoslugfield import django.db.models.deletion import oscar.models.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [ ("partner...
( "partner_name", models.CharField( max_length=128, verbose_name="Partner name", blank=True ), ), ( "partner_sku", models.CharField(max_length=128, verbose_na...
), ( "partner_line_reference", models.CharField( verbose_name="Partner reference", max_length=128, help_text="This is the item number that the partner uses within their system", ...
prathamtandon/g4gproblems
Arrays/flip_zeros_to_maximize_ones.py
Python
mit
3,953
0.002024
import unittest """ Given a binary array and an integer m, find the position of zeros flipping which creates the maximum number of consecutive 1s in the array such that number of zeros is <= m. Input: 1 0 0 1 1 0 1 0 1 1 1 Output: 5 7 """ """ Approach: 1. First, compute number of consecutive zeros to the left and righ...
es_and_zeros, 2), [5, 7]) ones_and_zeros = [1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1] self.assertEqual(flip_zeros_to_maximize_ones(ones_and_zeros, 1), [7]) ones_and_zeros = [0, 0, 0, 1] self.assertEqual(flip_zeros_to_maximize_ones(ones_and_zeros, 4), [0, 1, 2]) def test_flips_sliding_window(...
os = [1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1] self.assertEqual(flip_zeros_sliding_window(ones_and_zeros, 2), [5, 7]) ones_and_zeros = [1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1] self.assertEqual(flip_zeros_sliding_window(ones_and_zeros, 1), [7]) ones_and_zeros = [0, 0, 0, 1] self.assertEqual(flip...
kopringo/django-genealogy
genealogy/urls.py
Python
unlicense
856
0.022196
#-*- coding: utf-8 -*- #django from django.conf.urls import patterns, include, url from django.views.generic import RedirectView urlpatterns = patterns('genealogy',
# strona glowna url(r'^person-list$', 'views.person_list', name='person_list'), url(r'^person-view/(?P<handle>.*)/$', 'views.person_view', name='person_view'), url(r'^family-list$', 'views.family_list', name='...
anch_list'), url(r'^test$', 'views.test'), # mechanizm przelaczania wersji jezykowej #url(r'^lang/(?P<id>[plen]+)', 'views.lang', name='lang'), url(r'^$', 'views.home', name='home'), )
LICEF/edx-platform
cms/djangoapps/contentstore/views/course.py
Python
agpl-3.0
42,299
0.002482
""" Views related to operations on course objects """ import json import random import string # pylint: disable=W0402 from django.utils.translation import ugettext as _ import django.utils from django.contrib.auth.decorators import login_required from django_future.csrf import ensure_csrf_cookie from django.conf impo...
The restful handler for course specific requests. It provides the course tree with the necessary information for identifying and labeling the parts. The root will typically be a 'course' object but may not be especially as we support modules. GET html: return course listing page if not given a
course id html: return html page overview for the given course if given a course id json: return json representing the course branch's index entry as well as dag w/ all of the children replaced w/ json docs where each doc has {'_id': , 'display_name': , 'children': } POST json: crea...
FichteFoll/CSScheme
my_sublime_lib/constants.py
Python
mit
2,230
0.028251
KEY_UP = "up" KEY_DOWN = "down" KEY_RIGHT = "right" KEY_LEFT = "left" KEY_INSERT = "insert" KEY_HOME = "home" KEY_END = "end" KEY_PAGEUP = "pageup" KEY_PAGEDOWN = "pagedown" KEY_BACKSPACE ...
3" KEY_KEYPAD4 = "keypad4" KEY_KEYPAD5 = "keypad5" KEY_KEYPAD6 = "keypad6" KEY_KEYPAD7 = "keypad7" KEY_KEYPAD8 = "keypad8" KEY_KEYPAD9 = "keypad9" KEY_KEYPAD_PERIOD = "keypad_period" KEY_KEYPAD_DIVIDE = "keypad_divide" KEY_KEYPAD_MULTIP...
KEY_CLEAR = "clear" KEY_F1 = "f1" KEY_F2 = "f2" KEY_F3 = "f3" KEY_F4 = "f4" KEY_F5 = "f5" KEY_F6 = "f6" KEY_F7 = "f7" KEY_F8 = "f8" KEY_F9 = "f9" KEY_F10...
dsax64/reddit-to-prezi
xml_generator/prezi_xml_helpers.py
Python
mit
3,141
0.000955
from lxml import etree # TODO akos.hochrein think a way of removing side effects class PreziXmlHelpers(object): @staticmethod def generate_autoplay_node(xml_node, delay): autoplay_node = etree.SubElement(xml_node, 'autoplay') delay_node = etree.SubElement(autoplay_node, 'delay') dela...
version_node.text = str(version) @staticmethod def generate_type_node(xml_node, type): type_node = etree.SubElement(xml_node, 'type') type_node.text = type @staticmethod def generate_size_node(xml_node, dimensions):
size_node = etree.SubElement(xml_node, 'size') w_node = etree.SubElement(size_node, 'w') w_node.text = str(dimensions['w']) h_node = etree.SubElement(size_node, 'h') h_node.text = str(dimensions['h']) @staticmethod def generate_width_node(xml_node, dimensions): w_node...
entpy/beauty-and-pics
beauty_and_pics/custom_form_app/forms/delete_user_form.py
Python
mit
2,518
0.00556
# -*- coding: utf-8 -*- from django import forms from datetime import date from dateutil.relativedelta import * from django.contrib.auth.models import User from custom_form_app.forms.base_form_class import * from account_app.models impo
rt * from website.exceptions import * import logging, sys # force utf8 read data reload(sys); sys.setdefaulte
ncoding("utf8") # Get an instance of a logger logger = logging.getLogger(__name__) class DeleteUserForm(forms.Form, FormCommonUtils): user_id = forms.IntegerField(label='User id', required=True) # list of validator for this form custom_validation_list = ( 'check_all_fields_valid', ) def...
alfredodeza/ceph-doctor
ceph_medic/check.py
Python
mit
2,944
0.000679
import sys import ceph_medic import logging from ceph_medic import runner, collector from tambo import Transport logger = logging.getLogger(__name__) def as_list(string): if not string: return [] string = string.strip(',') # split on commas string = string.split(',') # strip spaces ...
lp = "Run checks for all the configured nodes in a cluster or hosts file" long_help = """ check: Run for all the configured nodes in the configuration Options: --ignore Comma-separated list of errors and warnings to ignore. Loaded Config Path: {config_path} Configured Nodes: {configured_nodes} ...
, parse=True): self.argv = argv or sys.argv @property def subcommand_args(self): # find where `check` is index = self.argv.index('check') # slice the args return self.argv[index:] def _help(self): node_section = [] for daemon, node in ceph_medic.conf...
julie-anderson/python_learning_samples
python_range.py
Python
mit
219
0.013699
# python_range.py # J.M. Anderson # sample of range function print "range(10): "
, range(10) print "range(10, 20): ", range(10,20) print "range(2, 30, 6): ", range(2,30,6) print "range(
20, 10, -2): ", range(20, 10, -2)
marzique/cs50_finance
sqlquery.py
Python
mit
382
0.007853
from cs50 import SQL from flask import session from helpers import usd db = SQL("sqlite:
///finance.db") def get_cash(): return float(db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])[0]["cash"]) def get_username():
return db.execute("SELECT username FROM users WHERE id = :id", id=session["user_id"] )[0]["username"]
fy2462/apollo
modules/tools/car_sound/car_sound.py
Python
apache-2.0
2,085
0.000959
#!/usr/bin/env python ############################################################################### # Copyright 2017 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy ...
ode """ rospy.init_node('car_sound', anonymous=True) sound = CarSound() time.sleep(1) sound.soundhandle.play(SoundRequest.NEEDS_UNPLUGGING) rospy.Subscriber('/apollo/carsound', String, sound.call
back_sound) rospy.spin() if __name__ == '__main__': main()
Kalimaha/simple_flask_blueprint
simple_flask_blueprint/rest/blueprint_rest.py
Python
gpl-2.0
299
0.003344
from flask import Blueprint from simple_flask_blueprint.core.
blueprint_core import say_hallo bp = Blueprint('simple_flask_blueprint', __name__) @bp.route('/') def say_hall
o_service(): return say_hallo() @bp.route('/<name>/') def say_hallo_to_guest_service(name): return say_hallo(name)
daizhengy/RDS
trove/tests/fakes/__init__.py
Python
apache-2.0
752
0
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #
Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the...
nts a fake version of the models code so that the server can be stood up and run under test quickly. """
ramusus/django-facebook-comments
setup.py
Python
bsd-3-clause
1,122
0
from setuptools import setup, find_packages setup( name='django-facebook-comments', version=__import__('facebook_comments').__version__, description='Django implementation for Facebook Graph API Comments', long_description=open('RE
ADME.md').read(), author='ramusus', author_email='[email protected]',
url='https://github.com/ramusus/django-facebook-comments', download_url='http://pypi.python.org/pypi/django-facebook-comments', license='BSD', packages=find_packages(), include_package_data=True, zip_safe=False, # because we're including media that Django needs install_requires=[ 'dj...
Tayamarn/socorro
socorro/signature/__main__.py
Python
mpl-2.0
9,386
0.002664
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import print_function import argparse import csv import logging import logging.config import os import ...
te in notes: print(' %s' % note) class CSVOutput(OutputBase): def __enter__(self): self.out = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL) self.out.writerow(['crashid', 'old', 'new', 'same?', 'notes']) return self def __exit__(self, exc_type, exc_value, trace...
rash_id, old_sig, new_sig, notes): self.out.writerow([crash_id, old_sig, new_sig, str(old_sig == new_sig), notes]) def fetch(endpoint, crash_id, api_token=None): kwargs = { 'params': { 'crash_id': crash_id } } if api_token: kwargs['headers'] = { 'Aut...
MayankAgarwal/euler_py
002/euler002.py
Python
mit
236
0.021186
T = int(raw
_input()) for test in xrange(T): N = int(raw_input()) a, b, result = 0, 1, 0 c = a+b while c < N: if c%2 == 0: result += c a,b = b,c c = a+b
print result
BryanQuigley/sos
sos/report/plugins/monit.py
Python
gpl-2.0
2,464
0
# Copyright (C) 2015 Red Hat, Inc., # Pablo Iranzo Gomez <[email protected]> # This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of ...
*******" ) self.do_file_sub(file, r"USERNAME (\w)+", r"USERNAME ********" ) self.do_file_sub(file,
r"PASSWORD (\w)+", r"PASSWORD ********" ) # vim: et ts=4 sw=4
shennjia/weblte
R12_36211/PRB.py
Python
mit
4,004
0.011489
__author__ = 'shenojia' import sys sys.path.insert(0, '.') sys.path.insert(0, '..') from R12_36xxx.HighLayer import * from R12_36211.REG import REG from math import floor from matplotlib.path import Path from matplotlib.patches import PathPatch from xlsxwriter.worksheet import Worksheet class PRB: """ Resource ...
vertices = [] codes = [] bottom = 0 left = 0 width = 0 height = 0 if subFrameTypeName == 'D': bottom = self.n__PRB * conf.N__sc___RB_DL left = 0 width = conf.N__symb___DL height = conf.N__sc___RB_DL if subFrameTy...
e == 'U': bottom = self.n__PRB * conf.N__sc___RB_UL left = 0 width = conf.N__symb___UL height = conf.N__sc___RB_UL if subFrameTypeName == 'S': if n__s %1 == 0: bottom = self.n__PRB * conf.N__sc___RB_DL left = 0 ...
thydeyx/LeetCode-Python
Queue_Reconstruction_by_Height.py
Python
mit
1,637
0.0281
# -*- coding:utf-8 -*- # # Author : TangHanYi # E-mail : [email protected] # Create Date : 2016-11-23 04:33:03 PM # Last modified : 2016-11-23 04:59:02 PM # File Name : Queue_Reconstruction_by_Height.py # Desc : """ #we have list of persons represented as [height, key] as input #First fill th...
y. eg: [7,0],[6,1],[7,1],[7,2],[6,5] #so on more explanation: #First sort the input list in descending order of heights and ascending order of keys #now iterate ov
er the list and insert each person into answer array at index same as key of person. eg: input : [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] sort input: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4] iterate over sorted array and insert each person at index same as key of the person answer array grows like this for each ite...
Pabsm94/HyperPlume
testing/tests_SSM/test_SSM.py
Python
mit
5,920
0.050845
# -*- coding: utf-8 -*- """ Created on Wed Mar 23 17:18:54 2016 @author: pablo """ import os dir_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import sys sys.path.append(dir_path) #change to src from src import np,unittest,SSM,type_parks,type_korsun,type_ashkenazy,Hyperplum...
plume().simple_plasma(1,1,1,1) Z_span = np.linspace(0,100,500) eta_0 = np.linspace(0,40,500) Plume = type_parks() Plume1 = type_parks(P,30,0.3,Z_span,eta_0,0.5) self.assertIsNotNone(Plume,Plume1) # test type_ interface. ...
ume3 = type_korsun(P1,30,0.3,Z_span,eta_0,0.5) Plume4 = type_ashkenazy(P1,30,0.3,Z_span,eta_0,0.5) self.assertIsNone(Plume2,Plume4) # test validity of Gamma value for the different plume types. self.assertIsNotNone(Plume3) nu = nu = 1 / (1 + 0.047 * e...
gary-pickens/HouseMonitor
housemonitor/outputs/zigbee/zigbeeoutputstep.py
Python
mit
2,202
0.012262
''' Created on 2012-11-06 @author: Gary ''' from housemonitor.steps.abc_step import abcStep from housemonitor.lib.constants import Constants from housemonitor.lib.hmqueue import HMQueue import random class ZigBeeOutputStep( abcStep ): ''' This object should be started with with the COSM thread and hang arou...
:type value: int, float, string, etc :param data: a dictionary containing more information about the value. :param listeners: a list of the subscribed routines to send the data to :returns: new_value, new_data, new_listeners :rtype: int, dict, listeners :raises: ValueError...
ants.DataPacket.ID] = int( random.random() * 255.0 ) data[Constants.DataPacket.value] = value data[Constants.DataPacket.listeners] = listeners self.queue.transmit( data, self.queue.THREE_QUARTERS_PRIORITY ) self.logger.debug( "ZigBee Step data transmitted to ZigBee thread: value = {} dat...
thunderboltsid/stampman
stampman/tests/test_services.py
Python
mit
1,776
0
import unittest import os from stampman.services import pool, sendgrid, mailgun from stampman.helpers import config_, mail_ class PoolServiceTest(unittest.TestCase): def test_creation(self): pool.PooledService() class TestSendgridEmailService(unittest.TestCase): def setUp(self): self._confi...
domain=self._domain) self._email = mail_.Email(sender=("Test", "[email protected]"), recipients=["[email protected]"],
subject="test", content="test_sendgrid") def test_send_email(self): self._service.send_email(self._email) class TestMailgunEmailService(unittest.TestCase): def setUp(self): self._config = config_.ServiceConfig("sendgrid", ...
toastar/Python-Segy-Bandpass
freq.py
Python
bsd-2-clause
1,915
0.031854
from numpy import sin, linspace, pi, array, empty from pylab import plot, show, title, xlabel, ylabel, subplot from scipy import fft, arange, signal from obspy.segy.core import readSEGY # # Input Parameters Block # filename='test.sgy'; Lowcut = 8 # Low frequency Highcut = 60 # High frequency or...
(Y),'r') xlabel('Freq (Hz)') ylabe
l('|Y(freq)|') # End Function space and begin main section. segy = readSEGY(filename) Data = segy.traces[0].data # This pulls the first trace strips the header and plots a numpy array of the data. Fs = 250.0; # sampling rate ( Samples per second.) datalen = len(Data) #Gets the length of the trace count = arang...
Tungul/pythonplayground
switch.py
Python
mit
2,791
0.005016
# Got this from http://code.activestate.com/recipes/410692/ # This class provides the functionality we want. You only need to look at # this if you want to know how this works. It only needs to be defined # once, no need to muck around with its internals. class switch(object): def __init__(self, value): se...
def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for v1.5, see below self.fall = True return True else: return False # The following...
ionary, # but is included for its simplicity. Note that you can include statements # in each suite. v = 'ten' for case in switch(v): if case('one'): print 1 break if case('two'): print 2 break if case('ten'): print 10 break if case('eleven'): print...
wsqhubapp/learning_log
learning_logs/admin.py
Python
apache-2.0
163
0
fr
om django.contrib import admin # Register your models here. from learning_logs.models import Topic, Entry admin.site.register(Topic) admin.site.register(Entry)
kostyll/kivy-okapi
okapi/screen_manager.py
Python
mit
5,182
0.001351
from __future__ import print_function, absolute_import, unicode_literals # Kivy from kivy.clock import Clock from kivy.uix.boxlayout import BoxLayout class ScreenManager(BoxLayout): """ Class that handles toggling between windows. So that's managing the loading screen, game screen, victory screen, high s...
f render(self): self.clear_widgets() widget = self.current_screen if hasattr(self.curre
nt_screen, 'container'): widget = self.current_screen.container self.add_widget(widget) @property def current_screen(self): """ Property used to wrap whichever screen is current to facilitate the swapping of screens and also automatically directing all user ...
karthik-sethuraman/ONFOpenTransport
RI/flask_server/tapi_server/controllers/tapi_photonic_media_controller.py
Python
apache-2.0
88,036
0
import connexion import six from tapi_server.models.tapi_photonic_media_application_identifier import TapiPhotonicMediaApplicationIdentifier # noqa: E501 from tapi_server.models.tapi_photonic_media_central_frequency import TapiPhotonicMediaCentralFrequency # noqa: E501 from tapi_server.models.tapi_photonic_media_fec...
c # noqa: E501 from tapi_server.models.tapi_photonic_media_media_channel_service_interface_point_spec import TapiPhotonicMediaMediaChannelServiceInterfacePointSpec # noqa: E501 from tapi_server.models.tapi_photonic_media_ots_connection_end_point_spec import TapiPhotonicMediaOtsConnec
tionEndPointSpec # noqa: E501 from tapi_server.models.tapi_photonic_media_otsi_assembly_connection_end_point_spec import TapiPhotonicMediaOtsiAssemblyConnectionEndPointSpec # noqa: E501 from tapi_server.models.tapi_photonic_media_otsi_capability_pac import TapiPhotonicMediaOtsiCapabilityPac # noqa: E501 from tapi_se...
googlearchive/simian
src/simian/mac/admin/xsrf.py
Python
apache-2.0
2,004
0.009481
#!/usr/bin/env python # # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
timestamp=None, time_=time): """Validate an XSRF token.""" if not token: return False if not user: user = users.get_current_user().email() if not timestamp: try: _, timestr = base64.urlsafe_b64decode(str(token)).rsplit( XSRF_DELIMITER, 1) timestamp = float(timestr) except (...
f timestamp + XSRF_VALID_TIME < time_.time(): return False if token != XsrfTokenGenerate(action, user, timestamp): return False return True
marcusbuffett/command-line-chess
src/MoveNode.py
Python
mit
1,936
0
class MoveNode: def __init__(self, move, children, parent): self.move = move self.children = children self.parent = parent self.pointAdvantage = None self.depth = 1 def __str__(self): stringRep = "Move : " + str(self.move) + \ " Point advanta...
e:
return highestNode def getDepth(self): depth = 1 highestNode = self while True: if highestNode.parent is not None: highestNode = highestNode.parent depth += 1 else: return depth
mohsraspi/mhscs14
jay/wowobsidian.py
Python
gpl-2.0
437
0.025172
import minecraft as minecraft import random import time x = 128 y = 2 z
= 128 mc = minecraft.Minecraft.create() while y < 63: j = mc.getBlock(x,y,z) if j == 0: mc.setBlock(x,y,z,8) z = z - 1 if z <= -128: z = 128 x = x - 1 if x<= -128: x =...
y = y + 1
lintzc/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/pg_twophase/switch_ckpt_serial/cleanup_sql/test_cleanup.py
Python
apache-2.0
845
0.001183
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ...
ither express or implied. See the License for the specific language governing permissions
and limitations under the License. """ from mpp.models import SQLConcurrencyTestCase ''' Cleanup sqls ''' class TestCleanupClass(SQLConcurrencyTestCase): ''' Cleanup sqls before the next test. '''
JeromeErasmus/browserstack_automate
automate/server/user/views.py
Python
apache-2.0
2,112
0.009943
# automate/server/user/views.py ################# #### imports #### ################# #from flask import render_template, Blueprint, url_for, \ # redirect, flash, request #from flask_login import login_user, logout_user, login_required #from automate.server import bcrypt, db #from automate.server import db #from...
form = LoginForm(request.form) # if form.validate_on_submit(): # user = User.query.filter_by(email=form.email.data).first() # if user: # #if user and bcrypt.check_password_hash( # # user.password, request.form['password']): # # login_user(user) # flash('You are...
s') # return redirect(url_for('user.members')) # else: # flash('Invalid email and/or password.', 'danger') # return render_template('user/login.html', form=form) # return render_template('user/login.html', title='Please Login', form=form) # # #@user_blueprint.route('/logout') ...
inuitwallet/bippy
num/rand.py
Python
mit
2,418
0.02895
import hashlib import num.elip as elip import num.enc as enc def clockbase(): """ 256 bit hex: 4 x 16 byte long from float using clock (process time) + time (UTC epoch time) Note: not enough clock precision on Linuxes to be unique between two immediate calls """ from struct import pack from time import time, cl...
lockst
r).digest()[1+(lbit % 29): 33+(lbit % 29)] randhash = hashlib.sha512(enc.encode(osrnd.getrandbits(512), 256)).digest()[0+(lbit % 31): 32+(lbit % 31)] privkey ^= enc.decode(randhash, 256) ^ enc.decode(clock32, 256) ^ osrndi.getrandbits(256) osrnd = SystemRandom(hashlib.sha512(clock32 + randhash + entstr).digest...
remcohaszing/pywakeonlan
docs/conf.py
Python
mit
534
0
""" Configuratio
n for the documentation generation. """ import pkg_resources project = "wakeonlan" _dist = pkg_resources.get_distribution(project) version = _dist.version release = _dist.version copyright = "2012, Remco Haszing" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", ] ...
_rtd_theme"
rojassergio/Aprendiendo-a-programar-en-Python-con-mi-computador
Programas_Capitulo_02/Cap02_pagina_25_comp_interactiva.py
Python
mit
746
0.014765
''' @author: Sergio Rojas @contact: rr.sergio@gma
il.com -------------------------- Contenido bajo Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE) http://creativecommons.org/licenses/by-nc-sa/3.0/ve/ Creado en abril 19, 2016 ''' print(3+5) print(2-6) print(2*7) print(6/2) print(1/3) print(1.0/3) print(((2 + 7*(234 -15)+673)*775)/(5+890.0 -...
nt(6.78**30) print(8.647504884825773*1e+24 - 8.647504884825773*10**24) print(1e+2) print(1e2) print(1e-2) print(2e4) print(4**(1./2.)) print(4**0.5) print(8**(1./3.)) print(8**0.3333)
ericmjl/bokeh
tests/unit/bokeh/plotting/test__lengends.py
Python
bsd-3-clause
8,707
0.004249
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
"baz"), legend) is None assert bpl._find_legend_item(dict(value="foo"), legend)
is legend.items[0] assert bpl._find_legend_item(dict(field="bar"), legend) is legend.items[1] class Test__handle_legend_deprecated(object): @pytest.mark.parametrize('arg', [1, 2.7, None, False, [], {'junk': 10}, {'label': 'foo', 'junk': 10}, {'value': 'foo', 'junk': 10}]) def test_bad_arg(self, arg) -> N...
geosolutions-it/ckanext-geonode
ckanext/geonode/harvesters/mappers/base.py
Python
gpl-2.0
14,238
0.002107
import json import logging from string import Template from ckan.logic import NotFound, get_action from ckan import model, plugins as p from ckan.plugins.toolkit import _ from ckan.model import Session from ckanext.harvest.harvesters import HarvesterBase from ckanext.harvest.model import HarvestObject from ckanext....
n'] = doc.doc_type() # # # Prepare the data downloader # resource[RESOURCE_DOWNLOADER] = \ # GeonodeDataDownloader(harvest_object.source.url, doc.id(), doc.doc_file()) # # package_dict['resources'].append(resource) return package_dict, extras def parse_common(harvest_object, georesour...
ject (with access to job and source objects) :type harvest_object: HarvestObject :param georesource: a resource (Layer or Map) from GeoNode :type georesource: a GeoResource (Map or Layer) :returns: A dataset dictionary (package_dict) :rtype: dict ''' tags = [] for tag in georesource.k...
jayceyxc/hue
desktop/core/ext-py/cx_Oracle-5.2.1/test/uCursor.py
Python
apache-2.0
10,123
0.005334
"""Module for testing cursor objects.""" import cx_Oracle class TestCursor(BaseTestCase): def testExecuteNoArgs(self): """test executing a statement without any arguments""" result = self.cursor.execute(u"begin null; end;") self.failUnlessEqual(result, None) def testExecuteNoStatemen...
cursor.execute(u"truncate table Te
stExecuteMany") rows = [ [n] for n in range(225) ] self.cursor.arraysize = 100 statement = u"insert into TestExecuteMany (IntCol) values (:1)" self.cursor.prepare(statement) self.cursor.executemany(None, rows) self.connection.commit() self.cursor.execute(u"select ...
FESOM/pyfesom
tools/scalar2geo.py
Python
mit
12,219
0.009412
import sys import os from netCDF4 import Dataset, MFDataset, num2date import numpy as np sys.path.append(os.path.join(os.path.dirname(__file__), "../")) import pyfesom as pf import joblib from joblib import Parallel, delayed import json from collections import OrderedDict import click from mpl_toolkits.basemap import m...
topo)((lonreg2, latreg2)) distances, inds = None, None elif interp == 'cubic': points = np.vstack((mesh.x2, mesh.y2)).T qh = qhull.Delaunay(points) topo_interp = CloughTocher2DInterpolator(qh, mesh.topo)((lonreg2, latreg2)) distances, inds = None, None mdata = maskoceans...
latreg2, topo_interp, resolution = 'h', inlands=False) topo = np.ma.masked_where(~mdata.mask, topo_interp) # Backend is switched to threading for linear and cubic interpolations # due to problems with memory mapping. # One have to test threading vs multiprocessing. if (interp == 'linear') or (...
obi-two/Rebelion
data/scripts/templates/object/draft_schematic/community_crafting/component/shared_lightweight_turret_hardware.py
Python
mit
485
0.045361
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/community_crafting/component/shared_lightweight_turret_h
ardware.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MO
DIFICATIONS #### #### END MODIFICATIONS #### return result
amaggi/bda
chapter_03/sample_via_cdf.py
Python
gpl-2.0
402
0.002488
from scipy.integrate import cumtrapz from scipy.int
erpolate import interp1d from scipy.stats import uniform def sample_via_cdf(x, p, nsamp): # get normalized cumulative distribution cdf = cumtrapz(p, x, initial=0) cdf = cdf/cdf.max() # get interpolator interp = int
erp1d(cdf, x) # get uniform samples over cdf cdf_samp = uniform.rvs(size=nsamp) return interp(cdf_samp)
junqueira/balance
finance/migrations/0004_remove_extract_provider.py
Python
mit
355
0
# -*- coding: utf-8 -*- from __future__ import unicode_l
iterals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('finance', '0003_auto_20140929_0130'), ] operations = [
migrations.RemoveField( model_name='extract', name='provider', ), ]
Luindil/PeakThis
peakthis/model/PickModel.py
Python
gpl-3.0
2,797
0.002145
# -*- coding: utf8 -*- __author__ = 'Clemens Prescher' class PickModel(): num_pick_models = 0 def __init__(self, number_picks): self.id = PickModel.num_pick_models PickModel.num_pick_models += 1 self._prefix = "id"+str(self.id)+"_" self.current_pick = 0 self.number_p...
n self.eval(self.parameters, x=x) def eval(self, *args, **kwargs): raise NotImplementedError def make_params(self, *args, **kwargs): raise NotImplemente
dError def __deepcopy__(self, memo): cls = self.__class__ result = cls() for parameter_name in self._param_root_names: # print result.parameters # print self.parameters result_param = result.get_param("{}{}".format(result._prefix, parameter_name)) ...
iulian787/spack
var/spack/repos/builtin/packages/nicstat/package.py
Python
lgpl-2.1
962
0.00104
# C
opyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Nicstat(MakefilePackage, SourceforgePackage): """ Nicstat is a Solaris and Linux command-...
izes and more. """ homepage = "https://github.com/scotte/nicstat" sourceforge_mirror_path = "nicstat/nicstat-1.95.tar.gz" version('1.95', sha256='c4cc33f8838f4523f27c3d7584eedbe59f4c587f0821612f5ac2201adc18b367') def edit(self, spec, prefix): copy('Makefile.Linux', 'makefile') fil...
jhjguxin/PyCDC
Karrigell-2.3.5/webapps/demo/wiki/search.py
Python
gpl-3.0
1,781
0.021898
# search engine import re import posixpath import BuanBuan import wikiBase db = wikiBase.db caseSensitive=QUERY.has_key("caseSensitive") fullWord=QUERY.has_key("fullWord") words=_words if fullWord: words=r"\W"+words+r"\W" sentence="[\n\r.?!].*"+words+".*[\n\r.?!]" if caseSensitive: se...
nce=sentence[re.search("[^!]",sentence).start():] sentence=wordPattern.sub(replace,sentence) # elimina
tes leading char "!" print sentence+"<br>" deb=searchObj.end()-len(words)+1 occ+=1 flag=1 if not occ: print "%s not found" %_words print '<a href="index.pih">Back</a>'
antoinecarme/pyaf
tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_MovingAverage_Seasonal_DayOfMonth_MLP.py
Python
bsd-3-clause
169
0.047337
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( [
'Quantization'] , ['MovingAverage'] , ['Seasonal_DayOfMonth']
, ['MLP'] );
wylieswanson/agilepyfs
fs/remote.py
Python
bsd-3-clause
26,904
0.008772
""" fs.remote ========= Utilities for interfacing with remote filesystems This module provides reusable utility functions that can be used to construct FS subclasses interfacing with a remote filesystem. These include: * RemoteFileBuffer: a file-like object that locally buffers the contents of ...
e() super(RemoteFileBuffer,self).__init__(wrapped_file,mode) # FIXME: What if mode with position on eof? if "a" in mode: # Not good enough... self.seek(0, SEEK_END) def __del__(self): # Don't try to close a partially-constructed file if "_lock" in se...
.__dict__: if not self.closed: try: self.close() except FSError: pass def _write(self,data,flushing=False): with self._lock: # Do we need to discard info from the buffer? toread = len(data) - (self....
eandersson/amqpstorm
amqpstorm/tests/functional/management/test_basic.py
Python
mit
2,514
0
from amqpstorm.management import ManagementApi from amqpstorm.message import Message from amqpstorm.tests import HTTP_URL from amqpstorm.tests import PASSWORD from amqpstorm.tests import USERNAME from amqpstorm.tests.functional.utility import TestFunctionalFramework from amqpstorm.tests.functional.utility import setup ...
result = api.basic.get(self.queue_name, requeue=True) sel
f.assertIsInstance(result, list) self.assertIsInstance(result[0], Message) self.assertEqual(result[0].body, self.message) # Make sure the message was re-queued. self.assertTrue(api.basic.get(self.queue_name, requeue=False)) @setup(queue=True) def test_api_basic_get_message_to_d...
Q-Leap-Networks/pyslurm
examples/listdb_reservations.py
Python
gpl-2.0
866
0.005774
#!/usr/bin/env python import
time import pyslurm def reservation_display(reservation): if reservation: for key,value in reservation.items(): print("\t{}={}".format(key, value)) if __name__ == "__main__": try: end = time.time() start = end - (30*24*60*60) print("start={}, end={}".format(start, e...
set_reservation_condition(start, end) reservations_dict = reservations.get() if len(reservations_dict): for key, value in reservations_dict.items(): print("{} Reservation: {}".format('{', key)) reservation_display(value) print("}") else...
schae234/cob
docs/conf.py
Python
mit
5,863
0.000682
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # cob documentation build configuration file, created by # sphinx-quickstart on Sun Jan 7 18:09:10 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autoge...
ey produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages
. See the documentation for # a list of builtin themes. # #html_theme = 'alabaster' html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any ...
hassaanm/stock-trading
src/pybrain/rl/environments/ode/instances/acrobot.py
Python
apache-2.0
1,031
0.008729
__author__ = 'Frank Sehnke, [email protected]' from pybrain.rl.environments.ode import ODEEnvironment, sensors, actuators import imp from scipy import array class AcrobotEnvironment(ODEEnvironment): def __init__(self, renderer=True, realtime=True, ip="127.0.0.1", port="21590", buf='16384'): ODEEnvironment....
, ip, port, buf) # load model file self.loadXODE(imp.find_module('pybrain')[1] + "/rl/environments/ode/models/acrobot.xode") # standard sensors and actuators self.addSensor(sensors.JointSensor()) self.addSensor(sensors.JointVelocitySensor()) self.addActuator(actuators.Jo...
ct- and obsLength, the min/max angles and the relative max touques of the joints self.actLen = self.indim self.obsLen = len(self.getSensors()) self.stepsPerAction = 1 if __name__ == '__main__' : w = AcrobotEnvironment() while True: w.step() if w.stepCounter == 1000: w.r...
Harmon758/discord.py
discord/user.py
Python
mit
13,435
0.002159
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
ss:`str`: Returns the user's display name. For regular users this is just their username, but if they have a guild specific nickname then that is returned instead. """ return self.name def mentioned_in(sel
f, message): """Checks if the user is mentioned in the specified message. Parameters ----------- message: :class:`Message` The message to check if you're mentioned in. Returns ------- :class:`bool` Indicates if the user is mentioned in th...
ViralTexts/vt-passim
scripts/place-cascade.py
Python
apache-2.0
6,658
0.004656
from __future__ import print_function import argparse, re import numpy as np from pyspark import SparkSession from pyspark.sql import Row from pyspark.sql.functions import col, datediff, lit, sum as gsum from pyspark.ml.feature import CountVectorizer, VectorAssembler def pairFeatures(sseries, dseries, sday, dday): ...
res.append(Row(cluster=long(c[0]), src=s+1, dst=d+1, label=(1 if dst.day > src.day else 0), longer=growth if growth > 0 else 0.0, shorter=abs(growth) if growth < 0 else 0.0, raw=pairFeatures(src...
te((np.zeros((size+1, 1)), np.concatenate((np.zeros((1, size)), m), axis=0)), axis=1) def laplaceGradient(L): tinv = padUpLeft(np.transpose(np.linalg.inv(L[1:, 1:]))) return tinv - tinv.diagonal() ## Should figure out how to reuse this in clusterGradients d...
aronsky/home-assistant
homeassistant/components/tasmota/device_automation.py
Python
apache-2.0
1,937
0.001549
"""Provides device automations for Tasmota.""" from hatasmota.const import AUTOMATION_TYPE_TRIGGER from hatasmota.models import DiscoveryHashType from hatasmota.trigger import TasmotaTrigger from homeassistant.config_entries import ConfigEntry from homeassistant.core import Event, HomeAssistant from homeassistant.hel...
ations(hass, event.data["device_id"]) async def async_discover( tasmota_automation: TasmotaTrigger, discovery_hash: DiscoveryHashType ) -> None: """Discover and add a Tasmota device automation.""" if tasmota_automation.automation_type == AUTOMATION_TYPE_TRIGGER: await device...
hass, tasmota_automation, config_entry, discovery_hash ) hass.data[ DATA_REMOVE_DISCOVER_COMPONENT.format("device_automation") ] = async_dispatcher_connect( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format("device_automation"), async_discover, ) hass.data[DATA_...
yuanagain/seniorthesis
venv/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py
Python
mit
93,454
0.001316
#!/usr/bin/python # axes3d.py, original mplot3d version by John Porter # Created: 23 Sep 2005 # Parts fixed by Reinier Heeres <[email protected]> # Minor additions by Ben Axelrod <[email protected]> # Significant updates and revisions by Ben Root <[email protected]> """ Module containing Axes3D, an object which...
fault 30) *zscale* [%(scale)s] *sharez* Other axes to share z-limits with ================ ========================================= .. versionadded :: 1.2.1 *sharez* ''' % {'scale': ' | '.join([repr(x) for x in mscale.get_scale_names()])...
s.pop('azim', -60) self.initial_elev = kwargs.pop('elev', 30) zscale = kwargs.pop('zscale', None) sharez = kwargs.pop('sharez', None) self.xy_viewLim = unit_bbox() self.zz_viewLim = unit_bbox() self.xy_dataLim = unit_bbox() self.zz_dataLim = unit_bbox() #...
sattila83/Robocar
input_parser.py
Python
mit
369
0.0271
#!/usr/bin/env python from posit
ion import Position class InputParser: @staticmethod def parse(filePath): positions = [] with open(
filePath, 'r') as file: for line in file.read().splitlines(): parts = [part.strip() for part in line.split(',')] if 2 == len(parts): positions.append(Position(float(parts[0]), float(parts[1]))) return positions