commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
f9c51c592483ab08417d4df33898d32f7700ffe9
sal/management/commands/update_admin_user.py
sal/management/commands/update_admin_user.py
''' Creates an admin user if there aren't any existing superusers ''' from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from optparse import make_option class Command(BaseCommand): help = 'Creates/Updates an Admin user' def add_arguments(self, parser): parser.add_argument('--username', action='store', dest='username', default=None, help='Admin username') parser.add_argument('--password', action='store', dest='password', default=None, help='Admin password') def handle(self, *args, **options): username = options.get('username') password = options.get('password') if not username or not password: raise StandardError('You must specify a username and password') # Get the current superusers su_count = User.objects.filter(is_superuser=True).count() if su_count == 0: # there aren't any superusers, create one user, created = User.objects.get_or_create(username=username) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() print('{0} updated'.format(username)) else: print('There are already {0} superusers'.format(su_count))
"""Creates an admin user if there aren't any existing superusers.""" from optparse import make_option from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Creates/Updates an Admin user' def add_arguments(self, parser): parser.add_argument('--username', action='store', dest='username', default=None, help='Admin username') parser.add_argument('--password', action='store', dest='password', default=None, help='Admin password') def handle(self, *args, **options): username = options.get('username') password = options.get('password') if not username or not password: raise CommandError('You must specify a username and password') # Get the current superusers su_count = User.objects.filter(is_superuser=True).count() if su_count == 0: # there aren't any superusers, create one user, created = User.objects.get_or_create(username=username) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() print(f'{username} updated') else: print(f'There are already {su_count} superusers')
Fix exception handling in management command. Clean up.
Fix exception handling in management command. Clean up.
Python
apache-2.0
salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal
a5f60d664e7758b113abc31b405657952dd5eccd
tests/conftest.py
tests/conftest.py
import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password'])
import json import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password']) @pytest.fixture def questions(): qs = [] for root, dirs, files in os.walk('tests/json/questions'): for filename in files: filepath = os.path.join(root, filename) try: qs.append(json.load(open(filepath))) except ValueError: raise ValueError('Expected {} to contain valid JSON'.format(filepath)) return qs
Implement test data JSON loader
Implement test data JSON loader
Python
mit
sherlocke/pywatson
904db705daf24d68fcc9ac6010b55b93c7dc4544
txircd/modules/core/accounts.py
txircd/modules/core/accounts.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None accounts = Accounts()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html irc.RPL_LOGGEDIN = "900" irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet), ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): if key == "account": if value is None: user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") else: user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
Add automatic sending of 900/901 numerics for account status
Add automatic sending of 900/901 numerics for account status
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
f3c1e5bdf25b46e96a77221ace7438eb3b55cb05
bluebottle/common/management/commands/makemessages.py
bluebottle/common/management/commands/makemessages.py
import json import codecs import tempfile from django.core.management.commands.makemessages import Command as BaseCommand class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'), ('geo', 'geo_data.json'), ] def handle(self, *args, **kwargs): with tempfile.NamedTemporaryFile(dir='bluebottle', suffix='.py') as temp: for app, file in self.fixtures: with open('bluebottle/{}/fixtures/{}'.format(app, file)) as fixture_file: for string in [ fixture['fields']['name'].encode('utf-8') for fixture in json.load(fixture_file)]: temp.write('pgettext("{}-fixtures", "{}")\n'.format(app, string)) temp.flush() return super(Command, self).handle(*args, **kwargs)
import json import codecs import tempfile from django.core.management.commands.makemessages import Command as BaseCommand class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'), ('geo', 'geo_data.json'), ] def handle(self, *args, **kwargs): with tempfile.NamedTemporaryFile(dir='bluebottle', suffix='.py') as temp: for app, file in self.fixtures: with open('bluebottle/{}/fixtures/{}'.format(app, file)) as fixture_file: strings = [ fixture['fields']['name'].encode('utf-8') for fixture in json.load(fixture_file) ] for string in strings: temp.write('pgettext("{}-fixtures", "{}")\n'.format(app, string)) temp.flush() return super(Command, self).handle(*args, **kwargs)
Make loop a little more readable
Make loop a little more readable
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
ecc56eec0ebee4a93d5052280ae5d8c649e1e6da
tests/test_api.py
tests/test_api.py
from nose.tools import eq_ import mock from lcp import api @mock.patch('lcp.api.requests.request') def _assert_calls_requests_with_url(original_url, expected_url, request_mock): api.Client('BASE_URL').request('METHOD', original_url) expected_headers = {'Content-Type': 'application/json'} eq_(request_mock.call_args_list, [ mock.call('METHOD', expected_url, data='{}', headers=expected_headers)]) def test_request_does_not_alter_absolute_urls(): for absolute_url in [ 'http://www.points.com', 'https://www.points.com', ]: yield _assert_calls_requests_with_url, absolute_url, absolute_url def test_request_adds_base_url_to_relative_urls(): for absolute_url in [ 'some/relative/path/', '/some/absolute/path', ]: yield _assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url
from nose.tools import eq_ import mock from lcp import api class TestApiClient(object): def setup(self): self.client = api.Client('BASE_URL') def test_request_does_not_alter_absolute_urls(self): for absolute_url in [ 'http://www.points.com', 'https://www.points.com', ]: yield self._assert_calls_requests_with_url, absolute_url, absolute_url def test_request_adds_base_url_to_relative_urls(self): for absolute_url in [ 'some/relative/path/', '/some/absolute/path', ]: yield self._assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url @mock.patch('lcp.api.requests.request') def _assert_calls_requests_with_url(self, original_url, expected_url, request_mock): self.client.request('METHOD', original_url) expected_headers = {'Content-Type': 'application/json'} eq_(request_mock.call_args_list, [ mock.call('METHOD', expected_url, data='{}', headers=expected_headers)])
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109
Python
bsd-3-clause
bradsokol/PyLCP,Points/PyLCP,bradsokol/PyLCP,Points/PyLCP
7bdfb1ef77d23bc868434e8d74d6184dd68c0a6e
tests/test_api.py
tests/test_api.py
# coding: utf-8 """ Test the backend API Written so that after creating a new backend, you can immediately see which parts are missing! """ from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): comp = inspect.getargspec(HttpBackend.go) for t in derived_types(): self.assertEqual(comp, inspect.getargspec(t.go), "Type %(t)s does not adhere to the spec %(s)s" % dict(t=t, s=comp)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass
# coding: utf-8 """ Test the backend API Written so that after creating a new backend, you can immediately see which parts are missing! """ from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): def just_args(s): return dict(args=s.args, varargs=s.varargs) comp = just_args(inspect.getargspec(HttpBackend.go)) for t in derived_types(): sig = just_args(inspect.getargspec(t.go)) self.assertEqual(comp, sig, "Type %(t)s does not adhere to the spec %(spec)s with signature %(sig)s" % dict(t=t, spec=comp, sig=sig)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass
Improve API test by only comparing args and varargs.
Improve API test by only comparing args and varargs.
Python
agpl-3.0
ahri/pycurlbrowser
cfaaf421bb9627f1741a9ef4074517fd5daaec86
wsgi/setup.py
wsgi/setup.py
import subprocess import sys import setup_util import os def start(args): subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gunicorn' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) except OSError: pass return 0
import subprocess import sys import setup_util import os def start(args): subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w ' + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gunicorn' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) except OSError: pass return 0
Use meinheld worker (same as other Python Frameworks)
wsgi: Use meinheld worker (same as other Python Frameworks)
Python
bsd-3-clause
torhve/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,denkab/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,actframework/FrameworkBenchmarks,denkab/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,doom369/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,testn/FrameworkBenchmarks,khellang/FrameworkBenchmarks,grob/FrameworkBenchmarks,methane/FrameworkBenchmarks,zloster/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jamming/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,dmacd/FB-try1,thousandsofthem/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,herloct/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,methane/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,denkab/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,valyala/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zapov/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,joshk/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Verber/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,herloct/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,testn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,grob/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,khellang/FrameworkBenchmarks,doom369/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zloster/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,torhve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sgml/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sgml/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zloster/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,herloct/FrameworkBenchmarks,methane/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zapov/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,leafo/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,dmacd/FB-try1,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,testn/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,leafo/FrameworkBenchmarks,dmacd/FB-try1,xitrum-framework/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sgml/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sgml/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,leafo/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,denkab/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,joshk/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,testn/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,doom369/FrameworkBenchmarks,dmacd/FB-try1,martin-g/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,doom369/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,khellang/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,grob/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zapov/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,grob/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,herloct/FrameworkBenchmarks,herloct/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jamming/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,methane/FrameworkBenchmarks,zloster/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,joshk/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zapov/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sxend/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,leafo/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,khellang/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,actframework/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,testn/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,leafo/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,torhve/FrameworkBenchmarks,herloct/FrameworkBenchmarks,valyala/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,valyala/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,sgml/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,dmacd/FB-try1,s-ludwig/FrameworkBenchmarks,zloster/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sgml/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,leafo/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,khellang/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zapov/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Verber/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,leafo/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,testn/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,grob/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,torhve/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sgml/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sxend/FrameworkBenchmarks,grob/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,herloct/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,herloct/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sxend/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,testn/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sxend/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,torhve/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,sxend/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,torhve/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,denkab/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zapov/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,valyala/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jamming/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Verber/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,joshk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,grob/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,grob/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,leafo/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zloster/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,actframework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,dmacd/FB-try1,RockinRoel/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,leafo/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,methane/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,dmacd/FB-try1,stefanocasazza/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,grob/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sxend/FrameworkBenchmarks,valyala/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,herloct/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,valyala/FrameworkBenchmarks,torhve/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,methane/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Verber/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sgml/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jamming/FrameworkBenchmarks,methane/FrameworkBenchmarks,methane/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zapov/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zloster/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jamming/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,doom369/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,dmacd/FB-try1,denkab/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,herloct/FrameworkBenchmarks,testn/FrameworkBenchmarks,jamming/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,methane/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Verber/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,grob/FrameworkBenchmarks,joshk/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,joshk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,torhve/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,dmacd/FB-try1,MTDdk/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,grob/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,denkab/FrameworkBenchmarks,doom369/FrameworkBenchmarks,joshk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,leafo/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,Verber/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,methane/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,valyala/FrameworkBenchmarks,jamming/FrameworkBenchmarks,grob/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sxend/FrameworkBenchmarks,actframework/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,joshk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,dmacd/FB-try1,diablonhn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,khellang/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,valyala/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Verber/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,joshk/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,testn/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,testn/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Verber/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zapov/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,dmacd/FB-try1,Jesterovskiy/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zloster/FrameworkBenchmarks,methane/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Verber/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sxend/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,herloct/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,denkab/FrameworkBenchmarks,actframework/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,leafo/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,testn/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,doom369/FrameworkBenchmarks,testn/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,actframework/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,valyala/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,actframework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,valyala/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,doom369/FrameworkBenchmarks,dmacd/FB-try1,valyala/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,grob/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sgml/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,testn/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zloster/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,torhve/FrameworkBenchmarks,testn/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zloster/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,actframework/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,khellang/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,joshk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Verber/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,torhve/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,leafo/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Verber/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,actframework/FrameworkBenchmarks
1d4777f810388ee87cceb01c2b53367723fb3a71
PyFBA/cmd/__init__.py
PyFBA/cmd/__init__.py
from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', 'list_media' ]
from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media from .reactions_to_roles import convert_reactions_to_roles # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', 'list_media', 'convert_reactions_to_roles' ]
Add a function to retrieve roles from reactions
Add a function to retrieve roles from reactions
Python
mit
linsalrob/PyFBA
6fd7f3cb01f621d2ea79e15188f8000c7b6fa361
tools/add_feed.py
tools/add_feed.py
import os from urllib.parse import urlencode, quote from autobit import Client def add_rarbg_feed(client, name, directory, filter_kwargs): url = 'http://localhost:5555/{}?{}'.format( quote(name), urlencode(filter_kwargs) ) return client.add_feed(name, url, directory) def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) if input('rarbg[yn]> ') == 'n': client.add_feed( name, input('url> '), directory ) else: add_rarbg_feed( client, name, directory, eval(input('filter dict> ')) ) if __name__ == '__main__': main()
import os from autobit import Client def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) client.get_torrents() name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) client.add_feed( name, input('url> '), directory ) if __name__ == '__main__': main()
Remove code specific to my system
Remove code specific to my system
Python
mit
Mause/autobit
894203d67e88e8bac8ec4f8948d940789387b648
tests/data/questions.py
tests/data/questions.py
QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { 'questionText': 'When can a union start a strike?' } ]
QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { 'questionText': 'When can a union start a strike?', 'items': 0, 'evidenceRequest': { 'items': 0, 'profile': '' }, 'answerAssertion': '', 'category': '', 'context': '', 'formattedAnswer': '', 'passthru': '', 'synonyms': '', 'lat': '', 'filters': [ { 'filterType': '', 'filterName': '', 'values': '' } ] } ]
Add all blank parameters to sample question
Add all blank parameters to sample question
Python
mit
sherlocke/pywatson
111d0bd356c18d0c028c73cd8c84c9d3e3ae591c
astropy/io/misc/asdf/tags/tests/helpers.py
astropy/io/misc/asdf/tags/tests/helpers.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import os import urllib.parse import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_resolver tag = format_tag(organization, standard, version, name) schema_path = urllib.parse.urlparse(default_resolver(tag)).path with open(schema_path, 'rb') as ff: schema = yaml.load(ff) examples = [] for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=schema_path) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff)
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import os import urllib.parse import urllib.request import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_tag_to_url_mapping from asdf.schema import load_schema tag = format_tag(organization, standard, version, name) uri = asdf.resolver.default_tag_to_url_mapping(tag) r = asdf.AsdfFile().resolver examples = [] schema = load_schema(uri, resolver=r) for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=uri) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff)
Fix ASDF tag test helper to load schemas correctly
Fix ASDF tag test helper to load schemas correctly
Python
bsd-3-clause
pllim/astropy,astropy/astropy,lpsinger/astropy,larrybradley/astropy,StuartLittlefair/astropy,mhvk/astropy,pllim/astropy,MSeifert04/astropy,saimn/astropy,dhomeier/astropy,lpsinger/astropy,pllim/astropy,stargaser/astropy,larrybradley/astropy,larrybradley/astropy,bsipocz/astropy,StuartLittlefair/astropy,astropy/astropy,dhomeier/astropy,bsipocz/astropy,pllim/astropy,astropy/astropy,mhvk/astropy,MSeifert04/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,lpsinger/astropy,mhvk/astropy,astropy/astropy,StuartLittlefair/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,saimn/astropy,stargaser/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,dhomeier/astropy,astropy/astropy,dhomeier/astropy,pllim/astropy,StuartLittlefair/astropy,larrybradley/astropy,bsipocz/astropy,stargaser/astropy,mhvk/astropy,stargaser/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,saimn/astropy,dhomeier/astropy,saimn/astropy,mhvk/astropy,saimn/astropy,MSeifert04/astropy
e2f1787601e7c05c9c5ab2efe26b6d1cb90b2ccb
saleor/account/migrations/0040_auto_20200415_0443.py
saleor/account/migrations/0040_auto_20200415_0443.py
# Generated by Django 3.0.5 on 2020-04-15 09:43 from django.db import migrations def change_extension_permission_to_plugin_permission(apps, schema_editor): permission = apps.get_model("auth", "Permission") users = apps.get_model("account", "User") plugin_permission = permission.objects.filter( codename="manage_plugins", content_type__app_label="plugins" ).first() extension_permission = permission.objects.filter( codename="manage_plugins", content_type__app_label="extensions" ).first() users = users.objects.filter( user_permissions__content_type__app_label="extensions", user_permissions__codename="manage_plugins", ) if not plugin_permission or not extension_permission: return for user in users: user.user_permissions.remove(extension_permission) user.user_permissions.add(plugin_permission) if extension_permission: extension_permission.delete() class Migration(migrations.Migration): dependencies = [ ("account", "0039_auto_20200221_0257"), ("plugins", "0001_initial"), ] operations = [ migrations.RunPython(change_extension_permission_to_plugin_permission), ]
# Generated by Django 3.0.5 on 2020-04-15 09:43 from django.db import migrations def change_extension_permission_to_plugin_permission(apps, schema_editor): permission = apps.get_model("auth", "Permission") users = apps.get_model("account", "User") service_account = apps.get_model("account", "ServiceAccount") plugin_permission = permission.objects.filter( codename="manage_plugins", content_type__app_label="plugins" ).first() extension_permission = permission.objects.filter( codename="manage_plugins", content_type__app_label="extensions" ).first() users = users.objects.filter( user_permissions__content_type__app_label="extensions", user_permissions__codename="manage_plugins", ) service_accounts = service_account.objects.filter( permissions__content_type__app_label="extensions", permissions__codename="manage_plugins", ) if not plugin_permission or not extension_permission: return for user in users: user.user_permissions.remove(extension_permission) user.user_permissions.add(plugin_permission) for service_account in service_accounts: service_account.permissions.remove(extension_permission) service_account.permissions.add(plugin_permission) if extension_permission: extension_permission.delete() class Migration(migrations.Migration): dependencies = [ ("account", "0039_auto_20200221_0257"), ("plugins", "0001_initial"), ] operations = [ migrations.RunPython(change_extension_permission_to_plugin_permission), ]
Fix plugin permission data migration
Fix plugin permission data migration
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
03e0e11491c64ae546134eb6c963a31958fe6d6d
address_book/address_book.py
address_book/address_book.py
from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] def add_person(self, person): self.persons.append(person) def __contains__(self, item): if isinstance(item, Person): return item in self.persons return False
from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons return False
Add `add_group` method to `AddressBook` class - to make it possible to add groups to the address book
Add `add_group` method to `AddressBook` class - to make it possible to add groups to the address book
Python
mit
dizpers/python-address-book-assignment
72466cb328fb56bfe28f5c3a1f8fca082db24319
typer/__init__.py
typer/__init__.py
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_os_args, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import Abort, Exit # noqa from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
Clean exports from typer, remove unneeded Click components, add needed ones
:fire: Clean exports from typer, remove unneeded Click components, add needed ones Clean exports from typer, remove unneeded Click components
Python
mit
tiangolo/typer,tiangolo/typer
6709944d7e856fbce0434da0dc731fc83b55feb1
tests/test_cli_update.py
tests/test_cli_update.py
# -*- coding: utf-8 -*- import pathlib def test_should_write_json(cli_runner, tmp_rc, tmp_templates_file): result = cli_runner([ '-c', tmp_rc, 'update' ]) assert result.exit_code == 0 templates = pathlib.Path(tmp_templates_file) assert templates.exists()
# -*- coding: utf-8 -*- import pathlib import json def test_store_template_data_to_json(cli_runner, tmp_rc, tmp_templates_file): result = cli_runner([ '-c', tmp_rc, 'update' ]) assert result.exit_code == 0 templates = pathlib.Path(tmp_templates_file) assert templates.exists() with templates.open('r', encoding='utf8') as fh: template_data = json.load(fh) fetched_templates = [template['name'] for template in template_data] expected_templates = [ 'cookiecutter-pypackage', 'cookiecutter-pylibrary', 'cookiecutter-pytest-plugin', 'cookiecutter-tapioca', ] assert fetched_templates == expected_templates
Extend integration test to check correctness of dumped json data
Extend integration test to check correctness of dumped json data
Python
bsd-3-clause
hackebrot/cibopath
9ee1db76af2a1afdf59bf9099008715d9bca2f4d
tests/test_collection.py
tests/test_collection.py
from bukkit import Collection def test_creation(): buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0) assert buckets.rate == 5 assert buckets.limit == 23 assert buckets.timeout == 31 assert buckets.head_node.prev_node is buckets.tail_node assert buckets.tail_node.next_node is buckets.head_node
from bukkit import Collection def test_creation(): buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0) assert buckets.rate == 5 assert buckets.limit == 23 assert buckets.timeout == 31 assert buckets.head_node.prev_node is buckets.tail_node assert buckets.tail_node.next_node is buckets.head_node def test_contains(): buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0) assert len(buckets.node_map) == 0 assert 'thingy' not in buckets buckets.consume('thingy', 5) assert len(buckets.node_map) == 1 assert 'thingy' in buckets def test_get(): buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0) try: buckets['thingy'] assert False, "Should not be able to look up 'thingy'" except IndexError, exc: assert str(exc) == "No such bucket: 'thingy'" buckets.consume('thingy', 5) assert buckets['thingy'].tokens == 18
Make sure getting buckets and checking for their presence work.
Make sure getting buckets and checking for their presence work.
Python
mit
kgaughan/bukkit
80c4b0fe0a654ef4ec56faac73af993408b846f1
test_client.py
test_client.py
from client import client import pytest def test_string_input(): assert client("String") == "You sent: String" def test_int_input(): assert client(42) == "You sent: 42" def test_empty_input(): with pytest.raises(TypeError): client() def test_over32_input(): assert client("A long message that will be over 32 bits but here's a few more")\ == "You sent: A long message that will be over 32 bits but here's a few more"
from client import client import pytest def test_response_ok(): msg = "GET /path/to/myindex.html HTTP/1.1\r\nHost: localhost:50000\r\n" result = "HTTP/1.1 200 OK\r\n" con_type = "Content-Type: text/plain\r\n" body = "Content length: {}".format(21) # Length of message from file name to end of line result = "{}{}{}".format(result, con_type, body) assert client(msg) == result
Add first test for a good response
Add first test for a good response
Python
mit
nbeck90/network_tools
6d6528182eb5dc21f41eb4ea5e4cfd08163edc96
sara_flexbe_states/src/sara_flexbe_states/Wonderland_Request.py
sara_flexbe_states/src/sara_flexbe_states/Wonderland_Request.py
#!/usr/bin/env python # encoding=utf8 import requests from flexbe_core import EventState, Logger class Wonderland_Request(EventState): ''' MoveArm receive a ROS pose as input and launch a ROS service with the same pose ># url string url to call <= response string Finish job. ''' def __init__(self): # See example_state.py for basic explanations. super(Wonderland_Request, self).__init__(outcomes=['done', 'error'], input_keys=['url'], output_keys=['response']) self._header = {'api-key': 'asdf'} def execute(self, userdata): # This method is called periodically while the state is active. # Main purpose is to check state conditions and trigger a corresponding outcome. # If no outcome is returned, the state will stay active. try: response = requests.get(userdata.url, headers=self._header) except requests.exceptions.RequestException as e: print e return 'error' userdata.response = response.content return 'done' # One of the outcomes declared above.
#!/usr/bin/env python # encoding=utf8 import requests from flexbe_core import EventState, Logger class Wonderland_Request(EventState): ''' Send requests to Wonderland server ># url string url to call <= response string Finish job. ''' def __init__(self): # See example_state.py for basic explanations. super(Wonderland_Request, self).__init__(outcomes=['done', 'error'], input_keys=['url'], output_keys=['response']) self._header = {'api-key': 'asdf'} def execute(self, userdata): # This method is called periodically while the state is active. # Main purpose is to check state conditions and trigger a corresponding outcome. # If no outcome is returned, the state will stay active. url = "http://192.168.0.46:8000/api/" + userdata.url try: response = requests.get(url, headers=self._header) except requests.exceptions.RequestException as e: print e return 'error' userdata.response = response.content return 'done' # One of the outcomes declared above.
Simplify state and save server URL
Simplify state and save server URL
Python
bsd-3-clause
WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors
f275c8cc020119b52ed01bc6b56946279853d854
src/mmw/apps/bigcz/clients/cuahsi/details.py
src/mmw/apps/bigcz/clients/cuahsi/details.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date)
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site, None) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date, None)
Stop ulmo caching for suds-jurko compliance
Stop ulmo caching for suds-jurko compliance Previously we were using ulmo with suds-jurko 0.6, which is the current latest release, but it is 4 years old. Most recent work on suds-jurko has been done on the development branch, including optimizations to memory use (which we need). Unfortunately, the development branch also includes some breaking changes, including one which "cleans up" the caching module: https://bitbucket.org/jurko/suds/commits/6b24afe3206fc648605cc8d19f7c58c605d9df5f?at=default This change renames .setduration() to .__set_duration(), which is called by ulmo here: https://github.com/emiliom/ulmo/blob/90dbfe31f38a72ea4cee9a52e572cfa8f8484adc/ulmo/cuahsi/wof/core.py#L290 By explicitly setting the caching to None, we ensure that line isn't executed and those errors don't crop up. The performance improvements we get from using the development branch of suds-jurko outweigh the benefits of caching for one day, since it is unlikely we will be accessing the exact same content repeatedly.
Python
apache-2.0
WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed
366316b0ea20ae178670581b61c52c481682d2b0
cosmic_ray/operators/exception_replacer.py
cosmic_ray/operators/exception_replacer.py
import ast import builtins from .operator import Operator class OutOfNoWhereException(Exception): pass setattr(builtins, OutOfNoWhereException.__name__, OutOfNoWhereException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = OutOfNoWhereException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
import ast import builtins from .operator import Operator class CosmicRayTestingException(Exception): pass setattr(builtins, CosmicRayTestingException.__name__, CosmicRayTestingException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = CosmicRayTestingException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
Change exception name to CosmicRayTestingException
Change exception name to CosmicRayTestingException
Python
mit
sixty-north/cosmic-ray
132309e91cc7e951d4a7f326d9e374dc8943f2f3
tests/core/providers/test_testrpc_provider.py
tests/core/providers/test_testrpc_provider.py
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider as TheTestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TheTestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
Resolve pytest warning about TestRPCProvider
Resolve pytest warning about TestRPCProvider
Python
mit
pipermerriam/web3.py
17e26fa55e70de657d52e340cb6b66691310a663
bettertexts/forms.py
bettertexts/forms.py
from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ Override to add inform field """ data = super(TextCommentForm, self).get_comment_create_data() data.update({'inform': True}) return data
from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ Override to add inform and involved field """ data = super(TextCommentForm, self).get_comment_create_data() data.update({'inform': self.cleaned_data["inform"], 'involved': self.cleaned_data["involved"]}) return data
Fix checkboxes inform and involved
CL011: Fix checkboxes inform and involved
Python
mit
citizenline/citizenline,citizenline/citizenline,citizenline/citizenline,citizenline/citizenline
ee66811628ea81e0540816e012c71d90457cc933
test/utils/filesystem/name_sanitizer_spec.py
test/utils/filesystem/name_sanitizer_spec.py
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=254, min_size=1)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any size_limit = 255 def byte_length_size(sample): return len(bytes(sample, "utf-8")) <= size_limit with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=size_limit, min_size=1) .filter(byte_length_size)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
Add explicit example filtering based on the byte length of the content
Add explicit example filtering based on the byte length of the content
Python
mit
Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki
c10be759ad2ddbd076a1fe0a887d3cf9325aba3d
src/scheduler.py
src/scheduler.py
from collections import namedtuple import sched_utils import check ScheduleConfiguration = namedtuple('ScheduleConfiguration', ['zones', 'teams', 'weight_zones', 'round_length', 'imbalance_action', 'match_count']) if __name__ == '__main__': config = ScheduleConfiguration(zones = 4, teams = ['Team {0}'.format(x) for x in xrange(1, 11)], weight_zones = True, round_length = None, imbalance_action = 'empty', match_count = 25) schedule = sched_utils.full_schedule(config) check.schedule_check(schedule) import json print json.dumps(schedule)
"""Match scheduler. Usage: scheduler.py full <teams> <matches> [options] scheduler.py partial <teams> <previous> <matches> [options] Options: -w --weight Try to balance out between starting zones. --zones=<z> Number of start zones [default: 4]. --empty Leave empty spaces to balance out the match distribution. --surrogate Use surrogate appearances to balance out the distribution. --rounds=<r> Divide the schedule into rounds of length r. -h --help Show this screen. """ from collections import namedtuple import sched_utils import check from docopt import docopt ScheduleConfiguration = namedtuple('ScheduleConfiguration', ['zones', 'teams', 'weight_zones', 'round_length', 'imbalance_action', 'match_count']) if __name__ == '__main__': options = docopt(__doc__) rl = int(options['--rounds']) if options['--rounds'] else None imba = 'empty' if options['--surrogate']: imba = 'surrogate' if options['--empty']: imba = 'empty' with open(options['<teams>'], 'r') as f: teams = [x.strip() for x in f if x.strip()] if options['partial']: with open(options['<previous>'], 'r') as f: partial = [x.strip().split('|') for x in f if x.strip()] else: partial = None config = ScheduleConfiguration(zones = int(options['--zones']), teams = teams, weight_zones = options['--weight'], round_length = rl, imbalance_action = imba, match_count = int(options['<matches>'])) if partial is None: schedule = sched_utils.full_schedule(config) else: schedule = sched_utils.partial_schedule(config, partial) check.schedule_check(schedule) for item in schedule: print '|'.join(item)
Switch to a new command-line interface
Switch to a new command-line interface
Python
mit
prophile/match-scheduler,prophile/match-scheduler
729d3160f974c521ab6605c02cf64861be0fb6ab
fri/utils.py
fri/utils.py
import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff))
import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff)) def permutate_feature_in_data(data, feature_i, random_state): X, y = data X_copy = np.copy(X) # Permute selected feature permutated_feature = random_state.permutation(X_copy[:, feature_i]) # Add permutation back to dataset X_copy[:, feature_i] = permutated_feature return X_copy, y
Revert removal of necessary function
Revert removal of necessary function
Python
mit
lpfann/fri
02522262692554a499d7c0fbc8f2efe4361023f1
bmi_ilamb/__init__.py
bmi_ilamb/__init__.py
import os from .bmi_ilamb import BmiIlamb __all__ = ['BmiIlamb'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data')
import os from .bmi_ilamb import BmiIlamb from .config import Configuration __all__ = ['BmiIlamb', 'Configuration'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data')
Add Configuration to package definition
Add Configuration to package definition
Python
mit
permamodel/bmi-ilamb
af2687703bc13eeabfe715e35988ad8c54ce9117
builds/format_json.py
builds/format_json.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(f_contents, indent=2, sort_keys=True) if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(data, indent=2) + '\n' if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
Tweak the JSON we export
Tweak the JSON we export
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
0b5cc3f4702081eb565ef83c3175efc4e8b30e75
circuits/node/node.py
circuits/node/node.py
# Module: node # Date: ... # Author: ... """Node ... """ from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
# Module: node # Date: ... # Author: ... """Node ... """ from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
Fix channel definition in add method
Fix channel definition in add method
Python
mit
eriol/circuits,eriol/circuits,treemo/circuits,nizox/circuits,eriol/circuits,treemo/circuits,treemo/circuits
3234d929d22d7504d89753ce6351d0efe1bfa8ac
whitepy/lexer.py
whitepy/lexer.py
from .lexerconstants import * from .ws_token import Tokeniser class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: # TODO: Add error handling for invalid integer pass return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
from .lexerconstants import * from .ws_token import Tokeniser class IntError(ValueError): '''Exception when invalid integer is found''' class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: raise IntError return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
Add Execption for invalid Integer
Add Execption for invalid Integer Exception class created for invalid integer and raise it if a bad integer is found
Python
apache-2.0
yasn77/whitepy
9d0ea4eaf8269350fabc3415545bebf4da4137a7
source/segue/backend/processor/background.py
source/segue/backend/processor/background.py
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
Fix passing invalid None to multiprocessing Process class.
Fix passing invalid None to multiprocessing Process class.
Python
apache-2.0
4degrees/segue
34334bdb85644a5553ba36af5dc98942ea5fbf21
launch_control/__init__.py
launch_control/__init__.py
# This file is part of the ARM Validation Dashboard Project. # for the Linaro organization (http://linaro.org/) # # For more details see: # https://blueprints.launchpad.net/ubuntu/+spec/arm-m-validation-dashboard __version__ = "0.0.1"
# This file is part of the ARM Validation Dashboard Project. # for the Linaro organization (http://linaro.org/) # # For more details see: # https://blueprints.launchpad.net/ubuntu/+spec/arm-m-validation-dashboard """ Public API for Launch Control. Please see one of the available packages for more information. """ __version__ = "0.0.1"
Add docstring to launch_control package
Add docstring to launch_control package
Python
agpl-3.0
Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server
cb1af2160952c7065e236d2cd544f46e5b252e92
account_partner_account_summary/__openerp__.py
account_partner_account_summary/__openerp__.py
# -*- coding: utf-8 -*- { 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', 'l10n_ar_invoice', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ADD dependency of l10n_ar_invoice for account summary
ADD dependency of l10n_ar_invoice for account summary
Python
agpl-3.0
maljac/odoo-addons,adhoc-dev/odoo-addons,syci/ingadhoc-odoo-addons,dvitme/odoo-addons,ingadhoc/account-payment,jorsea/odoo-addons,ingadhoc/stock,jorsea/odoo-addons,ingadhoc/account-financial-tools,sysadminmatmoz/ingadhoc,levkar/odoo-addons,syci/ingadhoc-odoo-addons,ingadhoc/partner,ingadhoc/product,ClearCorp/account-financial-tools,ingadhoc/sale,levkar/odoo-addons,levkar/odoo-addons,jorsea/odoo-addons,syci/ingadhoc-odoo-addons,HBEE/odoo-addons,levkar/odoo-addons,ingadhoc/account-invoicing,ingadhoc/sale,ingadhoc/product,ingadhoc/odoo-addons,ingadhoc/odoo-addons,adhoc-dev/account-financial-tools,dvitme/odoo-addons,maljac/odoo-addons,ingadhoc/sale,ingadhoc/odoo-addons,bmya/odoo-addons,bmya/odoo-addons,sysadminmatmoz/ingadhoc,bmya/odoo-addons,HBEE/odoo-addons,HBEE/odoo-addons,sysadminmatmoz/ingadhoc,ClearCorp/account-financial-tools,dvitme/odoo-addons,adhoc-dev/odoo-addons,adhoc-dev/account-financial-tools,ingadhoc/account-analytic,maljac/odoo-addons,adhoc-dev/odoo-addons,ingadhoc/sale
517d25cf79c4d04661309ab7b3ab0638a2f968ee
api/docbleach/utils/__init__.py
api/docbleach/utils/__init__.py
import os import random import string def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args)
import os import string from random import SystemRandom cryptogen = SystemRandom() def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): return ''.join(cryptogen.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args)
Use SystemRandom to generate security-viable randomness
Use SystemRandom to generate security-viable randomness
Python
mit
docbleach/DocBleach-Web,docbleach/DocBleach-Web,docbleach/DocBleach-Web,docbleach/DocBleach-Web
a4df3f966e232e8327522a3db32870f5dcea0c03
cartridge/shop/middleware.py
cartridge/shop/middleware.py
from mezzanine.conf import settings from cartridge.shop.models import Cart class ShopMiddleware(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break def process_request(self, request): """ Adds cart and wishlist attributes to the current request. """ request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist
from mezzanine.conf import settings from cartridge.shop.models import Cart class SSLRedirect(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break class ShopMiddleware(SSLRedirect): """ Adds cart and wishlist attributes to the current request. """ def process_request(self, request): request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist
Add deprecated fallback for SSLMiddleware.
Add deprecated fallback for SSLMiddleware.
Python
bsd-2-clause
traxxas/cartridge,traxxas/cartridge,Parisson/cartridge,Kniyl/cartridge,syaiful6/cartridge,jaywink/cartridge-reservable,wbtuomela/cartridge,syaiful6/cartridge,ryneeverett/cartridge,wbtuomela/cartridge,dsanders11/cartridge,wbtuomela/cartridge,dsanders11/cartridge,wyzex/cartridge,jaywink/cartridge-reservable,Parisson/cartridge,viaregio/cartridge,ryneeverett/cartridge,jaywink/cartridge-reservable,Kniyl/cartridge,traxxas/cartridge,wyzex/cartridge,wyzex/cartridge,stephenmcd/cartridge,Parisson/cartridge,dsanders11/cartridge,stephenmcd/cartridge,ryneeverett/cartridge,viaregio/cartridge,stephenmcd/cartridge,syaiful6/cartridge,Kniyl/cartridge
d7624defd7d05e721aeb0ccd074c7172c51295bf
nvchecker_source/git.py
nvchecker_source/git.py
# MIT licensed # Copyright (c) 2020 Felix Yan <felixonmars@archlinux.org>, et al. import re from nvchecker_source.cmd import run_cmd async def get_version( name, conf, *, cache, keymanager=None ): git = conf['git'] cmd = f"git ls-remote -t --refs {git}" data = await cache.get(cmd, run_cmd) regex = "(?<=refs/tags/).*$" return re.findall(regex, data)
# MIT licensed # Copyright (c) 2020 Felix Yan <felixonmars@archlinux.org>, et al. import re from .cmd import run_cmd # type: ignore async def get_version( name, conf, *, cache, keymanager=None ): git = conf['git'] cmd = f"git ls-remote -t --refs {git}" data = await cache.get(cmd, run_cmd) regex = "(?<=refs/tags/).*$" return re.findall(regex, data, re.MULTILINE)
Fix mypy and regex flag
Fix mypy and regex flag
Python
mit
lilydjwg/nvchecker
47f495e7e5b8fa06991e0c263bc9239818dd5b4f
airpy/list.py
airpy/list.py
import os import airpy def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n')
from __future__ import print_function import os import airpy def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n')
Add a Backwards compatibility for python 2.7 by adding a __future__ import
Add a Backwards compatibility for python 2.7 by adding a __future__ import
Python
mit
kevinaloys/airpy
6656493c3bf9b24d67c6de8cb33a1ca3defa4db8
code/python/yum-check-update.py
code/python/yum-check-update.py
#!/usr/bin/python import json import subprocess process = subprocess.Popen(["yum", "check-update", "-q"], stdout=subprocess.PIPE) (output, err) = process.communicate() exit_code = process.wait() if exit_code == 0 and output == "": print "Up to date" else: print json.dumps({"exit_code": exit_code, "raw": output})
#!/usr/bin/python import json import subprocess process = subprocess.Popen(["yum", "check-update", "-q"], stdout=subprocess.PIPE) (output, err) = process.communicate() exit_code = process.wait() if exit_code == 0 and output == "": print json.dumps({"exit_code": exit_code, "raw": "Up to date"}) else: print json.dumps({"exit_code": exit_code, "raw": output})
Make output types consistent for policy creation purposes
Make output types consistent for policy creation purposes
Python
mit
ScriptRock/content,ScriptRock/content,ScriptRock/content,ScriptRock/content,ScriptRock/content,ScriptRock/content
68b0f560322884967b817ad87cef8c1db9600dbd
app/main/errors.py
app/main/errors.py
from flask import render_template from app.main import main @main.app_errorhandler(400) def page_not_found(e): return _render_error_page(500) @main.app_errorhandler(404) def page_not_found(e): return _render_error_page(404) @main.app_errorhandler(500) def exception(e): return _render_error_page(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_page(503) def _render_error_page(status_code): template_map = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in template_map: status_code = 500 template_data = main.config['BASE_TEMPLATE_DATA'] return render_template(template_map[status_code], **template_data), status_code
from flask import render_template from app.main import main @main.app_errorhandler(400) def page_not_found(e): print(e.message) return _render_error_page(500) @main.app_errorhandler(404) def page_not_found(e): print(e.message) return _render_error_page(404) @main.app_errorhandler(500) def exception(e): print(e.message) return _render_error_page(500) @main.app_errorhandler(503) def service_unavailable(e): print(e.message) return _render_error_page(503) def _render_error_page(status_code): template_map = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in template_map: status_code = 500 template_data = main.config['BASE_TEMPLATE_DATA'] return render_template(template_map[status_code], **template_data), status_code
Add print statements for all error types
Add print statements for all error types
Python
mit
alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend
1dbb1e0f8751f37271178665a727c4eefc49a88c
partner_firstname/exceptions.py
partner_firstname/exceptions.py
# -*- encoding: utf-8 -*- # Odoo, Open Source Management Solution # Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from openerp import _, exceptions class PartnerNameError(exceptions.ValidationError): def __init__(self, record, value=None): self.record = record self._value = value self.name = _("Error(s) with partner %d's name.") % record.id @property def value(self): raise NotImplementedError() class EmptyNames(PartnerNameError): @property def value(self): return _("No name is set.")
# -*- encoding: utf-8 -*- # Odoo, Open Source Management Solution # Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from openerp import _, exceptions class EmptyNames(exceptions.ValidationError): def __init__(self, record, value=_("No name is set.")): self.record = record self._value = value self.name = _("Error(s) with partner %d's name.") % record.id
Remove subclassing of exception, since there is only one.
Remove subclassing of exception, since there is only one.
Python
agpl-3.0
BT-fgarbely/partner-contact,diagramsoftware/partner-contact,andrius-preimantas/partner-contact,BT-jmichaud/partner-contact,Antiun/partner-contact,Therp/partner-contact,idncom/partner-contact,gurneyalex/partner-contact,Endika/partner-contact,Ehtaga/partner-contact,QANSEE/partner-contact,raycarnes/partner-contact,open-synergy/partner-contact,BT-ojossen/partner-contact,charbeljc/partner-contact,sergiocorato/partner-contact,alanljj/oca-partner-contact,acsone/partner-contact,akretion/partner-contact
ef0d0fa26bfd22c281c54bc348877afd0a7ee9d7
tests/integration/blueprints/metrics/test_metrics.py
tests/integration/blueprints/metrics/test_metrics.py
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest # To be overridden by test parametrization @pytest.fixture def config_overrides(): return {} @pytest.fixture def client(admin_app, config_overrides, make_admin_app): app = make_admin_app(**config_overrides) with app.app_context(): yield app.test_client() @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}]) def test_metrics(client): response = client.get('/metrics') assert response.status_code == 200 assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8' assert response.mimetype == 'text/plain' assert response.get_data(as_text=True) == ( 'users_active_count 0\n' 'users_uninitialized_count 0\n' 'users_suspended_count 0\n' 'users_deleted_count 0\n' 'users_total_count 0\n' ) @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}]) def test_disabled_metrics(client): response = client.get('/metrics') assert response.status_code == 404
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import re import pytest # To be overridden by test parametrization @pytest.fixture def config_overrides(): return {} @pytest.fixture def client(admin_app, config_overrides, make_admin_app): app = make_admin_app(**config_overrides) with app.app_context(): yield app.test_client() @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}]) def test_metrics(client): response = client.get('/metrics') assert response.status_code == 200 assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8' assert response.mimetype == 'text/plain' # Not a full match as there can be other metrics, too. regex = re.compile( 'users_active_count \\d+\n' 'users_uninitialized_count \\d+\n' 'users_suspended_count \\d+\n' 'users_deleted_count \\d+\n' 'users_total_count \\d+\n' ) assert regex.search(response.get_data(as_text=True)) is not None @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}]) def test_disabled_metrics(client): response = client.get('/metrics') assert response.status_code == 404
Use regex to match user metrics
Use regex to match user metrics
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
9011b359bdf164994734f8d6890a2d5acb5fa865
project_euler/solutions/problem_32.py
project_euler/solutions/problem_32.py
from itertools import permutations def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): result = int(''.join(str(digit) for digit in permutation[:4])) for i in range(1, 4): left = int(''.join(str(digit) for digit in permutation[4:4 + i])) right = int(''.join(str(digit) for digit in permutation[4 + i:])) if left * right == result: pandigital.append(result) return sum(set(pandigital))
from itertools import permutations from ..library.base import list_to_number def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): result = list_to_number(permutation[:4]) for i in range(1, 4): left = list_to_number(permutation[4:4 + i]) right = list_to_number(permutation[4 + i:]) if left * right == result: pandigital.append(result) return sum(set(pandigital))
Replace joins with list_to_number in 32
Replace joins with list_to_number in 32
Python
mit
cryvate/project-euler,cryvate/project-euler
a3c582df681aae77034e2db08999c89866cd6470
utilities.py
utilities.py
import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): key_set = self.viewkeys() | compare_to.viewkeys() currentEMD = 0 lastEMD = 0 totaldistance = 0 for key in key_set: lastEMD = currentEMD currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, 0) totaldistance += math.fabs(currentEMD) return totaldistance
import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): return sum( (abs(self.get(bin) - compare_to.get(bin)) for bin in self.viewkeys() | compare_to.viewkeys()), 0)
Refactor earth mover's distance implementation
Refactor earth mover's distance implementation
Python
mit
davidfoerster/schema-matching
0d2079b1dcb97708dc55c32d9e2c1a0f12595875
salt/runners/launchd.py
salt/runners/launchd.py
# -*- coding: utf-8 -*- ''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> """.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write("Supported programs: %r\n" % supported_programs) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
# -*- coding: utf-8 -*- ''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = ''' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> '''.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write('Supported programs: {0!r}\n'.format(supported_programs)) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
Replace string substitution with string formatting
Replace string substitution with string formatting
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
69e760e4a571d16e75f30f1e97ea1a917445f333
recipes/recipe_modules/gitiles/__init__.py
recipes/recipe_modules/gitiles/__init__.py
DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'url', ]
DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/url', ]
Switch to recipe engine "url" module.
Switch to recipe engine "url" module. BUG=None TEST=expectations R=40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org Change-Id: I43a65405c957cb6dddd64f61846b926d81046752 Reviewed-on: https://chromium-review.googlesource.com/505278 Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org> Commit-Queue: Daniel Jacques <8400006a9338a0893dca0101ad49838955bd6b2c@chromium.org>
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
394954fc80230e01112166db4fe133c107febead
gitautodeploy/parsers/common.py
gitautodeploy/parsers/common.py
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config['url'] == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
Allow more than one GitHub repo from the same user
Allow more than one GitHub repo from the same user GitHub does not allow the same SSH key to be used for multiple repositories on the same server belonging to the same user, see: http://snipe.net/2013/04/multiple-github-deploy-keys-single-server The fix there doesn't work because the "url" field is used both to get the repo and to identify it when a push comes in. Using a local SSH name for the repo works for getting the repo but then the name in the push doesn't match. This patch adds a 'repo' option that that can be set to the name of the repo as given in the push. If 'repo' is not set the behaviour is unchanged. Example: "url": "git@repo-a-shortname/somerepo.git" "repo": "git@github.com/somerepo.git"
Python
mit
evoja/docker-Github-Gitlab-Auto-Deploy,evoja/docker-Github-Gitlab-Auto-Deploy
bb9d1255548b46dc2ba7a85e26606b7dd4c926f3
examples/greeting.py
examples/greeting.py
# greeting.py # # Demonstration of the pyparsing module, on the prototypical "Hello, World!" # example # # Copyright 2003, by Paul McGuire # from pyparsing import Word, alphas # define grammar greet = Word( alphas ) + "," + Word( alphas ) + "!" # input string hello = "Hello, World!" # parse input string print(hello, "->", greet.parseString( hello ))
# greeting.py # # Demonstration of the pyparsing module, on the prototypical "Hello, World!" # example # # Copyright 2003, 2019 by Paul McGuire # import pyparsing as pp # define grammar greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .") # input string hello = "Hello, World!" # parse input string print(hello, "->", greet.parseString( hello )) # parse a bunch of input strings greet.runTests("""\ Hello, World! Ahoy, Matey! Howdy, Pardner! Morning, Neighbor! """)
Update original "Hello, World!" parser to latest coding, plus runTests
Update original "Hello, World!" parser to latest coding, plus runTests
Python
mit
pyparsing/pyparsing,pyparsing/pyparsing
bc6c3834cd8383f7e1f9e109f0413bb6015a92bf
go/scheduler/views.py
go/scheduler/views.py
import datetime from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): now = datetime.datetime.utcnow() return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for')
from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for')
Remove unneeded datetime from view
Remove unneeded datetime from view
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
ebfaf30fca157e83ea9e4bf33173221fc9525caf
demo/examples/employees/forms.py
demo/examples/employees/forms.py
from datetime import date from django import forms from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
from django import forms from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
Fix emplorrs demo salary db error
Fix emplorrs demo salary db error
Python
bsd-3-clause
viewflow/django-material,viewflow/django-material,viewflow/django-material
a473b2cb9af95c1296ecae4d2138142f2be397ee
examples/variants.py
examples/variants.py
#!/usr/bin/env python # -*- coding: utf8 - *- from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
#!/usr/bin/env python # -*- coding: utf8 - *- from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
Add variant extension in example script
Add variant extension in example script
Python
mit
cihai/cihai,cihai/cihai-python,cihai/cihai
0727ad29721a3dad4c36113a299f5c67bda70822
importlib_resources/__init__.py
importlib_resources/__init__.py
"""Read resources contained within a package.""" import sys __all__ = [ 'contents', 'is_resource', 'open_binary', 'open_text', 'path', 'read_binary', 'read_text', 'Package', 'Resource', 'ResourceReader', ] if sys.version_info >= (3,): from importlib_resources._py3 import ( Package, Resource, contents, is_resource, open_binary, open_text, path, read_binary, read_text) from importlib_resources.abc import ResourceReader else: from importlib_resources._py2 import ( contents, is_resource, open_binary, open_text, path, read_binary, read_text) del __all__[-3:] __version__ = read_text('importlib_resources', 'version.txt').strip()
"""Read resources contained within a package.""" import sys __all__ = [ 'Package', 'Resource', 'ResourceReader', 'contents', 'is_resource', 'open_binary', 'open_text', 'path', 'read_binary', 'read_text', ] if sys.version_info >= (3,): from importlib_resources._py3 import ( Package, Resource, contents, is_resource, open_binary, open_text, path, read_binary, read_text, ) from importlib_resources.abc import ResourceReader else: from importlib_resources._py2 import ( contents, is_resource, open_binary, open_text, path, read_binary, read_text, ) del __all__[:3] __version__ = read_text('importlib_resources', 'version.txt').strip()
Sort everything alphabetically on separate lines.
Sort everything alphabetically on separate lines.
Python
apache-2.0
python/importlib_resources
7f974b87c278ef009535271461b5e49686057a9a
avatar/management/commands/rebuild_avatars.py
avatar/management/commands/rebuild_avatars.py
from django.core.management.base import NoArgsCommand from avatar.conf import settings from avatar.models import Avatar class Command(NoArgsCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle_noargs(self, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
Fix for django >= 1.10
Fix for django >= 1.10 The class django.core.management.NoArgsCommand is removed.
Python
bsd-3-clause
grantmcconnaughey/django-avatar,jezdez/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,ad-m/django-avatar,jezdez/django-avatar
6e2362351d9ccaa46a5a2bc69c4360e4faff166d
iclib/qibla.py
iclib/qibla.py
from . import formula def direction(lat, lng): return formula.qibla(lat, lng) def direction_dms(lat, lng): return _dms(formula.qibla(lat, lng)) def direction_str(lat, lng, prec=0): d, m, s = direction_dms(lat, lng) # negative input might returns wrong result return '{}° {}\' {:.{}f}"'.format(d, m, s, prec) def _dms(deg): seconds = deg * 3600 m, s = divmod(seconds, 60) d, m = divmod(m, 60) return (int(d), int(m), s)
# -*- coding: utf-8 -*- from . import formula def direction(lat, lng): return formula.qibla(lat, lng) def direction_dms(lat, lng): return _dms(formula.qibla(lat, lng)) def direction_str(lat, lng, prec=0): d, m, s = direction_dms(lat, lng) # negative input might returns wrong result return '{}° {}\' {:.{}f}"'.format(d, m, s, prec) def _dms(deg): seconds = deg * 3600 m, s = divmod(seconds, 60) d, m = divmod(m, 60) return (int(d), int(m), s)
Add encoding spec to comply Python 2
Add encoding spec to comply Python 2
Python
apache-2.0
fikr4n/iclib-python
eb1fdf3419bdfd1d5920d73a877f707162b783b0
cfgrib/__init__.py
cfgrib/__init__.py
# # Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF). # # 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 License. __version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage from .dataset import ( Dataset, DatasetBuildError, open_container, open_file, open_fileindex, open_from_index, ) from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass
# # Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF). # # 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 License. __version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass
Drop unused and dangerous entrypoint `open_fileindex`
Drop unused and dangerous entrypoint `open_fileindex`
Python
apache-2.0
ecmwf/cfgrib
e3548d62aa67472f291f6d3c0c8beca9813d6032
gym/envs/toy_text/discrete.py
gym/envs/toy_text/discrete.py
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering self._reset() @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
Make it possible to step() in a newly created env, rather than throwing AttributeError
Make it possible to step() in a newly created env, rather than throwing AttributeError
Python
mit
d1hotpep/openai_gym,Farama-Foundation/Gymnasium,dianchen96/gym,machinaut/gym,dianchen96/gym,d1hotpep/openai_gym,machinaut/gym,Farama-Foundation/Gymnasium
eb57a07277f86fc90b7845dc48fb5cde1778c8d4
test/unit_test/test_cut_number.py
test/unit_test/test_cut_number.py
from lexos.processors.prepare.cutter import split_keep_whitespace, \ count_words, cut_by_number class TestCutByNumbers: def test_split_keep_whitespace(self): assert split_keep_whitespace("Test string") == ["Test", " ", "string"] assert split_keep_whitespace("Test") == ["Test"] assert split_keep_whitespace(" ") == ["", " ", ""] # intended? assert split_keep_whitespace("") == [""] def test_count_words(self): assert count_words(["word", "word", " ", "not", "word"]) == 4 assert count_words(['\n', '\t', ' ', '', '\u3000', "word"]) == 1 assert count_words([""]) == 0
from lexos.processors.prepare.cutter import split_keep_whitespace, \ count_words, cut_by_number class TestCutByNumbers: def test_split_keep_whitespace(self): assert split_keep_whitespace("Test string") == ["Test", " ", "string"] assert split_keep_whitespace("Test") == ["Test"] assert split_keep_whitespace(" ") == ["", " ", ""] # intended? assert split_keep_whitespace("") == [""] def test_count_words(self): assert count_words(["word", "word", " ", "not", "word"]) == 4 assert count_words(['\n', '\t', ' ', '', '\u3000', "word"]) == 1 assert count_words([""]) == 0 def test_cut_by_number_normal(self): assert cut_by_number("Text", 1) == ["Text"] assert cut_by_number("This text has five words", 5) == \ ["This ", "text ", "has ", "five ", "words"] assert cut_by_number("Hanging space ", 2) == ["Hanging ", "space "]
Test cut_by_number with words and normal chunk numbers
Test cut_by_number with words and normal chunk numbers
Python
mit
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
91e916cb67867db9ce835be28b31904e6efda832
spacy/tests/regression/test_issue1727.py
spacy/tests/regression/test_issue1727.py
from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0
'''Test that models with no pretrained vectors can be deserialized correctly after vectors are added.''' from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0
Add comment to new test
Add comment to new test
Python
mit
aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy
9df00bbfa829006396c2a6718e4540410b27c4c6
kolibri/tasks/apps.py
kolibri/tasks/apps.py
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): pass
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): from kolibri.tasks.api import client client.clear(force=True)
Clear the job queue upon kolibri initialization.
Clear the job queue upon kolibri initialization.
Python
mit
MingDai/kolibri,mrpau/kolibri,benjaoming/kolibri,DXCanas/kolibri,lyw07/kolibri,learningequality/kolibri,rtibbles/kolibri,mrpau/kolibri,mrpau/kolibri,rtibbles/kolibri,DXCanas/kolibri,indirectlylit/kolibri,MingDai/kolibri,lyw07/kolibri,mrpau/kolibri,christianmemije/kolibri,DXCanas/kolibri,learningequality/kolibri,jonboiser/kolibri,christianmemije/kolibri,christianmemije/kolibri,lyw07/kolibri,lyw07/kolibri,benjaoming/kolibri,jonboiser/kolibri,jonboiser/kolibri,indirectlylit/kolibri,christianmemije/kolibri,benjaoming/kolibri,learningequality/kolibri,rtibbles/kolibri,learningequality/kolibri,benjaoming/kolibri,MingDai/kolibri,indirectlylit/kolibri,MingDai/kolibri,indirectlylit/kolibri,rtibbles/kolibri,jonboiser/kolibri,DXCanas/kolibri
f6be438e01a499dc2bde6abfa5a00fb281db7b83
kamboo/core.py
kamboo/core.py
import botocore from kotocore.session import Session class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", credentials=None): self.region = region_name self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region)
import botocore from kotocore.session import Session class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region)
Add account_id as the element of this class
Add account_id as the element of this class
Python
apache-2.0
henrysher/kamboo,henrysher/kamboo
29d151366d186ed75da947f2861741ed87af902b
website/addons/badges/settings/__init__.py
website/addons/badges/settings/__init__.py
from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
# -*- coding: utf-8 -*- import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
Add missing import to settings
Add missing import to settings
Python
apache-2.0
samchrisinger/osf.io,himanshuo/osf.io,jinluyuan/osf.io,chrisseto/osf.io,zachjanicki/osf.io,njantrania/osf.io,chrisseto/osf.io,reinaH/osf.io,billyhunt/osf.io,RomanZWang/osf.io,aaxelb/osf.io,arpitar/osf.io,mattclark/osf.io,sbt9uc/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,amyshi188/osf.io,kwierman/osf.io,njantrania/osf.io,RomanZWang/osf.io,pattisdr/osf.io,TomHeatwole/osf.io,brianjgeiger/osf.io,doublebits/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,caseyrygt/osf.io,KAsante95/osf.io,mattclark/osf.io,kwierman/osf.io,erinspace/osf.io,GaryKriebel/osf.io,ckc6cz/osf.io,jmcarp/osf.io,haoyuchen1992/osf.io,chennan47/osf.io,alexschiller/osf.io,jolene-esposito/osf.io,abought/osf.io,cwisecarver/osf.io,zachjanicki/osf.io,baylee-d/osf.io,reinaH/osf.io,lyndsysimon/osf.io,kushG/osf.io,laurenrevere/osf.io,brandonPurvis/osf.io,cldershem/osf.io,lyndsysimon/osf.io,dplorimer/osf,petermalcolm/osf.io,pattisdr/osf.io,jmcarp/osf.io,caseyrygt/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,GaryKriebel/osf.io,HarryRybacki/osf.io,adlius/osf.io,zkraime/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,DanielSBrown/osf.io,abought/osf.io,ckc6cz/osf.io,kushG/osf.io,brandonPurvis/osf.io,emetsger/osf.io,doublebits/osf.io,sloria/osf.io,KAsante95/osf.io,dplorimer/osf,lyndsysimon/osf.io,wearpants/osf.io,brandonPurvis/osf.io,SSJohns/osf.io,aaxelb/osf.io,KAsante95/osf.io,bdyetton/prettychart,jmcarp/osf.io,aaxelb/osf.io,TomHeatwole/osf.io,sbt9uc/osf.io,reinaH/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,haoyuchen1992/osf.io,zachjanicki/osf.io,pattisdr/osf.io,cosenal/osf.io,mluke93/osf.io,caseyrollins/osf.io,felliott/osf.io,caneruguz/osf.io,danielneis/osf.io,revanthkolli/osf.io,alexschiller/osf.io,mluo613/osf.io,RomanZWang/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,cosenal/osf.io,Ghalko/osf.io,RomanZWang/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,caseyrygt/osf.io,barbour-em/osf.io,icereval/osf.io,fabianvf/osf.io,RomanZWang/osf.io,jnayak1/osf.io,billyhunt/osf.io,CenterForOpenScience/osf.io,samanehsan/osf.io,cslzchen/osf.io,Ghalko/osf.io,lamdnhan/osf.io,kushG/osf.io,mattclark/osf.io,himanshuo/osf.io,cldershem/osf.io,HalcyonChimera/osf.io,haoyuchen1992/osf.io,fabianvf/osf.io,GageGaskins/osf.io,jeffreyliu3230/osf.io,emetsger/osf.io,sbt9uc/osf.io,samchrisinger/osf.io,kch8qx/osf.io,barbour-em/osf.io,emetsger/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,sloria/osf.io,rdhyee/osf.io,himanshuo/osf.io,petermalcolm/osf.io,ticklemepierce/osf.io,Nesiehr/osf.io,HarryRybacki/osf.io,jinluyuan/osf.io,binoculars/osf.io,arpitar/osf.io,binoculars/osf.io,binoculars/osf.io,jinluyuan/osf.io,adlius/osf.io,bdyetton/prettychart,amyshi188/osf.io,cwisecarver/osf.io,bdyetton/prettychart,abought/osf.io,rdhyee/osf.io,brandonPurvis/osf.io,caseyrollins/osf.io,cosenal/osf.io,wearpants/osf.io,kch8qx/osf.io,MerlinZhang/osf.io,caneruguz/osf.io,Nesiehr/osf.io,barbour-em/osf.io,ckc6cz/osf.io,alexschiller/osf.io,erinspace/osf.io,amyshi188/osf.io,fabianvf/osf.io,SSJohns/osf.io,cslzchen/osf.io,acshi/osf.io,felliott/osf.io,hmoco/osf.io,jeffreyliu3230/osf.io,ticklemepierce/osf.io,Johnetordoff/osf.io,arpitar/osf.io,revanthkolli/osf.io,samanehsan/osf.io,leb2dg/osf.io,Ghalko/osf.io,brandonPurvis/osf.io,mluke93/osf.io,TomBaxter/osf.io,abought/osf.io,samanehsan/osf.io,barbour-em/osf.io,baylee-d/osf.io,felliott/osf.io,TomHeatwole/osf.io,dplorimer/osf,amyshi188/osf.io,SSJohns/osf.io,mfraezz/osf.io,kushG/osf.io,asanfilippo7/osf.io,himanshuo/osf.io,petermalcolm/osf.io,laurenrevere/osf.io,doublebits/osf.io,monikagrabowska/osf.io,jeffreyliu3230/osf.io,mfraezz/osf.io,zkraime/osf.io,haoyuchen1992/osf.io,cldershem/osf.io,revanthkolli/osf.io,alexschiller/osf.io,fabianvf/osf.io,kwierman/osf.io,ckc6cz/osf.io,mfraezz/osf.io,zachjanicki/osf.io,Nesiehr/osf.io,mluo613/osf.io,GageGaskins/osf.io,monikagrabowska/osf.io,emetsger/osf.io,erinspace/osf.io,lyndsysimon/osf.io,cldershem/osf.io,jinluyuan/osf.io,acshi/osf.io,mluke93/osf.io,lamdnhan/osf.io,acshi/osf.io,petermalcolm/osf.io,GageGaskins/osf.io,zamattiac/osf.io,zamattiac/osf.io,HarryRybacki/osf.io,njantrania/osf.io,felliott/osf.io,DanielSBrown/osf.io,jolene-esposito/osf.io,samanehsan/osf.io,rdhyee/osf.io,ZobairAlijan/osf.io,KAsante95/osf.io,kch8qx/osf.io,bdyetton/prettychart,cslzchen/osf.io,mfraezz/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,jnayak1/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,icereval/osf.io,MerlinZhang/osf.io,jmcarp/osf.io,cwisecarver/osf.io,danielneis/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,mluo613/osf.io,jnayak1/osf.io,chennan47/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,lamdnhan/osf.io,icereval/osf.io,Johnetordoff/osf.io,cosenal/osf.io,reinaH/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,kch8qx/osf.io,KAsante95/osf.io,billyhunt/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,lamdnhan/osf.io,kwierman/osf.io,ZobairAlijan/osf.io,zkraime/osf.io,arpitar/osf.io,MerlinZhang/osf.io,danielneis/osf.io,kch8qx/osf.io,ticklemepierce/osf.io,chennan47/osf.io,jolene-esposito/osf.io,wearpants/osf.io,baylee-d/osf.io,doublebits/osf.io,hmoco/osf.io,acshi/osf.io,hmoco/osf.io,caneruguz/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,hmoco/osf.io,cwisecarver/osf.io,crcresearch/osf.io,HarryRybacki/osf.io,crcresearch/osf.io,mluo613/osf.io,chrisseto/osf.io,sbt9uc/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,mluke93/osf.io,leb2dg/osf.io,caseyrollins/osf.io,adlius/osf.io,danielneis/osf.io,asanfilippo7/osf.io,Nesiehr/osf.io,ZobairAlijan/osf.io,njantrania/osf.io,leb2dg/osf.io,asanfilippo7/osf.io,saradbowman/osf.io,revanthkolli/osf.io,GaryKriebel/osf.io,GaryKriebel/osf.io,doublebits/osf.io,Ghalko/osf.io,dplorimer/osf,brianjgeiger/osf.io,zkraime/osf.io,caseyrygt/osf.io,billyhunt/osf.io,jeffreyliu3230/osf.io,leb2dg/osf.io,chrisseto/osf.io,alexschiller/osf.io,GageGaskins/osf.io,samchrisinger/osf.io,GageGaskins/osf.io
959897478bbda18f02aa6e38f2ebdd837581f1f0
tests/test_sct_verify_signature.py
tests/test_sct_verify_signature.py
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is True assert got_output == 'Verified OK\n' assert got_cmd_res.exitcode == 0 signature_input = b'some invalid signature input' got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is False assert got_output == 'Verification Failure\n' assert got_cmd_res.exitcode == 1
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() assert verify_signature(signature_input, signature, pubkey) is True signature_input = b'some invalid signature input' assert verify_signature(signature_input, signature, pubkey) is False
Fix test for changed SctVerificationResult
Fix test for changed SctVerificationResult
Python
mit
theno/ctutlz,theno/ctutlz
1d10582d622ce6867a85d9e4e8c279ab7e4ab5ab
src/etc/tidy.py
src/etc/tidy.py
#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 config_proc=subprocess.Popen([ "git", "config", "core.autocrlf" ], stdout=subprocess.PIPE) result=config_proc.communicate()[0] autocrlf=result.strip() == b"true" if result is not None else False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
Revert "Don't complain about \r when core.autocrlf is on in Git"
Revert "Don't complain about \r when core.autocrlf is on in Git" This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.
Python
apache-2.0
ejjeong/rust,omasanori/rust,quornian/rust,mvdnes/rust,barosl/rust,aturon/rust,carols10cents/rust,mdinger/rust,AerialX/rust,krzysz00/rust,krzysz00/rust,sarojaba/rust-doc-korean,SiegeLord/rust,l0kod/rust,philyoon/rust,KokaKiwi/rust,nwin/rust,ktossell/rust,victorvde/rust,dwillmer/rust,0x73/rust,waynenilsen/rand,fabricedesre/rust,vhbit/rust,jroesch/rust,andars/rust,ejjeong/rust,avdi/rust,j16r/rust,michaelballantyne/rust-gpu,michaelballantyne/rust-gpu,l0kod/rust,ebfull/rust,XMPPwocky/rust,mitsuhiko/rust,philyoon/rust,kwantam/rust,Ryman/rust,bombless/rust,gifnksm/rust,fabricedesre/rust,defuz/rust,XMPPwocky/rust,bombless/rust,philyoon/rust,zaeleus/rust,pshc/rust,krzysz00/rust,pelmers/rust,andars/rust,michaelballantyne/rust-gpu,mitsuhiko/rust,bhickey/rand,XMPPwocky/rust,robertg/rust,LeoTestard/rust,rohitjoshi/rust,ebfull/rust,P1start/rust,vhbit/rust,dwillmer/rust,l0kod/rust,aepsil0n/rust,barosl/rust,miniupnp/rust,zachwick/rust,zachwick/rust,aidancully/rust,jashank/rust,mahkoh/rust,aidancully/rust,krzysz00/rust,erickt/rust,pelmers/rust,kmcallister/rust,bombless/rust,victorvde/rust,victorvde/rust,reem/rust,emk/rust,ruud-v-a/rust,GBGamer/rust,kwantam/rust,stepancheg/rust-ide-rust,cllns/rust,vhbit/rust,LeoTestard/rust,l0kod/rust,zachwick/rust,avdi/rust,AerialX/rust-rt-minimal,dwillmer/rust,richo/rust,pshc/rust,j16r/rust,kwantam/rust,emk/rust,kimroen/rust,avdi/rust,aneeshusa/rust,carols10cents/rust,victorvde/rust,aturon/rust,avdi/rust,aidancully/rust,ebfull/rust,hauleth/rust,rohitjoshi/rust,philyoon/rust,untitaker/rust,GBGamer/rust,stepancheg/rust-ide-rust,barosl/rust,TheNeikos/rust,SiegeLord/rust,P1start/rust,ebfull/rust,omasanori/rust,andars/rust,seanrivera/rust,pczarn/rust,huonw/rand,ktossell/rust,rohitjoshi/rust,barosl/rust,jroesch/rust,jbclements/rust,AerialX/rust-rt-minimal,erickt/rust,servo/rust,GBGamer/rust,zaeleus/rust,pythonesque/rust,TheNeikos/rust,richo/rust,aidancully/rust,emk/rust,jashank/rust,ktossell/rust,AerialX/rust-rt-minimal,bombless/rust,l0kod/rust,pythonesque/rust,LeoTestard/rust,kmcallister/rust,zubron/rust,seanrivera/rust,jbclements/rust,sarojaba/rust-doc-korean,TheNeikos/rust,KokaKiwi/rust,mahkoh/rust,cllns/rust,erickt/rust,pelmers/rust,aneeshusa/rust,sarojaba/rust-doc-korean,zubron/rust,erickt/rust,zubron/rust,KokaKiwi/rust,bluss/rand,hauleth/rust,defuz/rust,emk/rust,omasanori/rust,victorvde/rust,mihneadb/rust,barosl/rust,sarojaba/rust-doc-korean,ruud-v-a/rust,sae-bom/rust,zaeleus/rust,zachwick/rust,jashank/rust,krzysz00/rust,cllns/rust,aturon/rust,ruud-v-a/rust,ruud-v-a/rust,shepmaster/rand,TheNeikos/rust,gifnksm/rust,kimroen/rust,Ryman/rust,gifnksm/rust,graydon/rust,erickt/rust,servo/rust,aneeshusa/rust,GBGamer/rust,kimroen/rust,hauleth/rust,pshc/rust,jashank/rust,jbclements/rust,mitsuhiko/rust,jroesch/rust,kimroen/rust,miniupnp/rust,bombless/rust,kimroen/rust,pczarn/rust,LeoTestard/rust,untitaker/rust,sae-bom/rust,vhbit/rust,mahkoh/rust,jashank/rust,fabricedesre/rust,omasanori/rust,jbclements/rust,TheNeikos/rust,sarojaba/rust-doc-korean,XMPPwocky/rust,sae-bom/rust,emk/rust,jbclements/rust,quornian/rust,j16r/rust,victorvde/rust,richo/rust,andars/rust,KokaKiwi/rust,aneeshusa/rust,dinfuehr/rust,GBGamer/rust,jroesch/rust,pythonesque/rust,LeoTestard/rust,defuz/rust,mitsuhiko/rust,miniupnp/rust,mdinger/rust,SiegeLord/rust,mihneadb/rust,dwillmer/rust,robertg/rust,dwillmer/rust,AerialX/rust,erickt/rust,0x73/rust,defuz/rust,nwin/rust,Ryman/rust,jbclements/rust,zaeleus/rust,avdi/rust,nwin/rust,kmcallister/rust,erickt/rust,rohitjoshi/rust,aturon/rust,ruud-v-a/rust,dinfuehr/rust,nham/rust,dinfuehr/rust,mitsuhiko/rust,aepsil0n/rust,j16r/rust,quornian/rust,carols10cents/rust,j16r/rust,dinfuehr/rust,l0kod/rust,richo/rust,krzysz00/rust,gifnksm/rust,untitaker/rust,kimroen/rust,pczarn/rust,kmcallister/rust,fabricedesre/rust,ruud-v-a/rust,mvdnes/rust,pczarn/rust,Ryman/rust,mdinger/rust,l0kod/rust,reem/rust,michaelballantyne/rust-gpu,Ryman/rust,jbclements/rust,robertg/rust,jbclements/rust,zubron/rust,P1start/rust,XMPPwocky/rust,jroesch/rust,miniupnp/rust,rprichard/rust,rohitjoshi/rust,0x73/rust,sarojaba/rust-doc-korean,stepancheg/rust-ide-rust,michaelballantyne/rust-gpu,jashank/rust,ejjeong/rust,aepsil0n/rust,aidancully/rust,pythonesque/rust,philyoon/rust,kwantam/rust,dwillmer/rust,dwillmer/rust,achanda/rand,robertg/rust,j16r/rust,mahkoh/rust,pshc/rust,pythonesque/rust,ebfull/rust,omasanori/rust,quornian/rust,graydon/rust,barosl/rust,zachwick/rust,richo/rust,mvdnes/rust,untitaker/rust,P1start/rust,aneeshusa/rust,stepancheg/rust-ide-rust,pczarn/rust,reem/rust,zubron/rust,gifnksm/rust,servo/rust,servo/rust,nham/rust,GBGamer/rust,robertg/rust,SiegeLord/rust,0x73/rust,jashank/rust,rprichard/rust,rprichard/rust,michaelballantyne/rust-gpu,aepsil0n/rust,zubron/rust,reem/rust,pczarn/rust,fabricedesre/rust,andars/rust,zubron/rust,pshc/rust,kimroen/rust,AerialX/rust,mdinger/rust,kwantam/rust,jashank/rust,mahkoh/rust,reem/rust,seanrivera/rust,KokaKiwi/rust,SiegeLord/rust,richo/rust,P1start/rust,0x73/rust,retep998/rand,rprichard/rust,bombless/rust-docs-chinese,untitaker/rust,Ryman/rust,robertg/rust,pshc/rust,carols10cents/rust,quornian/rust,l0kod/rust,omasanori/rust,jroesch/rust,0x73/rust,mitsuhiko/rust,mvdnes/rust,KokaKiwi/rust,pythonesque/rust,aturon/rust,GrahamDennis/rand,AerialX/rust-rt-minimal,arthurprs/rand,ejjeong/rust,mdinger/rust,andars/rust,michaelballantyne/rust-gpu,graydon/rust,sae-bom/rust,emk/rust,fabricedesre/rust,bombless/rust,aneeshusa/rust,vhbit/rust,hauleth/rust,P1start/rust,philyoon/rust,XMPPwocky/rust,zubron/rust,seanrivera/rust,dwillmer/rust,servo/rust,kmcallister/rust,miniupnp/rust,AerialX/rust-rt-minimal,dinfuehr/rust,GBGamer/rust,nham/rust,nham/rust,rprichard/rust,carols10cents/rust,dinfuehr/rust,aepsil0n/rust,nwin/rust,ejjeong/rust,cllns/rust,reem/rust,pshc/rust,kmcallister/rust,pythonesque/rust,AerialX/rust,mvdnes/rust,carols10cents/rust,vhbit/rust,graydon/rust,hauleth/rust,mitsuhiko/rust,quornian/rust,mihneadb/rust,nwin/rust,graydon/rust,cllns/rust,defuz/rust,zachwick/rust,servo/rust,sae-bom/rust,LeoTestard/rust,mihneadb/rust,pelmers/rust,TheNeikos/rust,graydon/rust,avdi/rust,sae-bom/rust,GBGamer/rust,gifnksm/rust,barosl/rust,aturon/rust,ktossell/rust,rohitjoshi/rust,ejjeong/rust,untitaker/rust,mahkoh/rust,mvdnes/rust,jroesch/rust,kwantam/rust,mihneadb/rust,0x73/rust,defuz/rust,stepancheg/rust-ide-rust,P1start/rust,ebfull/rust,j16r/rust,sarojaba/rust-doc-korean,aturon/rust,AerialX/rust,pshc/rust,AerialX/rust-rt-minimal,rprichard/rust,kmcallister/rust,SiegeLord/rust,vhbit/rust,ktossell/rust,stepancheg/rust-ide-rust,mihneadb/rust,nwin/rust,zaeleus/rust,cllns/rust,zaeleus/rust,nwin/rust,miniupnp/rust,stepancheg/rust-ide-rust,aidancully/rust,nham/rust,LeoTestard/rust,seanrivera/rust,hauleth/rust,servo/rust,vhbit/rust,AerialX/rust,jroesch/rust,jbclements/rust,SiegeLord/rust,mdinger/rust,ktossell/rust,miniupnp/rust,aepsil0n/rust,emk/rust,ebfull/rand,pelmers/rust,pczarn/rust,pelmers/rust,nham/rust,nham/rust,miniupnp/rust,ktossell/rust,Ryman/rust,nwin/rust,fabricedesre/rust,seanrivera/rust,quornian/rust
a378649f85f0bc55060ad0238e426f587bc2ff1a
core/exceptions.py
core/exceptions.py
""" exceptions - Core exceptions """ class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider:%s" \ % (provider,) pass
""" exceptions - Core exceptions """ class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider: %s" \ % (provider.location,) pass
Send location only when printing exception (Avoid leaking ID/UUID)
Send location only when printing exception (Avoid leaking ID/UUID)
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
5a8199744bf658d491721b16fea7639303e47d3f
july/people/views.py
july/people/views.py
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404, HttpResponseRedirect from django.core.urlresolvers import reverse def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) return render_to_response('people/profile.html', {"commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': request.user.username}) ) if user == None: raise Http404("User not found") return render_to_response(template_name, {'form':form,}, RequestContext(request))
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404, HttpResponseRedirect from django.core.urlresolvers import reverse def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) return render_to_response('people/profile.html', {"commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user form = EditUserForm(request.POST or None, user=request.user) if form.is_valid(): for key in form.cleaned_data: setattr(user, key, form.cleaned_data.get(key)) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username}) ) if user == None: raise Http404("User not found") return render_to_response(template_name, {'form':form}, RequestContext(request))
Edit view pre-populates with data from user object
Edit view pre-populates with data from user object
Python
mit
ChimeraCoder/GOctober,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,julython/julython.org,julython/julython.org
a8e43dcdbdd00de9d4336385b3f3def1ae5c2515
main/modelx.py
main/modelx.py
# -*- coding: utf-8 -*- import hashlib class BaseX(object): @classmethod def retrieve_one_by(cls, name, value): cls_db_list = cls.query(getattr(cls, name) == value).fetch(1) if cls_db_list: return cls_db_list[0] return None class ConfigX(object): @classmethod def get_master_db(cls): return cls.get_or_insert('master') class UserX(object): def avatar_url(self, size=None): return '//gravatar.com/avatar/%(hash)s?d=identicon&r=x%(size)s' % { 'hash': hashlib.md5((self.email or self.name).encode('utf-8')).hexdigest().lower(), 'size': '&s=%d' % size if size > 0 else '', }
# -*- coding: utf-8 -*- import hashlib class BaseX(object): @classmethod def retrieve_one_by(cls, name, value): cls_db_list = cls.query(getattr(cls, name) == value).fetch(1) if cls_db_list: return cls_db_list[0] return None class ConfigX(object): @classmethod def get_master_db(cls): return cls.get_or_insert('master') class UserX(object): def avatar_url_size(self, size=None): return '//gravatar.com/avatar/%(hash)s?d=identicon&r=x%(size)s' % { 'hash': hashlib.md5((self.email or self.name).encode('utf-8')).hexdigest().lower(), 'size': '&s=%d' % size if size > 0 else '', } avatar_url = property(avatar_url_size)
Update UserX, with back compatibility
Update UserX, with back compatibility
Python
mit
vanessa-bell/hd-kiosk-v2,carylF/lab5,gmist/fix-5studio,lipis/the-smallest-creature,NeftaliYagua/gae-init,gmist/my-gae-init-auth,jakedotio/gae-init,carylF/lab5,lipis/gae-init,lipis/gae-init,lovesoft/gae-init,gae-init/gae-init-docs,mdxs/gae-init,tonyin/optionstg,gmist/my-gae-init,gae-init/gae-init-babel,terradigital/gae-init,lipis/life-line,gae-init/gae-init-upload,gmist/nashi-5studio,CLOUGH/info3180-lab5,topless/gae-init,tiberiucorbu/av-website,Kingclove/lab5info3180,gmist/alice-box,gmist/five-studio2,chineyting/lab5-Info3180,gae-init/phonebook,lipis/meet-notes,lipis/hurry-app,tkstman/lab5,lipis/gae-init,tonyin/optionstg,gae-init/gae-init-docs,gae-init/gae-init-babel,vanessa-bell/hd-kiosk-v2,jakedotio/gae-init,gae-init/gae-init-debug,wodore/wodore-gae,gae-init/gae-init-upload,mdxs/gae-init,d4rr3ll/gae-init-docker,vanessa-bell/hd-kiosk-v2,terradigital/gae-init,jaja14/lab5,wilfriedE/gae-init,gmist/nashi-5studio,tiberiucorbu/av-website,mdxs/gae-init,jaja14/lab5,georgekis/salary,gmist/fix-5studio,JoeyCodinja/INFO3180LAB3,gae-init/gae-init-babel,mdxs/gae-init-babel,gae-init/gae-init,gmist/1businka2,topless/gae-init-upload,gmist/1businka2,dhstack/gae-init,gmist/nashi-5studio,gmist/ctm-5studio,lovesoft/gae-init,lipis/gae-init,JoeyCodinja/INFO3180LAB3,wodore/wodore-gae,gae-init/gae-init,topless/gae-init-upload,gmist/fix-5studio,lipis/hurry-app,mdxs/gae-init-babel,wilfriedE/gae-init,lipis/the-smallest-creature,topless/gae-init-upload,lipis/life-line,lipis/the-smallest-creature,gmist/my-gae-init,NeftaliYagua/gae-init,gae-init/gae-init-docs,d4rr3ll/gae-init-docker,gae-init/gae-init-babel,jakedotio/gae-init,d4rr3ll/gae-init-docker,gmist/ctm-5studio,lovesoft/gae-init,CLOUGH/info3180-lab5,lipis/guestbook,lipis/github-stats,gae-init/gae-init,gmist/fix-5studio,JoeyCodinja/INFO3180LAB3,gae-init/gae-init-debug,d4rr3ll/gae-init-docker,lipis/electron-crash-reporter,lipis/github-stats,topless/gae-init,michals/hurry-app,gae-init/gae-init-docs,wodore/wodore-gae,michals/hurry-app,tkstman/lab5,NeftaliYagua/gae-init,gmist/ctm-5studio,jakedotio/gae-init,gmist/1businka2,lipis/electron-crash-reporter,gae-init/gae-init-upload,mdxs/gae-init-babel,georgekis/salary,michals/hurry-app,gae-init/gae-init-debug,lipis/github-stats,gmist/five-studio2,gmist/ctm-5studio,gae-init/gae-init-debug,JoeyCodinja/INFO3180LAB3,lipis/hurry-app,antotodd/lab5,gmist/alice-box,gae-init/gae-init,dhstack/gae-init,gmist/five-studio2,wilfriedE/gae-init,lipis/life-line,antotodd/lab5,topless/gae-init,gmist/my-gae-init,gae-init/gae-init-upload,gmist/five-studio2,Kingclove/lab5info3180,gmist/my-gae-init,lipis/electron-crash-reporter,chineyting/lab5-Info3180,lipis/meet-notes,mdxs/gae-init-docs,lipis/github-stats,dhstack/gae-init,topless/gae-init,terradigital/gae-init,lipis/meet-notes,tiberiucorbu/av-website,mdxs/gae-init,wodore/wodore-gae,vanessa-bell/hd-kiosk-v2,georgekis/salary
99e9ef79178d6e2dffd8ec7ed12b3edbd8b7d0f1
longclaw/longclawbasket/views.py
longclaw/longclawbasket/views.py
from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) return {"basket": items}
from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) total_price = sum(item.total() for item in items) return {"basket": items, "total_price": total_price}
Add basket total to context
Add basket total to context
Python
mit
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
6cfc94d8a03439c55808090aa5e3a4f35c288887
menpodetect/tests/opencv_test.py
menpodetect/tests/opencv_test.py
from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
from numpy.testing import assert_allclose from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert_allclose(len(pcs), 1) assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
Use assert_allclose so we can see the appveyor failure
Use assert_allclose so we can see the appveyor failure
Python
bsd-3-clause
yuxiang-zhou/menpodetect,jabooth/menpodetect,yuxiang-zhou/menpodetect,jabooth/menpodetect
1f98e497136ce3d9da7e63a6dc7c3f67fedf50b5
observations/views.py
observations/views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') def form_valid(self, form): observation = form.save(commit=False) observation.observer = self.request.observer observation.save() return super(AddObservationView, self).form_valid(form) class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
Save the observation if the form was valid.
Save the observation if the form was valid.
Python
mit
zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net
091ebd935c6145ac233c03bedeb52c65634939f4
Lib/xml/__init__.py
Lib/xml/__init__.py
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """ try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """ __all__ = ["dom", "parsers", "sax"] __version__ = "$Revision$"[1:-1].split()[1] _MINIMUM_XMLPLUS_VERSION = (0, 6, 1) try: import _xmlplus except ImportError: pass else: try: v = _xmlplus.version_info except AttributeError: # _xmlplue is too old; ignore it pass else: if v >= _MINIMUM_XMLPLUS_VERSION: import sys sys.modules[__name__] = _xmlplus else: del v
Include the version-detecting code to allow PyXML to override the "standard" xml package. Require at least PyXML 0.6.1.
Include the version-detecting code to allow PyXML to override the "standard" xml package. Require at least PyXML 0.6.1.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
3a27568211c07cf614aa9865a2f08d2a9b9bfb71
dinosaurs/views.py
dinosaurs/views.py
import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) ret, passwd = api.create_email(connection, email) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED)
import os import json import httplib as http import tornado.web import tornado.ioloop from dinosaurs import api from dinosaurs import settings class SingleStatic(tornado.web.StaticFileHandler): def initialize(self, path): self.dirname, self.filename = os.path.split(path) super(SingleStatic, self).initialize(self.dirname) def get(self, path=None, include_body=True): super(SingleStatic, self).get(self.filename, include_body) class DomainAPIHandler(tornado.web.RequestHandler): def get(self): self.write({ 'availableDomains': settings.DOMAINS.keys() }) class EmailAPIHandler(tornado.web.RequestHandler): def write_error(self, status_code, **kwargs): self.finish({ "code": status_code, "message": self._reason, }) def post(self): try: req_json = json.loads(self.request.body) except ValueError: raise tornado.web.HTTPError(http.BAD_REQUEST) email = req_json.get('email') domain = req_json.get('domain') connection = api.get_connection(domain) if not email or not domain or not connection: raise tornado.web.HTTPError(http.BAD_REQUEST) try: ret, passwd = api.create_email(connection, email) except api.YandexException as e: if e.message != 'occupied': raise self.write({}) raise tornado.web.HTTPError(http.FORBIDDEN) self.write({ 'password': passwd, 'email': ret['login'], 'domain': ret['domain'] }) self.set_status(http.CREATED)
Return errors in json only
Return errors in json only
Python
mit
chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy
f574e19b14ff861c45f6c66c64a2570bdb0e3a3c
crawl_comments.py
crawl_comments.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __doc__ = ''' Crawl comment from nicovideo.jp Usage: main_crawl.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
#!/usr/bin/env python # -*- coding: utf-8 -*- __doc__ = ''' Crawl comment from nicovideo.jp Usage: crawl_comments.py [--sqlite <sqlite>] [--csv <csv>] Options: --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # コマンドライン引数の取得 args = docopt(__doc__) sqlite_path = args['--sqlite'] csv_path = args['--csv'] ncrawler = NicoCrawler() ncrawler.connect_sqlite(sqlite_path) url = 'http://ch.nicovideo.jp/2016winter_anime' df = ncrawler.get_all_video_url_of_season(url) ncrawler.initialize_csv_from_db(csv_path) # # デイリーランキング1~300位の動画を取得する # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, csv_path, max_page=3) # ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
Apply change of file name
Apply change of file name
Python
mit
tosh1ki/NicoCrawler
317926c18ac2e139d2018acd767d10b4f53428f3
installer/installer_config/views.py
installer/installer_config/views.py
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
Remove unneeded post method from CreateEnvProfile view
Remove unneeded post method from CreateEnvProfile view
Python
mit
ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer
c24dbc2d4d8b59a62a68f326edb350b3c633ea25
interleaving/interleaving_method.py
interleaving/interleaving_method.py
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return a list of pairs of ranker indices in which element (i, j) indicates i won j. e.g. a result [(1, 0), (2, 1), (2, 0)] indicates ranker 1 won ranker 0, and ranker 2 won ranker 0 as well as ranker 1. ''' raise NotImplementedError()
Change the comment of InterleavingMethod.evaluate
Change the comment of InterleavingMethod.evaluate
Python
mit
mpkato/interleaving
85769162560d83a58ccc92f818559ddd3dce2a09
pages/index.py
pages/index.py
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: courses = Course.GetAllCoursesIds() return renderer.main(courses) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main() else: return renderer.index(True)
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(True)
Fix another bug in the authentication
Fix another bug in the authentication
Python
agpl-3.0
layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious
6d8dbb6621da2ddfffd58303131eb6cda345e37c
pombola/south_africa/urls.py
pombola/south_africa/urls.py
from django.conf.urls import patterns, include, url from pombola.south_africa.views import LatLonDetailView,SAPlaceDetailSub urlpatterns = patterns('pombola.south_africa.views', url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'), url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'), )
from django.conf.urls import patterns, include, url from pombola.core.views import PersonDetailSub from pombola.south_africa.views import LatLonDetailView,SAPlaceDetailSub urlpatterns = patterns('pombola.south_africa.views', url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'), url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'), url(r'^person/(?P<slug>[-\w]+)/$', PersonDetailSub.as_view(), { 'sub_page': 'experience' }, name='person'), )
Make person experience the default tab for ZA
Make person experience the default tab for ZA
Python
agpl-3.0
hzj123/56th,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,hzj123/56th,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,geoffkilpin/pombola,ken-muturi/pombola,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,ken-muturi/pombola,ken-muturi/pombola,ken-muturi/pombola,geoffkilpin/pombola,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola
84ee720fd2d8403de5f49c54fc41bfcb67a78f78
stdnum/tr/__init__.py
stdnum/tr/__init__.py
# __init__.py - collection of Turkish numbers # coding: utf-8 # # Copyright (C) 2016 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Turkish numbers."""
# __init__.py - collection of Turkish numbers # coding: utf-8 # # Copyright (C) 2016 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Turkish numbers.""" from stdnum.tr import vkn as vat # noqa: F401
Add missing vat alias for Turkey
Add missing vat alias for Turkey
Python
lgpl-2.1
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
cf07c34fe3a3d7b8767e50e77e609253dd177cff
moulinette/utils/serialize.py
moulinette/utils/serialize.py
import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): return str(o) # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o)
import logging from json.encoder import JSONEncoder import datetime logger = logging.getLogger('moulinette.utils.serialize') # JSON utilities ------------------------------------------------------- class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder Extend default JSON encoder to recognize more types and classes. It will never raise if the object can't be encoded and return its repr instead. The following objects and types are supported: - set: converted into list """ def default(self, o): """Return a serializable object""" # Convert compatible containers into list if isinstance(o, set) or ( hasattr(o, '__iter__') and hasattr(o, 'next')): return list(o) # Convert compatible containers into list if isinstance(o, datetime.datetime) or isinstance(o, datetime.date): return o.isoformat() # Return the repr for object that json can't encode logger.warning('cannot properly encode in JSON the object %s, ' 'returned repr is: %r', type(o), o) return repr(o)
Use isoformat date RFC 3339
[enh] Use isoformat date RFC 3339
Python
agpl-3.0
YunoHost/moulinette
396ab20874a0c3492482a8ae03fd7d61980917a5
chatterbot/adapters/logic/closest_match.py
chatterbot/adapters/logic/closest_match.py
# -*- coding: utf-8 -*- from fuzzywuzzy import fuzz from .base_match import BaseMatchAdapter class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter logic adapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement self.logger.info( u'No statements have known responses. ' + u'Choosing a random response to return.' ) return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text.lower(), statement.text.lower()) if ratio > confidence: confidence = ratio closest_match = statement # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
# -*- coding: utf-8 -*- from fuzzywuzzy import fuzz from .base_match import BaseMatchAdapter class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter logic adapter selects a known response to an input by searching for a known statement that most closely matches the input based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement self.logger.info( u'No statements have known responses. ' + u'Choosing a random response to return.' ) return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text.lower(), statement.text.lower()) if ratio > confidence: confidence = ratio closest_match = statement # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
Update closest match adapter docstring.
Update closest match adapter docstring.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot,davizucon/ChatterBot
2947fe97d466872de05ada289d9172f41895969c
tests/templates/components/test_radios_with_images.py
tests/templates/components/test_radios_with_images.py
import json def test_govuk_frontend_jinja_overrides_on_design_system_v3(): with open("package.json") as package_file: package_json = json.load(package_file) assert package_json["dependencies"]["govuk-frontend"].startswith("3."), ( "After upgrading the Design System, manually validate that " "`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`" "are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the " "rendering process." )
import json from importlib import metadata from packaging.version import Version def test_govuk_frontend_jinja_overrides_on_design_system_v3(): with open("package.json") as package_file: package_json = json.load(package_file) govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"]) govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja")) # This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are. # Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/ correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0") correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0") assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, ( "After upgrading either of the Design System packages, you must validate that " "`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`" "are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the " "rendering process." )
Update GOV.UK Frontend/Jinja lib test
Update GOV.UK Frontend/Jinja lib test Check both the javascript and python packages, and make sure they're both on our expected versions. If not, prompt the developer to check macros.
Python
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
15ae458f7cf1a8257967b2b3b0ceb812547c4766
IPython/utils/tests/test_pycolorize.py
IPython/utils/tests/test_pycolorize.py
"""Test suite for our color utilities. Authors ------- * Min RK """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- def test_unicode_colorize(): p = Parser() f1 = p.format('1/0', 'str') f2 = p.format(u'1/0', 'str') nt.assert_equal(f1, f2)
# coding: utf-8 """Test suite for our color utilities. Authors ------- * Min RK """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # third party import nose.tools as nt # our own from IPython.utils.PyColorize import Parser import io #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- sample = u""" def function(arg, *args, kwarg=True, **kwargs): ''' this is docs ''' pass is True False == None with io.open(ru'unicode'): raise ValueError("\n escape \r sequence") print("wěird ünicoðe") class Bar(Super): def __init__(self): super(Bar, self).__init__(1**2, 3^4, 5 or 6) """ def test_loop_colors(): for scheme in ('Linux', 'NoColor','LightBG'): def test_unicode_colorize(): p = Parser() f1 = p.format('1/0', 'str', scheme=scheme) f2 = p.format(u'1/0', 'str', scheme=scheme) nt.assert_equal(f1, f2) def test_parse_sample(): """and test writing to a buffer""" buf = io.StringIO() p = Parser() p.format(sample, buf, scheme=scheme) buf.seek(0) f1 = buf.read() nt.assert_not_in('ERROR', f1) def test_parse_error(): p = Parser() f1 = p.format(')', 'str', scheme=scheme) if scheme != 'NoColor': nt.assert_in('ERROR', f1) yield test_unicode_colorize yield test_parse_sample yield test_parse_error
Test more edge cases of the highlighting parser
Test more edge cases of the highlighting parser
Python
bsd-3-clause
ipython/ipython,ipython/ipython
6cb0822aade07999d54e5fcd19eb2c7322abc80a
measurement/admin.py
measurement/admin.py
from django.contrib import admin from .models import Measurement admin.site.register(Measurement)
from django.contrib import admin from .models import Measurement class MeasurementAdmin(admin.ModelAdmin): model = Measurement def get_queryset(self, request): return super(MeasurementAdmin, self).get_queryset(request).select_related('patient__user') admin.site.register(Measurement, MeasurementAdmin)
Improve performance @ Measurement Admin
Improve performance @ Measurement Admin
Python
mit
sigurdsa/angelika-api
b9b3837937341e6b1b052bbfdd979e3bb57d87c4
tests/integration/test_with_ssl.py
tests/integration/test_with_ssl.py
from . import base class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
import os from pymco.test import ctxt from . import base FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures') class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', 'plugin.ssl_server_private': os.path.join(FIXTURES_PATH, 'server-private.pem'), 'securityprovider': 'ssl', 'plugin.ssl_client_cert_dir': FIXTURES_PATH, } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
Fix SSL security provider integration tests
Fix SSL security provider integration tests They were running with none provider instead.
Python
bsd-3-clause
rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective
66284e57accec5977d606fc91a0b28177b352eb4
test/test_producer.py
test/test_producer.py
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") @pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4']) def test_end_to_end(kafka_broker, compression): # LZ4 requires 0.8.2 if compression == 'lz4' and version() < (0, 8, 2): return connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, compression_type=compression, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
Add end-to-end integration testing for all compression types
Add end-to-end integration testing for all compression types
Python
apache-2.0
dpkp/kafka-python,ohmu/kafka-python,Yelp/kafka-python,ohmu/kafka-python,zackdever/kafka-python,Aloomaio/kafka-python,DataDog/kafka-python,Aloomaio/kafka-python,wikimedia/operations-debs-python-kafka,mumrah/kafka-python,scrapinghub/kafka-python,mumrah/kafka-python,dpkp/kafka-python,Yelp/kafka-python,scrapinghub/kafka-python,wikimedia/operations-debs-python-kafka,zackdever/kafka-python
f127f0e9bb0b8778feafbdbc1fa68e79a923d639
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()]))
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper products and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] product_dict = {} for product in items: product_id = product['link'].split('/')[-1] product_dict[str(product_id)] = product for product in Product.objects.all(): self.assertEqual( product_dict[str(product.id)]['description'], product.description) self.assertEqual( product_dict[str(product.id)]['name'], product.name) self.assertEqual( product_dict[str(product.id)]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( product_dict[str(product.id)]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(product_dict[str(product.id)]['preparations']), sort([prep.name for prep in product.preparations.all()]))
Update product listing test to use product ids rather than index
Update product listing test to use product ids rather than index
Python
apache-2.0
osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api
12b34fc09baa5060495e25e57680d1f6170559c5
addons/bestja_configuration_fpbz/__openerp__.py
addons/bestja_configuration_fpbz/__openerp__.py
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_account_deletion', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_stores', 'bestja_requests', 'bestja_detailed_reports', 'bestja_offers', 'bestja_offers_by_org', 'bestja_files', 'quizzes', 'bestja_organization_warehouse', 'bestja_age_verification', 'bestja_frontend_fpbz', 'bestja_page_fixtures_fpbz', ], 'data': [ 'data.xml', ], 'application': True, }
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_account_deletion', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_stores', 'bestja_requests', 'bestja_detailed_reports', 'bestja_estimation_reports', 'bestja_offers', 'bestja_offers_by_org', 'bestja_files', 'quizzes', 'bestja_organization_warehouse', 'bestja_age_verification', 'bestja_frontend_fpbz', 'bestja_page_fixtures_fpbz', ], 'data': [ 'data.xml', ], 'application': True, }
Enable estimation reports for FPBŻ
Enable estimation reports for FPBŻ
Python
agpl-3.0
KamilWo/bestja,EE/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,EE/bestja,KamilWo/bestja,EE/bestja,KamilWo/bestja
fc75f5843af70c09e0d63284277bf88689cbb06d
invocations/docs.py
invocations/docs.py
import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task def docs(clean=False, browse=False): if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body()
import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run("rm -rf %s" % build) @task def browse_docs(): run("open %s" % os.path.join(build, 'index.html')) @task def api_docs(target, output="api", exclude=""): """ Runs ``sphinx-apidoc`` to autogenerate your API docs. Must give target directory/package as ``target``. Results are written out to ``docs/<output>`` (``docs/api`` by default). To exclude certain output files from the final build give ``exclude`` as a comma separated list of file paths. """ output = os.path.join('docs', output) # Have to make these absolute or apidoc is dumb :( exclude = map( lambda x: os.path.abspath(os.path.join(os.getcwd(), x)), exclude.split(',') ) run("sphinx-apidoc -o %s %s %s" % (output, target, ' '.join(exclude))) @task def docs(clean=False, browse=False, api_target=None, api_output=None, api_exclude=None): """ Build Sphinx docs, optionally ``clean``ing and/or ``browse``ing. Can also build API docs by giving ``api_target`` and optionally ``api_output`` and/or ``api_exclude``. """ if api_target: kwargs = {'target': api_target} if api_output: kwargs['output'] = api_output if api_exclude: kwargs['exclude'] = api_exclude api_docs.body(**kwargs) if clean: clean_docs.body() run("sphinx-build %s %s" % (docs_dir, build), pty=True) if browse: browse_docs.body()
Add apidoc to doc building
Add apidoc to doc building
Python
bsd-2-clause
mrjmad/invocations,pyinvoke/invocations,alex/invocations,singingwolfboy/invocations
a9ac098ec492739f37005c9bd6278105df0261c5
parliamentsearch/items.py
parliamentsearch/items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field()
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class MemberofParliament(scrapy.Item): """ Data structure to define Member of Parliament information """ mp_id = scrapy.Field() mp_name = scrapy.Field() mp_constituency = scrapy.Field() mp_party = scrapy.Field() mp_photo = scrapy.Field() class RajyaSabhaQuestion(scrapy.Item): """ Data structure to define a Rajya Sabha question """ q_no = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() class LokSabhaQuestion(scrapy.Item): """ Data structure to define a Lok Sabha question """ q_no = scrapy.Field() q_session = scrapy.Field() q_type = scrapy.Field() q_date = scrapy.Field() q_ministry = scrapy.Field() q_member = scrapy.Field() q_subject = scrapy.Field() q_url = scrapy.Field() q_annex = scrapy.Field()
Add fields to save question url and annexure links
Add fields to save question url and annexure links Details of each question is in another link and some questions have annexures (in English/Hindi), add fields to save all these items Signed-off-by: Arun Siluvery <66692e34e783869a1e5829b4c5eee5e1a471c4f7@gmail.com>
Python
mit
mthipparthi/parliament-search
376b8aa5b77066e06c17f41d65fe32a3c2bdef1f
geo.py
geo.py
#! /usr/bin/python3 # -*- coding-utf-8 -*- """ This script transform a md into a plain html in the context of a documentation for Kit&Pack. """ import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader()
#! /usr/bin/python3 # -*- coding-utf-8 -*- """ This script transform a md into a plain html in the context of a documentation for Kit&Pack. """ import mmap import yaml print("---------------------------- geo --") print("-- by antoine.delhomme@espci.org --") print("-----------------------------------") doc_in = "./001-v2-doc.md" class geoReader(): def __init__(self, doc_in): self.doc_in = doc_in self.header = None self.header_limit = -1 def __enter__(self): """Open the file. """ self.f = open(self.doc_in, 'r') return self def __exit__(self, type, value, traceback): """Close the file. """ self.f.close() def parseHeader(self): """Parse the header of the file. """ s = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ) self.header_limit = s.find(b'---') if self.header_limit != -1: self.header = yaml.load(s[0:self.header_limit]) print(self.header['name']) else: print("Cannot load the header") # Read the document with geoReader(doc_in) as g: g.parseHeader()
Add a default value to the header limit
Add a default value to the header limit
Python
mit
a2ohm/geo
fdae17a50223c2f9b8ba4a665fc24726e2c2ce14
tests/lib/es_tools.py
tests/lib/es_tools.py
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200").json()["tagline"] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post(url, headers=headers, data=body)
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200", auth=("elastic", "changeme")).json()[ "tagline" ] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post( url, headers=headers, data=body, auth=("elastic", "changeme") )
Add auth header to the fixture loader
Add auth header to the fixture loader It seems to work fine with the unauthenticated es instance
Python
mit
matthewfranglen/postgres-elasticsearch-fdw
bafdbd28e35d80d28bfb82c23532533cb2915066
fuel/exceptions.py
fuel/exceptions.py
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- message : str The error message to be associated with this exception. filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
Add docs for MissingInputFiles 'message' arg.
Add docs for MissingInputFiles 'message' arg.
Python
mit
hantek/fuel,rodrigob/fuel,dmitriy-serdyuk/fuel,codeaudit/fuel,udibr/fuel,mjwillson/fuel,dribnet/fuel,capybaralet/fuel,aalmah/fuel,glewis17/fuel,glewis17/fuel,vdumoulin/fuel,dmitriy-serdyuk/fuel,dwf/fuel,bouthilx/fuel,mila-udem/fuel,chrishokamp/fuel,udibr/fuel,janchorowski/fuel,dwf/fuel,dribnet/fuel,markusnagel/fuel,aalmah/fuel,markusnagel/fuel,orhanf/fuel,capybaralet/fuel,rodrigob/fuel,dhruvparamhans/fuel,dhruvparamhans/fuel,janchorowski/fuel,mila-udem/fuel,bouthilx/fuel,harmdevries89/fuel,hantek/fuel,harmdevries89/fuel,chrishokamp/fuel,codeaudit/fuel,orhanf/fuel,vdumoulin/fuel,mjwillson/fuel
0fdb93fb73142315fe404b9a161ef19af0d920cd
tests/test_bawlerd.py
tests/test_bawlerd.py
import io import os from textwrap import dedent from pg_bawler import bawlerd class TestBawlerdConfig: def test_build_config_location_list(self): assert not bawlerd.conf.build_config_location_list(locations=()) user_conf = os.path.join( os.path.expanduser('~'), bawlerd.conf.DEFAULT_CONFIG_FILENAME) system_conf = os.path.join( '/etc/pg_bawler', bawlerd.conf.DEFAULT_CONFIG_FILENAME) assert user_conf in bawlerd.conf.build_config_location_list() assert system_conf in bawlerd.conf.build_config_location_list() def test__load_file(self): config = bawlerd.conf._load_file(io.StringIO(dedent("""\ logging: formatters: standard: format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\" handlers: default: level: "INFO" formatter: standard class: logging.StreamHandler loggers: "": handlers: ["default"] level: INFO propagate: True """))) assert 'logging' in config
import io import os from textwrap import dedent from pg_bawler import bawlerd class TestBawlerdConfig: def test_build_config_location_list(self): assert not bawlerd.conf.build_config_location_list(locations=()) user_conf = os.path.join( os.path.expanduser('~'), bawlerd.conf.DEFAULT_CONFIG_FILENAME) system_conf = os.path.join( '/etc/pg_bawler', bawlerd.conf.DEFAULT_CONFIG_FILENAME) assert user_conf in bawlerd.conf.build_config_location_list() assert system_conf in bawlerd.conf.build_config_location_list() def test__load_file(self): config = bawlerd.conf._load_file(io.StringIO(dedent("""\ logging: formatters: standard: format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\" handlers: default: level: "INFO" formatter: standard class: logging.StreamHandler loggers: "": handlers: ["default"] level: INFO propagate: True """))) assert 'logging' in config def test_read_config_files(self): config_base = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'configs') locations = [ os.path.join(config_base, 'etc'), os.path.join(config_base, 'home'), ] config = bawlerd.conf.read_config_files( bawlerd.conf.build_config_location_list(locations=locations)) assert config['common']['listen_timeout'] == 40 assert 'logging' in config
Add simple test for config builder
Add simple test for config builder Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
Python
bsd-3-clause
beezz/pg_bawler,beezz/pg_bawler
ea3ad65d3d0976ec24c15703fafacb805a6b5351
students/psbriant/final_project/clean_data.py
students/psbriant/final_project/clean_data.py
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Code for Final Project """ import pandas from datetime import datetime def clean(data): """ Take in data and return cleaned version. """ # Remove Date Values column data = data.drop(["Date Value"], axis=1) # Determine what values are missing # empty = data.apply(lambda col: pandas.isnull(col)) return data def find_low_water_use(data): """ """ under100 = data[(data["90012"] <= 100) & (data["90013"] <= 100)] print(under100) under25 = data[(data["90012"] <= 25) & (data["90013"] <= 25)] print(under25) def main(): """ """ # Connect to file. data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv") cleaned_data = clean(data) find_low_water_use(cleaned_data) if __name__ == '__main__': main()
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Code for Final Project """ import pandas import matplotlib.pyplot as plt from datetime import datetime def clean(data): """ Take in data and return cleaned version. """ # Remove Date Values column data = data.drop(["Date Value"], axis=1) # Determine what values are missing # empty = data.apply(lambda col: pandas.isnull(col)) return data def find_low_water_use(data): """ """ under100 = data[(data["90012"] <= 100) & (data["90013"] <= 100)] print(under100) under25 = data[(data["90012"] <= 25) & (data["90013"] <= 25)] print(under25) def plot_zipcode(data, zipcode): """ """ # data["90012"].plot(kind="bar", rot=10) plt.plot(data[zipcode]) plt.show() def main(): """ """ # Connect to file. data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv") cleaned_data = clean(data) # find_low_water_use(cleaned_data) plot_zipcode(cleaned_data, "90012") # cleaned_data["90012"].plot(kind="bar", rot=10) # cleaned_data["90012"].hist() # plt.plot(cleaned_data["90012"]) # plt.plot([1, 2, 3, 4]) if __name__ == '__main__': main()
Add simple plots of downtown LA wateruse.
Add simple plots of downtown LA wateruse.
Python
unlicense
UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016
c99e0ac2e463302d41838f11ea28ea8a62990671
wafer/kv/serializers.py
wafer/kv/serializers.py
from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs)
from django.core.exceptions import PermissionDenied from rest_framework import serializers from wafer.kv.models import KeyValue class KeyValueSerializer(serializers.ModelSerializer): class Meta: model = KeyValue fields = ('group', 'key', 'value') # There doesn't seem to be a better way of handling the problem # of filtering the groups. # See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985 # and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292 def __init__(self, *args, **kwargs): # Explicitly fail with a hopefully informative error message # if there is no request. This is for introspection tools which # call serializers without a request if 'request' not in kwargs['context']: raise PermissionDenied("No request information provided." "The KeyValue API isn't available without " "an authorized user") user = kwargs['context']['request'].user # Limit to groups shown to those we're a member of groups = self.fields['group'] groups.queryset = user.groups super(KeyValueSerializer, self).__init__(*args, **kwargs)
Add catchall fields property to KeyValueSerializer
Add catchall fields property to KeyValueSerializer With the latest django-restframework, not explicitly setting the fields for a serializer causes errors. This explicitly sets the fields to those of the model.
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
f802111f1f241444f874119e5949f3da4abd1c85
python/raindrops/raindrops.py
python/raindrops/raindrops.py
def raindrops(number): if is_three_a_factor(number): return "Pling" if is_five_a_factor(number): return "Plang" return "{}".format(number) def is_three_a_factor(number): return number % 3 == 0 def is_five_a_factor(number): return number % 5 == 0
def raindrops(number): if is_three_a_factor(number): return "Pling" if is_five_a_factor(number): return "Plang" if is_seven_a_factor(number): return "Plong" return "{}".format(number) def is_three_a_factor(number): return number % 3 == 0 def is_five_a_factor(number): return number % 5 == 0 def is_seven_a_factor(number): return number % 7 == 0
Handle 7 as a factor
Handle 7 as a factor
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
bb86433e80c1361b57c58fb32a2e250e915b1b05
thinglang/__init__.py
thinglang/__init__.py
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'include') def collect_includes(): files = [os.path.join(BASE_DIR, path) for path in os.listdir(BASE_DIR)] return '\n' + '\n'.join(open(f).read() for f in files) def run(source): if not source: raise ValueError('Source cannot be empty') source = (source + collect_includes()).strip().replace(' ' * 4, '\t') utils.print_header('Source', source) lexical_groups = list(lexer(source)) ast = parse(lexical_groups) Simplifier(ast).run() utils.print_header('Parsed AST', ast.tree()) Analyzer(ast).run() with ExecutionEngine(ast) as engine: engine.execute() return engine.results()
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'include') def collect_includes(): files = [os.path.join(BASE_DIR, path) for path in os.listdir(BASE_DIR)] return '\n' + '\n'.join(open(f).read() for f in files) def run(source): if not source: raise ValueError('Source cannot be empty') source = (source + collect_includes()).strip().replace(' ' * 4, '\t') utils.print_header('Source', source) lexical_groups = list(lexer(source)) ast = parse(lexical_groups) Simplifier(ast).run() utils.print_header('C++ Transpilation', ast.transpile_children()) utils.print_header('Parsed AST', ast.tree()) Analyzer(ast).run() with ExecutionEngine(ast) as engine: engine.execute() return engine.results()
Print C++ code during parsing
Print C++ code during parsing
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
baacda228682a50acc5a4528d43f5d3a88c7c6ec
salt/client/netapi.py
salt/client/netapi.py
# encoding: utf-8 ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) multiprocessing.Process(target=netapi[fun]).start()
# encoding: utf-8 ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing import signal # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts self.processes = [] def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) p = multiprocessing.Process(target=netapi[fun]) p.start() self.processes.append(p) # make sure to kill the subprocesses if the parent is killed signal.signal(signal.SIGTERM, self.kill_children) def kill_children(self, *args): ''' Kill all of the children ''' for p in self.processes: p.terminate() p.join()
Make sure to not leave hanging children processes if the parent is killed
Make sure to not leave hanging children processes if the parent is killed
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
a3b119e14df4aff213231492470587f88457a241
setuptools/command/upload.py
setuptools/command/upload.py
import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( self.password or self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password
import getpass from distutils.command import upload as orig class upload(orig.upload): """ Override default upload behavior to obtain password in a variety of different ways. """ def finalize_options(self): orig.upload.finalize_options(self) # Attempt to obtain password. Short circuit evaluation at the first # sign of success. self.password = ( self.password or self._load_password_from_keyring() or self._prompt_for_password() ) def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') password = keyring.get_password(self.repository, self.username) except Exception: password = None finally: return password def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ password = None try: while not password: password = getpass.getpass() except (Exception, KeyboardInterrupt): password = None finally: return password
Add carriage return for symmetry
Add carriage return for symmetry
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
0b8cc130f00b51b18e55805f82ba661fdf66fba6
saml2idp/saml2idp_metadata.py
saml2idp/saml2idp_metadata.py
""" Django Settings that more closely resemble SAML Metadata. Detailed discussion is in doc/SETTINGS_AND_METADATA.txt. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): available_keys = set(keys).intersection(set(config.keys())) if not available_keys: raise ImproperlyConfigured( 'one of the followin keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME]) check_configuration_contains(config=config, keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME]) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
""" Django Settings that more closely resemble SAML Metadata. Detailed discussion is in doc/SETTINGS_AND_METADATA.txt. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured CERTIFICATE_DATA = 'certificate_data' CERTIFICATE_FILENAME = 'certificate_file' PRIVATE_KEY_DATA = 'private_key_data' PRIVATE_KEY_FILENAME = 'private_key_file' def check_configuration_contains(config, keys): available_keys = frozenset(keys).intersection(frozenset(config.keys())) if not available_keys: raise ImproperlyConfigured( 'one of the following keys is required but none was ' 'specified: {}'.format(keys)) if len(available_keys) > 1: raise ImproperlyConfigured( 'found conflicting configuration: {}. Only one key can be used at' 'a time.'.format(available_keys)) def validate_configuration(config): check_configuration_contains(config=config, keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME)) check_configuration_contains(config=config, keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME)) try: SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG except: raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.') else: validate_configuration(SAML2IDP_CONFIG) try: SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES except: raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
Implement suggested changes in PR review
Implement suggested changes in PR review
Python
mit
mobify/dj-saml-idp,mobify/dj-saml-idp,mobify/dj-saml-idp
b6c63bedc6fcd2294aae60643f41df4acb2ee681
pdfminer/pdfcolor.py
pdfminer/pdfcolor.py
import collections from .psparser import LIT import six #Python 2+3 compatibility ## PDFColorSpace ## LITERAL_DEVICE_GRAY = LIT('DeviceGray') LITERAL_DEVICE_RGB = LIT('DeviceRGB') LITERAL_DEVICE_CMYK = LIT('DeviceCMYK') class PDFColorSpace(object): def __init__(self, name, ncomponents): self.name = name self.ncomponents = ncomponents return def __repr__(self): return '<PDFColorSpace: %s, ncomponents=%d>' % (self.name, self.ncomponents) PREDEFINED_COLORSPACE = collections.OrderedDict() for (name, n) in [ ('CalRGB', 3), ('CalGray', 1), ('Lab', 3), ('DeviceRGB', 3), ('DeviceCMYK', 4), ('DeviceGray', 1), ('Separation', 1), ('Indexed', 1), ('Pattern', 1), ]: PREDEFINED_COLORSPACE[name]=PDFColorSpace(name, n)
import collections from .psparser import LIT import six #Python 2+3 compatibility ## PDFColorSpace ## LITERAL_DEVICE_GRAY = LIT('DeviceGray') LITERAL_DEVICE_RGB = LIT('DeviceRGB') LITERAL_DEVICE_CMYK = LIT('DeviceCMYK') class PDFColorSpace(object): def __init__(self, name, ncomponents): self.name = name self.ncomponents = ncomponents return def __repr__(self): return '<PDFColorSpace: %s, ncomponents=%d>' % (self.name, self.ncomponents) PREDEFINED_COLORSPACE = collections.OrderedDict() for (name, n) in [ ('DeviceGray', 1), # default value first ('CalRGB', 3), ('CalGray', 1), ('Lab', 3), ('DeviceRGB', 3), ('DeviceCMYK', 4), ('Separation', 1), ('Indexed', 1), ('Pattern', 1), ]: PREDEFINED_COLORSPACE[name]=PDFColorSpace(name, n)
Make DeviceGray the default color as it should be
Make DeviceGray the default color as it should be
Python
mit
goulu/pdfminer,pdfminer/pdfminer.six
70ba84dc485ed3db4ccf5008db87b2c9f003634b
tests/fixtures/__init__.py
tests/fixtures/__init__.py
"""Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). FILE_CONTENT = FILE_PATH.read_text().strip() JSON_FILE_CONTENT = JSON_FILE_PATH.read_text() BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT
"""Test data""" from pathlib import Path def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ return str(path).replace('\\', '\\\\\\') FIXTURES_ROOT = Path(__file__).parent FILE_PATH = FIXTURES_ROOT / 'test.txt' JSON_FILE_PATH = FIXTURES_ROOT / 'test.json' BIN_FILE_PATH = FIXTURES_ROOT / 'test.bin' FILE_PATH_ARG = patharg(FILE_PATH) BIN_FILE_PATH_ARG = patharg(BIN_FILE_PATH) JSON_FILE_PATH_ARG = patharg(JSON_FILE_PATH) # Strip because we don't want new lines in the data so that we can # easily count occurrences also when embedded in JSON (where the new # line would be escaped). FILE_CONTENT = FILE_PATH.read_text('utf8').strip() JSON_FILE_CONTENT = JSON_FILE_PATH.read_text('utf8') BIN_FILE_CONTENT = BIN_FILE_PATH.read_bytes() UNICODE = FILE_CONTENT
Fix fixture encoding on Windows
Fix fixture encoding on Windows
Python
bsd-3-clause
PKRoma/httpie,jakubroztocil/httpie,jkbrzt/httpie,jakubroztocil/httpie,jkbrzt/httpie,jakubroztocil/httpie,jkbrzt/httpie,PKRoma/httpie
4be668a7d8cdb692c20be2eabf65c20e294e16a8
scopus/utils/get_encoded_text.py
scopus/utils/get_encoded_text.py
# Namespaces for Scopus XML ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: return container.find(xpath, ns).text except AttributeError: return None
# Namespaces for Scopus XML ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd', 'ait': "http://www.elsevier.com/xml/ani/ait", 'cto': "http://www.elsevier.com/xml/cto/dtd", 'xocs': "http://www.elsevier.com/xml/xocs/dtd", 'ce': 'http://www.elsevier.com/xml/ani/common', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'xsi': "http://www.w3.org/2001/XMLSchema-instance", 'dc': 'http://purl.org/dc/elements/1.1/', 'atom': 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'} def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ try: return "".join(container.find(xpath, ns).itertext()) except AttributeError: return None
Use itertext() to skip children in elements with text
Use itertext() to skip children in elements with text
Python
mit
scopus-api/scopus,jkitchin/scopus