commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
74652fd620f33231e4e3086d4b461c2cdf18bfba | conjureup/controllers/vspheresetup/common.py | conjureup/controllers/vspheresetup/common.py | from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.get_datacenters():
if dc.name == app.provider.region:
self.datacenter = dc
def finish(self, data):
app.provider.model_defaults = {
'primary-network': data['primary-network'],
'external-network': data['external-network'],
'datastore': data['datastore']
}
return controllers.use('controllerpicker').render()
| from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.get_datacenters():
if dc == app.provider.region:
self.datacenter = dc
def finish(self, data):
app.provider.model_defaults = {
'primary-network': data['primary-network'],
'external-network': data['external-network'],
'datastore': data['datastore']
}
return controllers.use('controllerpicker').render()
| Fix datacenter listing for r34lz | Fix datacenter listing for r34lz
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
| Python | mit | Ubuntu-Solutions-Engineering/conjure,Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,conjure-up/conjure-up,ubuntu/conjure-up,conjure-up/conjure-up |
532b0809b040318abbb8e62848f18ad0cdf72547 | src/workspace/workspace_managers.py | src/workspace/workspace_managers.py | from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace
def ref_from_workspace(workspace):
if isinstance(workspace, WorkSpace):
return 'group/' + str(workspace.id)
elif isinstance(workspace, PublishedWorkSpace):
return 'group_published/' + str(workspace.id)
class OrganizationWorkspaceManager:
def get_id(self):
return 'ezweb_organizations'
def update_base_workspaces(self, user, current_workspace_refs):
workspaces_to_remove = current_workspace_refs[:]
workspaces_to_add = []
user_groups = user.groups.all()
# workspaces assigned to the user's groups
# the compression list outside the inside compression list is for flattening
# the inside list
workspaces = [workspace for sublist in
[WorkSpace.objects.filter(targetOrganizations=org)
for org in user_groups]
for workspace in sublist]
# published workspaces assigned to the user's groups
# the compression list outside the inside compression list is for flattening
# the inside list
workspaces += [relation.workspace for sublist in
[GroupPublishedWorkspace.objects.filter(group=group)
for group in user_groups]
for relation in sublist]
workspaces = set(workspaces)
for workspace in workspaces:
ref = ref_from_workspace(workspace)
if ref not in current_workspace_refs:
workspaces_to_add.append((ref, workspace))
else:
workspaces_to_remove.remove(ref)
return (workspaces_to_remove, workspaces_to_add)
| from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace
def ref_from_workspace(workspace):
if isinstance(workspace, WorkSpace):
return 'group/' + str(workspace.id)
elif isinstance(workspace, PublishedWorkSpace):
return 'group_published/' + str(workspace.id)
class OrganizationWorkspaceManager:
def get_id(self):
return 'ezweb_organizations'
def update_base_workspaces(self, user, current_workspace_refs):
workspaces_to_remove = current_workspace_refs[:]
workspaces_to_add = []
user_groups = user.groups.all()
# workspaces assigned to the user's groups
# the compression list outside the inside compression list is for flattening
# the inside list
workspaces = [workspace for sublist in
[WorkSpace.objects.filter(targetOrganizations=org)
for org in user_groups]
for workspace in sublist]
# published workspaces assigned to the user's groups
# the compression list outside the inside compression list is for flattening
# the inside list
workspaces += [relation.workspace for sublist in
[GroupPublishedWorkspace.objects.filter(group=group)
for group in user_groups]
for relation in sublist]
workspaces = set(workspaces)
for workspace in workspaces:
if workspace.creator == user:
# Ignore workspaces created by the user
continue
ref = ref_from_workspace(workspace)
if ref not in current_workspace_refs:
workspaces_to_add.append((ref, workspace))
else:
workspaces_to_remove.remove(ref)
return (workspaces_to_remove, workspaces_to_add)
| Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups | Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups
| Python | agpl-3.0 | rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud |
06e7cf66d37a34a33349e47c374e733b1f3006be | test/functional/feature_shutdown.py | test/functional/feature_shutdown.py | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
Thread(target=test_long_call, args=(node,)).start()
# wait 1 second to ensure event loop waits for current connections to close
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy, wait_until
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
# Force connection establishment by executing a dummy command.
node.getblockcount()
Thread(target=test_long_call, args=(node,)).start()
# Wait until the server is executing the above `waitfornewblock`.
wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2)
# Wait 1 second after requesting shutdown but not before the `stop` call
# finishes. This is to ensure event loop waits for current connections
# to close.
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
| Remove race between connecting and shutdown on separate connections | qa: Remove race between connecting and shutdown on separate connections
| Python | mit | chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin |
63ca54e320b77501a304aa0520e133e1194e1324 | src/sentry/tasks/deletion.py | src/sentry/tasks/deletion.py | """
sentry.tasks.deletion
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.task import task
@task(name='sentry.tasks.deletion.delete_project', queue='cleanup')
def delete_project(object_id, **kwargs):
from sentry.models import Project
try:
p = Project.objects.get(id=object_id)
except Project.DoesNotExist:
return
p.delete()
@task(name='sentry.tasks.deletion.delete_group', queue='cleanup')
def delete_group(object_id, **kwargs):
from sentry.models import Group
try:
g = Group.objects.get(id=object_id)
except Group.DoesNotExist:
return
g.delete()
| """
sentry.tasks.deletion
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.task import task
@task(name='sentry.tasks.deletion.delete_project', queue='cleanup')
def delete_project(object_id, **kwargs):
from sentry.models import (
Project, TagKey, TagValue, GroupTagKey, GroupTag, GroupCountByMinute,
ProjectCountByMinute, Activity, EventMapping, Event, Group
)
try:
p = Project.objects.get(id=object_id)
except Project.DoesNotExist:
return
logger = delete_project.get_logger()
# This handles cascades properly
# TODO: this doesn't clean up the index
for model in (
TagKey, TagValue, GroupTagKey, GroupTag, GroupCountByMinute,
ProjectCountByMinute, Activity, EventMapping, Event, Group):
logger.info('Removing %r objects where project=%s', model, p.id)
has_results = False
for obj in model.objects.filter(project=p)[:1000]:
obj.delete()
has_results = True
if has_results:
delete_project.delay(object_id=object_id)
p.delete()
@task(name='sentry.tasks.deletion.delete_group', queue='cleanup')
def delete_group(object_id, **kwargs):
from sentry.models import Group
try:
g = Group.objects.get(id=object_id)
except Group.DoesNotExist:
return
g.delete()
| Break delete_project into smaller tasks | Break delete_project into smaller tasks
| Python | bsd-3-clause | vperron/sentry,BuildingLink/sentry,JTCunning/sentry,fotinakis/sentry,BuildingLink/sentry,zenefits/sentry,daevaorn/sentry,nicholasserra/sentry,hongliang5623/sentry,llonchj/sentry,mitsuhiko/sentry,TedaLIEz/sentry,alexm92/sentry,mvaled/sentry,jokey2k/sentry,fuziontech/sentry,ngonzalvez/sentry,looker/sentry,camilonova/sentry,beeftornado/sentry,wujuguang/sentry,wujuguang/sentry,JamesMura/sentry,kevinastone/sentry,looker/sentry,BayanGroup/sentry,pauloschilling/sentry,camilonova/sentry,zenefits/sentry,TedaLIEz/sentry,looker/sentry,ifduyue/sentry,BuildingLink/sentry,nicholasserra/sentry,BayanGroup/sentry,gencer/sentry,fotinakis/sentry,korealerts1/sentry,fotinakis/sentry,1tush/sentry,Kryz/sentry,fuziontech/sentry,nicholasserra/sentry,ewdurbin/sentry,kevinastone/sentry,ngonzalvez/sentry,Natim/sentry,JackDanger/sentry,Natim/sentry,ifduyue/sentry,camilonova/sentry,korealerts1/sentry,wong2/sentry,gencer/sentry,kevinastone/sentry,beeftornado/sentry,wong2/sentry,felixbuenemann/sentry,JackDanger/sentry,JackDanger/sentry,gg7/sentry,imankulov/sentry,fotinakis/sentry,drcapulet/sentry,Natim/sentry,JTCunning/sentry,Kryz/sentry,jokey2k/sentry,drcapulet/sentry,argonemyth/sentry,1tush/sentry,rdio/sentry,JTCunning/sentry,fuziontech/sentry,llonchj/sentry,korealerts1/sentry,ewdurbin/sentry,ifduyue/sentry,wujuguang/sentry,JamesMura/sentry,hongliang5623/sentry,felixbuenemann/sentry,gencer/sentry,ngonzalvez/sentry,pauloschilling/sentry,jean/sentry,songyi199111/sentry,kevinlondon/sentry,ifduyue/sentry,boneyao/sentry,ewdurbin/sentry,gg7/sentry,1tush/sentry,ifduyue/sentry,felixbuenemann/sentry,hongliang5623/sentry,mvaled/sentry,beeftornado/sentry,JamesMura/sentry,BuildingLink/sentry,BayanGroup/sentry,jean/sentry,zenefits/sentry,JamesMura/sentry,daevaorn/sentry,zenefits/sentry,rdio/sentry,alexm92/sentry,rdio/sentry,argonemyth/sentry,looker/sentry,gg7/sentry,drcapulet/sentry,jean/sentry,zenefits/sentry,daevaorn/sentry,songyi199111/sentry,wong2/sentry,mvaled/sentry,jean/sentry,mvaled/sentry,Kryz/sentry,songyi199111/sentry,daevaorn/sentry,imankulov/sentry,mitsuhiko/sentry,llonchj/sentry,TedaLIEz/sentry,jokey2k/sentry,gencer/sentry,vperron/sentry,rdio/sentry,kevinlondon/sentry,jean/sentry,mvaled/sentry,kevinlondon/sentry,boneyao/sentry,gencer/sentry,JamesMura/sentry,looker/sentry,mvaled/sentry,vperron/sentry,pauloschilling/sentry,alexm92/sentry,boneyao/sentry,BuildingLink/sentry,argonemyth/sentry,imankulov/sentry |
d73872b8bcc6c7c32fa10d4a8ffdd77fe568a954 | pyautotest/cli.py | pyautotest/cli.py | # -*- coding: utf-8 -*-
import logging
import os
import signal
import time
from optparse import OptionParser
from watchdog.observers import Observer
from pyautotest.observers import Notifier, ChangeHandler
# Configure logging
logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s',
datefmt='%m-%d-%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger('pyautotest')
def main():
parser = OptionParser("usage: %prog [options]")
parser.set_defaults(loglevel="INFO")
parser.add_option("-l", "--log-level", action="store", dest="loglevel")
(options, args) = parser.parse_args()
# Handle options
logger.setLevel(getattr(logging, options.loglevel.upper(), None))
while True:
event_handler = ChangeHandler()
event_handler.run_tests()
observer = Observer()
observer.schedule(event_handler, os.getcwd(), recursive=True)
# Avoid child zombie processes
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == "__main__":
main() | # -*- coding: utf-8 -*-
import argparse
import logging
import os
import signal
import time
from watchdog.observers import Observer
from pyautotest.observers import Notifier, ChangeHandler
# Configure logging
logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s',
datefmt='%m-%d-%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger('pyautotest')
def main():
parser = argparse.ArgumentParser(description="Continuously run unit tests when changes detected")
parser.add_argument('-l', '--log-level',
metavar='L',
default='INFO',
dest='loglevel',
action='store',
help='set logger level')
args = parser.parse_args()
# Handle options
logger.setLevel(getattr(logging, args.loglevel.upper(), None))
while True:
event_handler = ChangeHandler()
event_handler.run_tests()
observer = Observer()
observer.schedule(event_handler, os.getcwd(), recursive=True)
# Avoid child zombie processes
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == "__main__":
main() | Switch from optparase to argparse | Switch from optparase to argparse
| Python | mit | ascarter/pyautotest |
5e30bd1ae8218a6ad5a2582c15aed99258994d83 | tests/tests/test_swappable_model.py | tests/tests/test_swappable_model.py | from django.test import TestCase | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, modify_settings
from boardinghouse.schema import get_schema_model
class TestSwappableModel(TestCase):
@modify_settings()
def test_schema_model_app_not_found(self):
settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo.bar'
with self.assertRaises(ImproperlyConfigured):
get_schema_model()
@modify_settings()
def test_schema_model_model_not_found(self):
settings.BOARDINGHOUSE_SCHEMA_MODEL = 'boardinghouse.NotSchemaModel'
with self.assertRaises(ImproperlyConfigured):
get_schema_model()
@modify_settings()
def test_invalid_schema_model_string(self):
settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo__bar'
with self.assertRaises(ImproperlyConfigured):
get_schema_model()
| Write tests for swappable model. | Write tests for swappable model.
Resolves #28, #36.
--HG--
branch : fix-swappable-model
| Python | bsd-3-clause | schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse |
1b1652053213f3939b50b2ac66a775cd5d4beed9 | openpnm/__init__.py | openpnm/__init__.py | r"""
=======
OpenPNM
=======
OpenPNM is a package for performing pore network simulations of transport in
porous materials.
OpenPNM consists of several key modules. Each module is consisted of
several classes and each class is consisted of a few methods. Here, you'll
find a comprehensive documentation of the modules, classes, and finally the
methods, occasionally with basic embedded examples on how to use them.
"""
from .__version__ import __version__
from . import utils
from . import core
from . import network
from . import geometry
from . import phases
from . import physics
from . import models
from . import solvers
from . import integrators
from . import algorithms
from . import materials
from . import topotools
from . import io
from . import metrics
from .utils import Workspace, Project
import numpy as _np
_np.seterr(divide='ignore', invalid='ignore')
| r"""
=======
OpenPNM
=======
OpenPNM is a package for performing pore network simulations of transport in
porous materials.
OpenPNM consists of several key modules. Each module is consisted of
several classes and each class is consisted of a few methods. Here, you'll
find a comprehensive documentation of the modules, classes, and finally the
methods, occasionally with basic embedded examples on how to use them.
"""
from .__version__ import __version__
from . import utils
from . import core
from . import network
from . import geometry
from . import phases
from . import physics
from . import models
from . import algorithms
from . import solvers
from . import integrators
from . import materials
from . import topotools
from . import io
from . import metrics
from .utils import Workspace, Project
import numpy as _np
_np.seterr(divide='ignore', invalid='ignore')
| Fix import order to avoid circular import | Fix import order to avoid circular import
| Python | mit | PMEAL/OpenPNM |
32bf828445ed897609b908dff435191287f922f4 | bookie/views/stats.py | bookie/views/stats.py | """Basic views with no home"""
import logging
from pyramid.view import view_config
from bookie.bcelery import tasks
from bookie.models import BmarkMgr
from bookie.models.auth import ActivationMgr
from bookie.models.auth import UserMgr
LOG = logging.getLogger(__name__)
@view_config(
route_name="dashboard",
renderer="/stats/dashboard.mako")
def dashboard(request):
"""A public dashboard of the system
"""
res = tasks.count_total.delay()
# Generate some user data and stats
user_count = UserMgr.count()
pending_activations = ActivationMgr.count()
# Generate some bookmark data.
bookmark_count = BmarkMgr.count()
unique_url_count = BmarkMgr.count(distinct=True)
users_with_bookmarks = BmarkMgr.count(distinct_users=True)
return {
'bookmark_data': {
'count': bookmark_count,
'unique_count': unique_url_count,
},
'user_data': {
'count': user_count,
'activations': pending_activations,
'with_bookmarks': users_with_bookmarks,
}
}
| """Basic views with no home"""
import logging
from pyramid.view import view_config
from bookie.models import BmarkMgr
from bookie.models.auth import ActivationMgr
from bookie.models.auth import UserMgr
LOG = logging.getLogger(__name__)
@view_config(
route_name="dashboard",
renderer="/stats/dashboard.mako")
def dashboard(request):
"""A public dashboard of the system
"""
# Generate some user data and stats
user_count = UserMgr.count()
pending_activations = ActivationMgr.count()
# Generate some bookmark data.
bookmark_count = BmarkMgr.count()
unique_url_count = BmarkMgr.count(distinct=True)
users_with_bookmarks = BmarkMgr.count(distinct_users=True)
return {
'bookmark_data': {
'count': bookmark_count,
'unique_count': unique_url_count,
},
'user_data': {
'count': user_count,
'activations': pending_activations,
'with_bookmarks': users_with_bookmarks,
}
}
| Clean up old code no longer used | Clean up old code no longer used
| Python | agpl-3.0 | adamlincoln/Bookie,charany1/Bookie,GreenLunar/Bookie,charany1/Bookie,skmezanul/Bookie,charany1/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,pombredanne/Bookie,wangjun/Bookie,bookieio/Bookie,skmezanul/Bookie,pombredanne/Bookie,bookieio/Bookie,GreenLunar/Bookie,pombredanne/Bookie,teodesson/Bookie,skmezanul/Bookie,bookieio/Bookie,teodesson/Bookie,wangjun/Bookie,adamlincoln/Bookie,teodesson/Bookie,skmezanul/Bookie,wangjun/Bookie,GreenLunar/Bookie,teodesson/Bookie,adamlincoln/Bookie,bookieio/Bookie,wangjun/Bookie |
a29dad3b094b8d01a695e72cfc5e9b3bd51d6b6a | DataBase.py | DataBase.py |
''' Copyright 2015 RTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin)
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.
'''
| Use source file with license | Use source file with license
| Python | apache-2.0 | proffK/CourseManager |
|
130acde92df3b0f9aad2f28b61f45e37531f44ac | runserver.py | runserver.py | #!/usr/bin/env python
from sherry import app
# Load debug config
app.config.from_pyfile('../sherry.conf', silent=False)
app.run(host='0.0.0.0', port=5000, debug=True)
| #!/usr/bin/env python
from sherry import app
# Load debug config
app.config.from_pyfile('../sherry.conf', silent=True)
app.run(host='0.0.0.0', port=5000, debug=True)
| Make optional sherry.conf optional. Oops. | Make optional sherry.conf optional. Oops.
| Python | bsd-2-clause | PaulMcMillan/sherry,PaulMcMillan/sherry |
c64149d3b1bb4998bddd6c05c85f0b3129f47020 | pydbus/bus.py | pydbus/bus.py | from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
Type = Gio.BusType
def __init__(self, type, timeout=10):
self.con = Gio.bus_get_sync(type, None)
self.timeout = timeout
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.con = None
def SystemBus():
return Bus(Bus.Type.SYSTEM)
def SessionBus():
return Bus(Bus.Type.SESSION)
if __name__ == "__main__":
import sys
title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'
bus = SessionBus()
notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
# [""] is not required, but makes us compatible with Gnome 2030.
| from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
Type = Gio.BusType
def __init__(self, type, timeout=1000):
self.con = Gio.bus_get_sync(type, None)
self.timeout = timeout
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.con = None
def SystemBus():
return Bus(Bus.Type.SYSTEM)
def SessionBus():
return Bus(Bus.Type.SESSION)
if __name__ == "__main__":
import sys
title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'
bus = SessionBus()
notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
# [""] is not required, but makes us compatible with Gnome 2030.
| Increase the default timeout to 1s. | Increase the default timeout to 1s.
| Python | lgpl-2.1 | LEW21/pydbus,LEW21/pydbus |
c5a2c7e802d89ea17a7f0fd1a9194eaab8eaf61d | wcontrol/src/main.py | wcontrol/src/main.py | from flask import Flask
app = Flask(__name__)
app.config.from_object("config")
| import os
from flask import Flask
app = Flask(__name__)
app.config.from_object(os.environ.get("WCONTROL_CONF"))
| Use a env var to get config | Use a env var to get config
| Python | mit | pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control |
8d669dc8b09b8d7c8bc9b4c123e2bdd7c3521521 | functionaltests/api/base.py | functionaltests/api/base.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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.
from tempest.common import rest_client
from tempest import config
import testtools
CONF = config.CONF
class SolumClient(rest_client.RestClient):
def __init__(self, username, password, auth_url, tenant_name=None):
super(SolumClient, self).__init__(username, password, auth_url,
tenant_name)
self.service = 'application_deployment'
class TestCase(testtools.TestCase):
def setUp(self):
super(TestCase, self).setUp()
username = CONF.identity.username
password = CONF.identity.password
tenant_name = CONF.identity.tenant_name
auth_url = CONF.identity.uri
client_args = (username, password, auth_url, tenant_name)
self.client = SolumClient(*client_args)
| # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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.
from tempest import clients
from tempest.common import rest_client
from tempest import config
import testtools
CONF = config.CONF
class SolumClient(rest_client.RestClient):
def __init__(self, auth_provider):
super(SolumClient, self).__init__(auth_provider)
self.service = 'application_deployment'
class TestCase(testtools.TestCase):
def setUp(self):
super(TestCase, self).setUp()
username = CONF.identity.username
password = CONF.identity.password
tenant_name = CONF.identity.tenant_name
mgr = clients.Manager(username, password, tenant_name)
auth_provider = mgr.get_auth_provider()
self.client = SolumClient(auth_provider)
| Fix Tempest tests failing on gate-solum-devstack-dsvm | Fix Tempest tests failing on gate-solum-devstack-dsvm
Due to a new commit on tempest, devstack tests are failing. It changed
the signature of RestClient constructor.
This patch changes the signature of our inherited class to match the
change from tempest.
Change-Id: Id15682c68de123c0d66c6aa10d889c6304fcbb65
| Python | apache-2.0 | devdattakulkarni/test-solum,openstack/solum,ed-/solum,openstack/solum,ed-/solum,gilbertpilz/solum,ed-/solum,julienvey/solum,gilbertpilz/solum,stackforge/solum,ed-/solum,stackforge/solum,gilbertpilz/solum,gilbertpilz/solum,devdattakulkarni/test-solum,julienvey/solum |
98dfc5569fb1ae58905f8b6a36deeda324dcdd7b | cronos/teilar/models.py | cronos/teilar/models.py | from django.db import models
class Departments(models.Model):
urlid = models.IntegerField(unique = True)
name = models.CharField("Department name", max_length = 200)
class Teachers(models.Model):
urlid = models.CharField("URL ID", max_length = 30, unique = True)
name = models.CharField("Teacher name", max_length = 100)
email = models.EmailField("Teacher's mail", null = True)
department = models.CharField("Teacher's department", max_length = 100, null = True)
def __unicode__(self):
return self.name
| from django.db import models
class Departments(models.Model):
urlid = models.IntegerField(unique = True)
name = models.CharField("Department name", max_length = 200)
deprecated = models.BooleanField(default = False)
def __unicode__(self):
return self.name
class Teachers(models.Model):
urlid = models.IntegerField(unique = True)
name = models.CharField("Teacher name", max_length = 100)
email = models.EmailField("Teacher's mail", null = True)
department = models.CharField("Teacher's department", max_length = 100, null = True)
deprecated = models.BooleanField(default = False)
def __unicode__(self):
return self.name
| Add deprecated flag for teachers and departments | Add deprecated flag for teachers and departments
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr |
2ac94aa922dbf2d07039bc6545e7b1d31c5c9e4e | src/cclib/progress/__init__.py | src/cclib/progress/__init__.py | __revision__ = "$Revision$"
from textprogress import TextProgress
try:
import qt
except ImportError:
pass # import QtProgress will cause an error
else:
from qtprogress import QtProgress
| __revision__ = "$Revision$"
from textprogress import TextProgress
import sys
if 'qt' in sys.modules.keys():
from qtprogress import QtProgress
| Check to see if qt is loaded; if so, export QtProgress class | Check to see if qt is loaded; if so, export QtProgress class
| Python | lgpl-2.1 | Clyde-fare/cclib,Schamnad/cclib,jchodera/cclib,ghutchis/cclib,gaursagar/cclib,berquist/cclib,andersx/cclib,ben-albrecht/cclib,Schamnad/cclib,cclib/cclib,ATenderholt/cclib,cclib/cclib,langner/cclib,berquist/cclib,Clyde-fare/cclib,langner/cclib,ben-albrecht/cclib,ATenderholt/cclib,ghutchis/cclib,jchodera/cclib,andersx/cclib,cclib/cclib,langner/cclib,berquist/cclib,gaursagar/cclib |
f239fd08bb5536501b05ba6a81c99edffdea6f38 | pylamb/bmi_ilamb.py | pylamb/bmi_ilamb.py | #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'run_ilamb'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ILAMB_PARA_SETUP']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
| #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'run_ilamb.sh'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ILAMB_PARA_SETUP']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
| Use the correct name for the run script | Use the correct name for the run script
It may be time to go home.
| Python | mit | permamodel/ILAMB,permamodel/ILAMB,permamodel/ILAMB |
32def5f720b5ffb858f604dc360f66fa2a1b946a | pirx/base.py | pirx/base.py | import collections
class Settings(object):
def __init__(self):
self._settings = collections.OrderedDict()
def __setattr__(self, name, value):
if name.startswith('_'):
super(Settings, self).__setattr__(name, value)
else:
self._settings[name] = value
def _set_raw_value(self, value):
self._settings['_%d' % len(self._settings)] = value
def imp(self, module_name):
value = 'import %s' % module_name
self._set_raw_value(value)
def write(self):
for name, value in self._settings.iteritems():
if name.startswith('_'):
print value
else:
print '%s = %s' % (name.upper(), value.__repr__())
| import collections
class Settings(object):
def __init__(self):
self._settings = collections.OrderedDict()
def __setattr__(self, name, value):
if name.startswith('_'):
super(Settings, self).__setattr__(name, value)
else:
self._settings[name] = value
def __str__(self):
lines = []
for name, value in self._settings.iteritems():
if name.startswith('_'):
lines.append(value)
else:
lines.append('%s = %s' % (name.upper(), value.__repr__()))
return '\n'.join(lines)
def _set_raw_value(self, value):
self._settings['_%d' % len(self._settings)] = value
def imp(self, module_name):
value = 'import %s' % module_name
self._set_raw_value(value)
| Replace 'write' method with '__str__' | Replace 'write' method with '__str__'
| Python | mit | piotrekw/pirx |
62e32c356fc86bcd855d2931974b9df17856809e | tests/backends/test_macOS.py | tests/backends/test_macOS.py | import pytest
import keyring
from keyring.testing.backend import BackendBasicTests
from keyring.backends import macOS
@pytest.mark.skipif(
not keyring.backends.macOS.Keyring.viable,
reason="macOS backend not viable",
)
class TestOSXKeychain(BackendBasicTests):
def init_keyring(self):
return macOS.Keyring()
| import pytest
import keyring
from keyring.testing.backend import BackendBasicTests
from keyring.backends import macOS
@pytest.mark.skipif(
not keyring.backends.macOS.Keyring.viable,
reason="macOS backend not viable",
)
class Test_macOSKeychain(BackendBasicTests):
def init_keyring(self):
return macOS.Keyring()
| Rename test to match preferred naming convention for macOS. | Rename test to match preferred naming convention for macOS.
| Python | mit | jaraco/keyring |
d26b9d22363f9763f959332d07445a2a4e7c221c | services/vimeo.py | services/vimeo.py | import foauth.providers
class Vimeo(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://vimeo.com/'
docs_url = 'http://developer.vimeo.com/apis/advanced'
category = 'Videos'
# URLs to interact with the API
request_token_url = 'https://vimeo.com/oauth/request_token'
authorize_url = 'https://vimeo.com/oauth/authorize?permission=delete'
access_token_url = 'https://vimeo.com/oauth/access_token'
api_domain = 'vimeo.com'
available_permissions = [
('read', 'access information about videos'),
('write', 'update and like videos'),
('delete', 'delete videos'),
]
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/rest/v2?method=vimeo.people.getInfo&format=json')
return r.json[u'person'][u'id']
| import foauth.providers
class Vimeo(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://vimeo.com/'
docs_url = 'http://developer.vimeo.com/apis/advanced'
category = 'Videos'
# URLs to interact with the API
request_token_url = 'https://vimeo.com/oauth/request_token'
authorize_url = 'https://vimeo.com/oauth/authorize'
access_token_url = 'https://vimeo.com/oauth/access_token'
api_domain = 'vimeo.com'
available_permissions = [
(None, 'access your videos'),
('write', 'access, update and like videos'),
('delete', 'access, update, like and delete videos'),
]
permissions_widget = 'radio'
def get_authorize_params(self, redirect_uri, scopes):
params = super(Vimeo, self).get_authorize_params(redirect_uri, scopes)
if any(scopes):
params['permission'] = scopes[0]
return params
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/rest/v2?method=vimeo.people.getInfo&format=json')
return r.json[u'person'][u'id']
| Rewrite Vimeo to use the new scope selection system | Rewrite Vimeo to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org |
612c393ec4d964fb933ebf5b8f957ae573ae65ba | tests/rules/test_git_push.py | tests/rules/test_git_push.py | import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
| import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
def test_match(stderr):
assert match(Command('git push', stderr=stderr))
assert match(Command('git push master', stderr=stderr))
assert not match(Command('git push master'))
assert not match(Command('ls', stderr=stderr))
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
| Check git_push matches without specifying a branch | Check git_push matches without specifying a branch
| Python | mit | nvbn/thefuck,mlk/thefuck,mlk/thefuck,nvbn/thefuck,SimenB/thefuck,Clpsplug/thefuck,scorphus/thefuck,scorphus/thefuck,SimenB/thefuck,Clpsplug/thefuck |
e621b9f03b19e38dc6754dd1a4cb7b172e4891e7 | tests/test_extended_tests.py | tests/test_extended_tests.py | import pytest
import glob
from html2kirby import HTML2Kirby
files = []
for f in glob.glob("extended_tests/*.html"):
html = f
txt = f.replace(".html", ".txt")
files.append((html, txt))
@pytest.mark.parametrize("html,kirby", files)
def test_file(html, kirby):
formatter = HTML2Kirby()
with open(html, 'r') as html_file:
formatter.feed(html_file.read())
with open(kirby, 'r') as kirby_file:
expected_result = kirby_file.read()
assert formatter.markdown.strip() == expected_result.strip()
| import pytest
import glob
import os
from html2kirby import HTML2Kirby
files = []
path = os.path.dirname(os.path.abspath(__file__))
extended_tests_path = os.path.join(path, "extended_tests/*.html")
for f in glob.glob(extended_tests_path):
html = f
txt = f.replace(".html", ".txt")
files.append((html, txt))
@pytest.mark.parametrize("html,kirby", files)
def test_file(html, kirby):
formatter = HTML2Kirby()
with open(html, 'r') as html_file:
formatter.feed(html_file.read())
with open(kirby, 'r') as kirby_file:
expected_result = kirby_file.read()
assert formatter.markdown.strip() == expected_result.strip()
| Fix the extended test search | Fix the extended test search
| Python | mit | liip/html2kirby,liip/html2kirby |
603aacd06b99326d7dbab28e750b34589c51fa05 | tests/test_postgresqlgate.py | tests/test_postgresqlgate.py | # coding: utf-8
"""
Unit tests for the base gate.
"""
from unittest.mock import MagicMock, mock_open, patch
import smdba.postgresqlgate
class TestPgGt:
"""
Test suite for base gate.
"""
@patch("os.path.exists", MagicMock(side_effect=[True, False, False]))
@patch("smdba.postgresqlgate.open", new_callable=mock_open,
read_data="key=value")
def test_get_scenario_template(self, mck):
"""
Gets scenario template.
:return:
"""
pgt = smdba.postgresqlgate.PgSQLGate({})
template = pgt.get_scenario_template(target="psql")
assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF"
| # coding: utf-8
"""
Unit tests for the base gate.
"""
from unittest.mock import MagicMock, mock_open, patch
import smdba.postgresqlgate
class TestPgGt:
"""
Test suite for base gate.
"""
@patch("os.path.exists", MagicMock(side_effect=[True, False, False]))
@patch("smdba.postgresqlgate.open", new_callable=mock_open,
read_data="key=value")
def test_get_scenario_template(self, mck):
"""
Gets scenario template.
:return:
"""
pgt = smdba.postgresqlgate.PgSQLGate({})
template = pgt.get_scenario_template(target="psql")
assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF"
@patch("os.path.exists", MagicMock(side_effect=[True, False, False]))
@patch("smdba.postgresqlgate.open", new_callable=mock_open,
read_data="key=value")
def test_call_scenario(self, mck):
"""
Calls database scenario.
:return:
"""
pgt = smdba.postgresqlgate.PgSQLGate({})
pgt.get_scn = MagicMock()
pgt.get_scn().read = MagicMock(return_value="SELECT pg_reload_conf();")
pgt.syscall = MagicMock()
pgt.call_scenario("pg-reload-conf.scn", target="psql")
expectations = [
(
('sudo', '-u', 'postgres', '/bin/bash'),
{'input': 'cat - << EOF | /usr/bin/psql -t --pset footer=off\nSELECT pg_reload_conf();\nEOF'}
)
]
for call in pgt.syscall.call_args_list:
args, kw = call
exp_args, exp_kw = next(iter(expectations))
expectations.pop(0)
assert args == exp_args
assert "input" in kw
assert "input" in exp_kw
assert kw["input"] == exp_kw["input"]
assert not expectations
| Add unit test for database scenario call | Add unit test for database scenario call
| Python | mit | SUSE/smdba,SUSE/smdba |
2a0b1d070996bfb3d950d4fae70b264ddabc7d2f | sheldon/config.py | sheldon/config.py | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
import os
class Config:
def __init__(self, prefix='SHELDON_'):
"""
Load config from environment variables.
:param prefix: string, all needed environment variables
starts from it.
Default - 'SHELDON_'. So, environment
variables will be looking like:
'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY'
:return:
"""
# Bot config variables
self.variables = {}
for variable in os.environ:
if variable.startswith(prefix):
self.variables[variable] = os.environ[variable]
def get(self, variable, default_value):
"""
:param variable: string, needed variable
:param default_value: string, value that returns if
variable is not set
:return:
"""
if variable not in self.variables:
return default_value
return self.variables[variable]
| # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
import os
class Config:
def __init__(self, prefix='SHELDON_'):
"""
Load config from environment variables.
:param prefix: string, all needed environment variables
starts from it.
Default - 'SHELDON_'. So, environment
variables will be looking like:
'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY'
:return:
"""
# Bot config variables
self.variables = {}
for variable in os.environ:
if variable.startswith(prefix):
self.variables[variable] = os.environ[variable]
def get(self, variable, default_value):
"""
Get variable value from environment
:param variable: string, needed variable
:param default_value: string, value that returns if
variable is not set
:return: variable value
"""
if variable not in self.variables:
return default_value
return self.variables[variable]
def get_installed_plugins(self):
"""
Return list of installed plugins from installed_plugins.txt
:return: list of strings with names of plugins
"""
plugins_file = open('installed_plugins.txt')
return plugins_file.readlines()
| Add function for getting installed plugins | Add function for getting installed plugins
| Python | mit | lises/sheldon |
2f8ae4d29bd95c298209a0cb93b5354c00186d6b | trackpy/C_fallback_python.py | trackpy/C_fallback_python.py | try:
from _Cfilters import nullify_secondary_maxima
except ImportError:
import numpy as np
# Because of the way C imports work, nullify_secondary_maxima
# is *called*, as in nullify_secondary_maxima().
# For the pure Python variant, we do not want to call the function,
# so we make nullify_secondary_maxima a wrapper than returns
# the pure Python function that does the actual filtering.
def _filter(a):
target = a.size // 2 + 1
target_val = a[target]
if np.any(a[:target] > target_val):
return 0
if np.any(a[target + 1:] >= target_val):
return 0
return target
def nullify_secondary_maxima():
return _filter
| try:
from _Cfilters import nullify_secondary_maxima
except ImportError:
import numpy as np
# Because of the way C imports work, nullify_secondary_maxima
# is *called*, as in nullify_secondary_maxima().
# For the pure Python variant, we do not want to call the function,
# so we make nullify_secondary_maxima a wrapper than returns
# the pure Python function that does the actual filtering.
def _filter(a):
target = a.size // 2
target_val = a[target]
if target_val == 0:
return 0 # speedup trivial case
if np.any(a[:target] > target_val):
return 0
if np.any(a[target + 1:] >= target_val):
return 0
return target_val
def nullify_secondary_maxima():
return _filter
| Fix and speedup pure-Python fallback for C filter. | BUG/PERF: Fix and speedup pure-Python fallback for C filter.
| Python | bsd-3-clause | daniorerio/trackpy,daniorerio/trackpy |
cef249edef4100b8a3c009fa05febbc66c3fe5df | spamostack/spamostack.py | spamostack/spamostack.py | import argparse
from collections import OrderedDict
import json
import logger
import logging
from session import Session
from simulator import Simulator
from cache import Cache
from client_factory import ClientFactory
from keeper import Keeper
parser = argparse.ArgumentParser()
parser.add_argument('--pipe', dest='pipelines', required=True,
help='Path to the config file with pipes')
parser.add_argument('--db', dest='db', default='./db',
help='Path to the database directory')
args = parser.parse_args()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(logger.SpamStreamHandler())
def main():
if args.pipelines:
with open(args.pipelines, 'r') as pipes_file:
pipelines = json.load(pipes_file, object_pairs_hook=OrderedDict)
simulators = []
cache = Cache(args.db)
admin_session = Session(cache)
admin_factory = ClientFactory(cache)
admin_keeper = Keeper(cache, admin_session, admin_factory)
for pipe_name, pipe in pipelines.iteritems():
simulators.append(Simulator(pipe_name, pipe, cache, admin_keeper))
for simulator in simulators:
simulator.simulate()
if __name__ == "__main__":
main()
| import argparse
from collections import OrderedDict
import json
import logger
import logging
from session import Session
from simulator import Simulator
from cache import Cache
from client_factory import ClientFactory
from keeper import Keeper
parser = argparse.ArgumentParser()
parser.add_argument('--pipe', dest='pipelines', default='/etc/spamostack/conf.json',
help='Path to the config file with pipes')
parser.add_argument('--db', dest='db', default='./db',
help='Path to the database directory')
args = parser.parse_args()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(logger.SpamStreamHandler())
def main():
if args.pipelines:
with open(args.pipelines, 'r') as pipes_file:
pipelines = json.load(pipes_file, object_pairs_hook=OrderedDict)
simulators = []
cache = Cache(args.db)
admin_session = Session(cache)
admin_factory = ClientFactory(cache)
admin_keeper = Keeper(cache, admin_session, admin_factory)
for pipe_name, pipe in pipelines.iteritems():
simulators.append(Simulator(pipe_name, pipe, cache, admin_keeper))
for simulator in simulators:
simulator.simulate()
if __name__ == "__main__":
main()
| Add default path to config | Add default path to config
| Python | apache-2.0 | seecloud/spamostack |
0003ef7fe3d59c4bda034dee334d45b6d7a2622d | pyvm_test.py | pyvm_test.py | import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
| import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_num_float(self):
self.assertEqual(
10.55,
self.vm.eval('10.55')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
| Add test of storing float | Add test of storing float
| Python | mit | utgwkk/tiny-python-vm |
9ff48dd4bff605ad1521c8ebaffc18432a155d8d | wagtailcodeblock/settings.py | wagtailcodeblock/settings.py | from django.conf import settings
def get_language_choices():
"""
Default list of language choices, if not overridden by Django.
"""
DEFAULT_LANGUAGES = (
('bash', 'Bash/Shell'),
('css', 'CSS'),
('diff', 'diff'),
('http', 'HTML'),
('javascript', 'Javascript'),
('json', 'JSON'),
('python', 'Python'),
('scss', 'SCSS'),
('yaml', 'YAML'),
)
return getattr(settings, "WAGTAIL_CODE_BLOCK_LANGUAGES", DEFAULT_LANGUAGES)
def get_theme():
"""
Returns a default theme, if not in the proejct's settings. Default theme is 'coy'.
"""
return getattr(settings, "WAGTAIL_CODE_BLOCK_THEME", 'coy')
def get_prism_version():
prism_version = "1.9.0"
return prism_version
| from django.conf import settings
def get_language_choices():
"""
Default list of language choices, if not overridden by Django.
"""
DEFAULT_LANGUAGES = (
('bash', 'Bash/Shell'),
('css', 'CSS'),
('diff', 'diff'),
('http', 'HTML'),
('javascript', 'Javascript'),
('json', 'JSON'),
('python', 'Python'),
('scss', 'SCSS'),
('yaml', 'YAML'),
)
return getattr(settings, "WAGTAIL_CODE_BLOCK_LANGUAGES", DEFAULT_LANGUAGES)
def get_theme():
"""
Returns a default theme, if not in the proejct's settings. Default theme is 'coy'.
"""
return getattr(settings, "WAGTAIL_CODE_BLOCK_THEME", 'coy')
def get_prism_version():
prism_version = "1.10.0"
return prism_version
| Update to prims 1.10 version | Update to prims 1.10 version | Python | bsd-3-clause | FlipperPA/wagtailcodeblock,FlipperPA/wagtailcodeblock,FlipperPA/wagtailcodeblock |
c4d64672c8c72ca928b354e9cfd35a7d40dbb78f | MROCPdjangoForm/ocpipeline/mrpaths.py | MROCPdjangoForm/ocpipeline/mrpaths.py | #
# Code to load project paths
#
import os, sys
MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "/Users/dmhembere44/MR-connectome" ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )
sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MRCAP_PATH ]
| #
# Code to load project paths
#
import os, sys
MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.." ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )
sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MRCAP_PATH ]
| Change to path, made relative | Change to path, made relative
Former-commit-id: f00bf782fad3f6ddc6d2c97a23ff4f087ad3a22f
| Python | apache-2.0 | neurodata/ndmg |
cba5a3d4928a3ee2e7672ca4a3f766a789d83acf | cupcake/smush/plot.py | cupcake/smush/plot.py | """
User-facing interface for plotting all dimensionality reduction algorithms
"""
def smushplot(data, smusher='pca', n_components=2, marker='o', marker_order=None,
text=False, text_order=None, linewidth=1, linewidth_order=None,
edgecolor='k', edgecolor_order=None, smusher_kws=None,
plot_kws=None):
if isinstance(smusher, str):
# Need to get appropriate smusher from sklearn given the string
pass
else:
# Assume this is already an initialized sklearn object with the
# ``fit_transform()`` method
pass
| """
User-facing interface for plotting all dimensionality reduction algorithms
"""
def smushplot(data, smusher='PCA', x=1, y=2, n_components=2, marker='o',
marker_order=None, text=False, text_order=None, linewidth=1,
linewidth_order=None, edgecolor='k', edgecolor_order=None,
smusher_kws=None, plot_kws=None):
"""Plot high dimensional data in 2d space
Parameters
----------
data : pandas.DataFrame or numpy.array
A (n_samples, m_features) wide matrix of observations. The samples
(rows) will be plotted relative to the reduced representation of the
features (columns)
smusher : str or object
Either a string specifying a valid dimensionality reduction algorithm
in ``sklearn.decomposition`` or ``sklearn.manifold``, or any object
with ``fit_transform()`` methods.
Notes
-----
"""
if isinstance(smusher, str):
# Need to get appropriate smusher from sklearn given the string
pass
else:
# Assume this is already an initialized sklearn object with the
# ``fit_transform()`` method
pass
| Add x, y arguments and docstring | Add x, y arguments and docstring
| Python | bsd-3-clause | olgabot/cupcake |
66ba9aa2172fbed67b67a06acb331d449d32a33c | tests/services/shop/conftest.py | tests/services/shop/conftest.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail
@pytest.fixture
def shop(email_config):
return shop_service.create_shop('shop-01', 'Some Shop', email_config.id)
@pytest.fixture
def orderer(normal_user):
user = create_user_with_detail('Besteller')
return create_orderer(user)
@pytest.fixture
def empty_cart() -> Cart:
return Cart()
@pytest.fixture
def order_number_sequence(shop) -> None:
sequence_service.create_order_number_sequence(shop.id, 'order-')
| """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail
@pytest.fixture
def shop(email_config):
return shop_service.create_shop('shop-01', 'Some Shop', email_config.id)
@pytest.fixture
def orderer():
user = create_user_with_detail('Besteller')
return create_orderer(user)
@pytest.fixture
def empty_cart() -> Cart:
return Cart()
@pytest.fixture
def order_number_sequence(shop) -> None:
sequence_service.create_order_number_sequence(shop.id, 'order-')
| Remove unused fixture from orderer | Remove unused fixture from orderer
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
d95001c17b095b713d8a4edacead561ba127aa53 | src/NamerTests.py | src/NamerTests.py | import unittest
import os
from approvaltests.Namer import Namer
class NamerTests(unittest.TestCase):
def test_class(self):
n = Namer()
self.assertEqual("NamerTests", n.getClassName())
def test_method(self):
n = Namer()
self.assertEqual("test_method", n.getMethodName())
def test_file(self):
n = Namer()
self.assertTrue(os.path.exists(n.getDirectory() + "/NamerTests.py"))
def test_basename(self):
n = Namer()
self.assertTrue(n.get_basename().endswith("\\NamerTests.test_basename"), n.get_basename())
if __name__ == '__main__':
unittest.main()
| import unittest
import os
from approvaltests.Namer import Namer
class NamerTests(unittest.TestCase):
def test_class(self):
n = Namer()
self.assertEqual("NamerTests", n.getClassName())
def test_method(self):
n = Namer()
self.assertEqual("test_method", n.getMethodName())
def test_file(self):
n = Namer()
self.assertTrue(os.path.exists(n.getDirectory() + "/NamerTests.py"))
def test_basename(self):
n = Namer()
self.assertTrue(n.get_basename().endswith("NamerTests.test_basename"), n.get_basename())
if __name__ == '__main__':
unittest.main()
| Remove '\' condition from test as it will not be in the file path when used on Linux. | Remove '\' condition from test as it will not be in the file path when used on Linux.
| Python | apache-2.0 | approvals/ApprovalTests.Python,tdpreece/ApprovalTests.Python,approvals/ApprovalTests.Python,approvals/ApprovalTests.Python |
4e88b6ee9c1927aeb312e40335633d2ca9871c8c | tokens/migrations/0002_token_token_type.py | tokens/migrations/0002_token_token_type.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-14 19:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tokens', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='token',
name='token_type',
field=models.CharField(choices=[('MintableToken', 'Mintable Token')], default='MintableToken', max_length=12),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-14 19:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tokens', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='token',
name='token_type',
field=models.CharField(choices=[('MintableToken', 'Mintable Token')], default='MintableToken', max_length=20),
),
]
| Fix psycopg2 DataError due to bad varchar length | Fix psycopg2 DataError due to bad varchar length
| Python | apache-2.0 | onyb/ethane,onyb/ethane,onyb/ethane,onyb/ethane |
e743f82d93e9501c8b3bd827ee0553ceec8aadb6 | linkedin_scraper/spiders/search.py | linkedin_scraper/spiders/search.py | import scrapy
class SearchSpider(scrapy.Spider):
name = 'search'
allowed_domains = ['linkedin.com']
start_urls = [
'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta']
def parse(self, response):
for search_result in response.css('li.mod.result.people'):
*first_name, last_name = search_result.css('b::text').extract()
yield {
'first_name': ' '.join(first_name),
'last_name': last_name,
}
| from os import environ
from scrapy.spiders.init import InitSpider
from scrapy.http import Request, FormRequest
class SearchSpider(InitSpider):
name = 'search'
allowed_domains = ['linkedin.com']
login_page = 'https://www.linkedin.com/uas/login'
start_urls = [
'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta']
def __init__(self, *args, **kwargs):
try:
self.username = kwargs.pop('username', environ['SPIDER_USERNAME'])
self.password = kwargs.pop('password', environ['SPIDER_PASSWORD'])
except KeyError:
self.logger.error('Both username and password need to be specified '
'by -a option or SPIDER_<PARAM> environment var')
super().__init__(*args, **kwargs)
def init_request(self):
return Request(url=self.login_page, callback=self.login)
def login(self, response):
return FormRequest.from_response(
response, callback=self.check_login_response,
formdata={'session_key': self.username,
'session_password': self.password})
def parse(self, response):
for search_result in response.css('li.mod.result.people'):
*first_name, last_name = search_result.css('b::text').extract()
yield {
'first_name': ' '.join(first_name),
'last_name': last_name,
}
def check_login_response(self, response):
if b'Sign Out' in response.body:
self.logger.debug("Successfully logged in. Let's start crawling!")
return self.initialized()
self.logger.error('Login failed!')
| Allow Spider to log into LinkedIn. | Allow Spider to log into LinkedIn.
* SearchSpider now uses InitSpider as base class,
* SearchSpider now accepts username and password arguments,
* username and password can also be set by SPIDER_USERNAME and SPIDER_PASSWORD env variables,
* SearchSpider log into LinkedIn by sending form with credentials to /uas/login endpoint.
| Python | mit | nihn/linkedin-scraper,nihn/linkedin-scraper |
d237071aef4cc62c3506d25072937cdc6feab797 | examples/modes/pygments_syntax_highlighter.py | examples/modes/pygments_syntax_highlighter.py | """
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys
from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit, ColorScheme
from pyqode.core.backend import server
from pyqode.core.modes import PygmentsSH
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
editor = CodeEdit()
editor.backend.start(server.__file__)
editor.resize(800, 600)
sh = editor.modes.append(PygmentsSH(editor.document()))
sh.color_scheme = ColorScheme('monokai')
editor.file.open(__file__)
editor.show()
app.exec_()
editor.close()
del editor
del app
| """
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys
from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit, ColorScheme
from pyqode.core.backend import server
from pyqode.core.modes import PygmentsSH
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
editor = CodeEdit()
editor.backend.start(server.__file__)
editor.resize(800, 600)
sh = editor.modes.append(PygmentsSH(editor.document()))
sh.color_scheme = 'monokai'
editor.file.open(__file__)
editor.show()
app.exec_()
editor.close()
del editor
del app
| Update example to make use of the new simplified color scheme api | Update example to make use of the new simplified color scheme api
| Python | mit | pyQode/pyqode.core,zwadar/pyqode.core,pyQode/pyqode.core |
cd9b9675cd81e9ee01b4ad2932319a6070b82753 | zerver/migrations/0099_index_wildcard_mentioned_user_messages.py | zerver/migrations/0099_index_wildcard_mentioned_user_messages.py | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0098_index_has_alert_word_user_messages"),
]
operations = [
migrations.RunSQL(
"""
CREATE INDEX IF NOT EXISTS zerver_usermessage_wildcard_mentioned_message_id
ON zerver_usermessage (user_profile_id, message_id)
WHERE (flags & 8) != 0 OR (flags & 16) != 0;
""",
reverse_sql="DROP INDEX zerver_usermessage_wilcard_mentioned_message_id;",
),
]
| from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0098_index_has_alert_word_user_messages"),
]
operations = [
migrations.RunSQL(
"""
CREATE INDEX IF NOT EXISTS zerver_usermessage_wildcard_mentioned_message_id
ON zerver_usermessage (user_profile_id, message_id)
WHERE (flags & 8) != 0 OR (flags & 16) != 0;
""",
reverse_sql="DROP INDEX zerver_usermessage_wildcard_mentioned_message_id;",
),
]
| Fix typo in 0099 reverse_sql. | migrations: Fix typo in 0099 reverse_sql.
Signed-off-by: Anders Kaseorg <[email protected]>
| Python | apache-2.0 | kou/zulip,kou/zulip,kou/zulip,rht/zulip,andersk/zulip,zulip/zulip,kou/zulip,andersk/zulip,andersk/zulip,zulip/zulip,andersk/zulip,rht/zulip,kou/zulip,rht/zulip,zulip/zulip,kou/zulip,andersk/zulip,zulip/zulip,zulip/zulip,zulip/zulip,rht/zulip,rht/zulip,kou/zulip,zulip/zulip,rht/zulip,rht/zulip,andersk/zulip,andersk/zulip |
2e897f7dce89d4b52c3507c62e7120ee238b713c | database/database_setup.py | database/database_setup.py | from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from models.base import Base
from models.user import User
from models.store import Store
from models.product import Product
engine = create_engine('sqlite:///productcatalog.db')
Base.metadata.create_all(engine)
| from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from models.base import Base
from models.user import User
from models.store import Store
from models.product import Product
engine = create_engine('postgresql://catalog:catalog123!@localhost:8000/catalog')
Base.metadata.create_all(engine)
| Connect database engine to postgresql | feat: Connect database engine to postgresql
| Python | mit | caasted/aws-flask-catalog-app,caasted/aws-flask-catalog-app |
a8c8b136f081e3a2c7f1fd1f833a85288a358e42 | vumi_http_retry/workers/api/validate.py | vumi_http_retry/workers/api/validate.py | import json
from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from vumi_http_retry.workers.api.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v in validators:
errors.extend(v(req, *a, **kw) or [])
if not errors:
return fn(api, req, *a, **kw)
else:
return response(req, {'errors': errors}, code=http.BAD_REQUEST)
return wrapper
return validator
def has_header(name):
def validator(req):
if not req.requestHeaders.hasHeader(name):
return [{
'type': 'header_missing',
'message': "Header '%s' is missing" % (name,)
}]
else:
return []
return validator
def body_schema(schema):
json_validator = Draft4Validator(schema)
def validator(req, body):
return [{
'type': 'invalid_body',
'message': e.message
} for e in json_validator.iter_errors(body)]
return validator
| import json
from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from vumi_http_retry.workers.api.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v in validators:
errors.extend(v(req, *a, **kw) or [])
if not errors:
return fn(api, req, *a, **kw)
else:
return response(req, {'errors': errors}, code=http.BAD_REQUEST)
return wrapper
return validator
def has_header(name):
def validator(req, *a, **kw):
if not req.requestHeaders.hasHeader(name):
return [{
'type': 'header_missing',
'message': "Header '%s' is missing" % (name,)
}]
else:
return []
return validator
def body_schema(schema):
json_validator = Draft4Validator(schema)
def validator(req, body, *a, **kw):
return [{
'type': 'invalid_body',
'message': e.message
} for e in json_validator.iter_errors(body)]
return validator
| Change validators to allow additional arguments to be given to the functions they are wrapping | Change validators to allow additional arguments to be given to the functions they are wrapping
| Python | bsd-3-clause | praekelt/vumi-http-retry-api,praekelt/vumi-http-retry-api |
370dac353937d73798b4cd2014884b9f1aa95abf | osmaxx-py/osmaxx/contrib/auth/tests/test_frontend_permissions.py | osmaxx-py/osmaxx/contrib/auth/tests/test_frontend_permissions.py | from django.test import TestCase
from django.contrib.auth.models import User
from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group
class TestFrontendPermissions(TestCase):
def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self):
an_admin = User.objects.create_superuser('A. D. Min', '[email protected]', 'password')
self.assertTrue(user_in_osmaxx_group(an_admin))
| from django.test import TestCase
from django.contrib.auth.models import User, Group
from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP
class TestFrontendPermissions(TestCase):
def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self):
an_admin = User.objects.create_superuser('A. D. Min', '[email protected]', 'password')
self.assertTrue(user_in_osmaxx_group(an_admin))
def test_user_can_access_frontend_when_in_osmaxx_group(self):
a_user = User.objects.create_user('U. Ser', '[email protected]', 'password')
a_user.groups.add(Group.objects.get(name=FRONTEND_USER_GROUP))
self.assertTrue(user_in_osmaxx_group(a_user))
| Test that users can access frontend when in osmaxx group | Test that users can access frontend when in osmaxx group
| Python | mit | geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend |
1652b921fa2fadc936b346fc3de217cf97b0e476 | src/etc/make-snapshot.py | src/etc/make-snapshot.py | #!/usr/bin/env python
import snapshot, sys
if len(sys.argv) == 2:
print(snapshot.make_snapshot(sys.argv[1], sys.argv[2], ""))
else:
print(snapshot.make_snapshot(sys.argv[1], sys.argv[2], sys.argv[3]))
| #!/usr/bin/env python
import snapshot, sys
if len(sys.argv) == 3:
print(snapshot.make_snapshot(sys.argv[1], sys.argv[2], ""))
else:
print(snapshot.make_snapshot(sys.argv[1], sys.argv[2], sys.argv[3]))
| Fix condition in snapshot script. Argv is never 2 long, it can be 3 or 4. | Fix condition in snapshot script. Argv is never 2 long, it can be 3 or 4.
| Python | apache-2.0 | AerialX/rust-rt-minimal,fabricedesre/rust,emk/rust,erickt/rust,cllns/rust,j16r/rust,untitaker/rust,cllns/rust,miniupnp/rust,zachwick/rust,seanrivera/rust,aidancully/rust,achanda/rand,barosl/rust,pshc/rust,aidancully/rust,barosl/rust,kmcallister/rust,mdinger/rust,l0kod/rust,quornian/rust,fabricedesre/rust,LeoTestard/rust,erickt/rust,aturon/rust,emk/rust,defuz/rust,pczarn/rust,jbclements/rust,jbclements/rust,stepancheg/rust-ide-rust,nham/rust,bombless/rust-docs-chinese,sarojaba/rust-doc-korean,erickt/rust,Ryman/rust,ruud-v-a/rust,victorvde/rust,gifnksm/rust,bombless/rust,aneeshusa/rust,jashank/rust,dinfuehr/rust,XMPPwocky/rust,aidancully/rust,avdi/rust,dinfuehr/rust,vhbit/rust,ejjeong/rust,aturon/rust,avdi/rust,zaeleus/rust,dwillmer/rust,miniupnp/rust,aturon/rust,aidancully/rust,seanrivera/rust,aneeshusa/rust,zubron/rust,ktossell/rust,untitaker/rust,philyoon/rust,ebfull/rust,rohitjoshi/rust,defuz/rust,pelmers/rust,sae-bom/rust,ebfull/rust,TheNeikos/rust,pelmers/rust,jbclements/rust,arthurprs/rand,sae-bom/rust,sarojaba/rust-doc-korean,richo/rust,waynenilsen/rand,P1start/rust,0x73/rust,krzysz00/rust,hauleth/rust,ruud-v-a/rust,sarojaba/rust-doc-korean,rprichard/rust,KokaKiwi/rust,XMPPwocky/rust,sae-bom/rust,aepsil0n/rust,AerialX/rust,defuz/rust,omasanori/rust,emk/rust,andars/rust,quornian/rust,vhbit/rust,TheNeikos/rust,aidancully/rust,zachwick/rust,GBGamer/rust,mdinger/rust,barosl/rust,philyoon/rust,TheNeikos/rust,kimroen/rust,pelmers/rust,AerialX/rust-rt-minimal,vhbit/rust,0x73/rust,andars/rust,sae-bom/rust,l0kod/rust,AerialX/rust,dwillmer/rust,reem/rust,fabricedesre/rust,erickt/rust,nwin/rust,mihneadb/rust,l0kod/rust,l0kod/rust,graydon/rust,mvdnes/rust,AerialX/rust,hauleth/rust,quornian/rust,l0kod/rust,aneeshusa/rust,servo/rust,aneeshusa/rust,mitsuhiko/rust,jashank/rust,mahkoh/rust,victorvde/rust,AerialX/rust,GrahamDennis/rand,dinfuehr/rust,pythonesque/rust,stepancheg/rust-ide-rust,krzysz00/rust,kimroen/rust,robertg/rust,servo/rust,emk/rust,quornian/rust,sarojaba/rust-doc-korean,P1start/rust,SiegeLord/rust,Ryman/rust,zubron/rust,nham/rust,seanrivera/rust,carols10cents/rust,graydon/rust,AerialX/rust-rt-minimal,mihneadb/rust,miniupnp/rust,0x73/rust,vhbit/rust,pythonesque/rust,seanrivera/rust,j16r/rust,ktossell/rust,XMPPwocky/rust,quornian/rust,nwin/rust,sae-bom/rust,jbclements/rust,zaeleus/rust,AerialX/rust,jroesch/rust,rprichard/rust,sarojaba/rust-doc-korean,j16r/rust,mihneadb/rust,reem/rust,zubron/rust,reem/rust,krzysz00/rust,gifnksm/rust,pczarn/rust,pythonesque/rust,dwillmer/rust,jashank/rust,michaelballantyne/rust-gpu,kimroen/rust,untitaker/rust,zachwick/rust,untitaker/rust,barosl/rust,quornian/rust,philyoon/rust,stepancheg/rust-ide-rust,andars/rust,erickt/rust,aneeshusa/rust,XMPPwocky/rust,AerialX/rust-rt-minimal,michaelballantyne/rust-gpu,carols10cents/rust,pczarn/rust,dwillmer/rust,nwin/rust,Ryman/rust,mihneadb/rust,kmcallister/rust,SiegeLord/rust,bombless/rust,mvdnes/rust,KokaKiwi/rust,SiegeLord/rust,stepancheg/rust-ide-rust,ruud-v-a/rust,vhbit/rust,pythonesque/rust,krzysz00/rust,vhbit/rust,vhbit/rust,servo/rust,l0kod/rust,pczarn/rust,erickt/rust,stepancheg/rust-ide-rust,avdi/rust,ejjeong/rust,rprichard/rust,servo/rust,nwin/rust,ebfull/rust,graydon/rust,carols10cents/rust,miniupnp/rust,victorvde/rust,nham/rust,GBGamer/rust,mdinger/rust,P1start/rust,cllns/rust,fabricedesre/rust,mitsuhiko/rust,aepsil0n/rust,0x73/rust,mihneadb/rust,kimroen/rust,rohitjoshi/rust,LeoTestard/rust,pshc/rust,richo/rust,aepsil0n/rust,jashank/rust,servo/rust,richo/rust,victorvde/rust,emk/rust,kmcallister/rust,carols10cents/rust,defuz/rust,XMPPwocky/rust,pythonesque/rust,omasanori/rust,rprichard/rust,fabricedesre/rust,dwillmer/rust,LeoTestard/rust,hauleth/rust,michaelballantyne/rust-gpu,carols10cents/rust,ejjeong/rust,avdi/rust,miniupnp/rust,mdinger/rust,rprichard/rust,jbclements/rust,miniupnp/rust,michaelballantyne/rust-gpu,dinfuehr/rust,michaelballantyne/rust-gpu,LeoTestard/rust,krzysz00/rust,j16r/rust,TheNeikos/rust,bombless/rust,mitsuhiko/rust,nham/rust,kwantam/rust,SiegeLord/rust,jbclements/rust,bombless/rust,nham/rust,andars/rust,nham/rust,kmcallister/rust,sae-bom/rust,pelmers/rust,ruud-v-a/rust,mihneadb/rust,aturon/rust,pelmers/rust,0x73/rust,j16r/rust,mdinger/rust,rprichard/rust,jroesch/rust,mahkoh/rust,robertg/rust,defuz/rust,AerialX/rust-rt-minimal,zubron/rust,vhbit/rust,AerialX/rust,kwantam/rust,philyoon/rust,richo/rust,reem/rust,ktossell/rust,nwin/rust,barosl/rust,jashank/rust,bombless/rust,seanrivera/rust,miniupnp/rust,richo/rust,aturon/rust,stepancheg/rust-ide-rust,zubron/rust,KokaKiwi/rust,reem/rust,dwillmer/rust,SiegeLord/rust,ejjeong/rust,huonw/rand,P1start/rust,kimroen/rust,KokaKiwi/rust,cllns/rust,Ryman/rust,untitaker/rust,robertg/rust,gifnksm/rust,sarojaba/rust-doc-korean,graydon/rust,kwantam/rust,LeoTestard/rust,jroesch/rust,stepancheg/rust-ide-rust,defuz/rust,Ryman/rust,aepsil0n/rust,SiegeLord/rust,graydon/rust,jbclements/rust,jroesch/rust,0x73/rust,ejjeong/rust,j16r/rust,ebfull/rust,servo/rust,bluss/rand,mahkoh/rust,ebfull/rust,erickt/rust,pczarn/rust,omasanori/rust,mahkoh/rust,KokaKiwi/rust,barosl/rust,ebfull/rust,pczarn/rust,pshc/rust,michaelballantyne/rust-gpu,pshc/rust,kwantam/rust,reem/rust,robertg/rust,kmcallister/rust,richo/rust,emk/rust,TheNeikos/rust,rohitjoshi/rust,ktossell/rust,servo/rust,kwantam/rust,ebfull/rand,kmcallister/rust,rohitjoshi/rust,miniupnp/rust,jbclements/rust,jroesch/rust,dwillmer/rust,pshc/rust,jashank/rust,GBGamer/rust,nwin/rust,krzysz00/rust,dinfuehr/rust,seanrivera/rust,mvdnes/rust,victorvde/rust,zubron/rust,philyoon/rust,bombless/rust,gifnksm/rust,zaeleus/rust,carols10cents/rust,Ryman/rust,michaelballantyne/rust-gpu,emk/rust,bhickey/rand,zaeleus/rust,avdi/rust,andars/rust,GBGamer/rust,avdi/rust,Ryman/rust,gifnksm/rust,ejjeong/rust,mitsuhiko/rust,hauleth/rust,kmcallister/rust,zubron/rust,aturon/rust,jashank/rust,cllns/rust,sarojaba/rust-doc-korean,barosl/rust,mvdnes/rust,mvdnes/rust,zachwick/rust,aidancully/rust,fabricedesre/rust,mvdnes/rust,pythonesque/rust,LeoTestard/rust,rohitjoshi/rust,robertg/rust,shepmaster/rand,pczarn/rust,dinfuehr/rust,P1start/rust,pshc/rust,hauleth/rust,cllns/rust,aepsil0n/rust,jbclements/rust,gifnksm/rust,l0kod/rust,kimroen/rust,KokaKiwi/rust,mahkoh/rust,P1start/rust,ktossell/rust,kwantam/rust,andars/rust,GBGamer/rust,victorvde/rust,GBGamer/rust,nwin/rust,GBGamer/rust,omasanori/rust,jroesch/rust,robertg/rust,j16r/rust,jroesch/rust,rohitjoshi/rust,GBGamer/rust,quornian/rust,SiegeLord/rust,zachwick/rust,XMPPwocky/rust,mahkoh/rust,mdinger/rust,zaeleus/rust,fabricedesre/rust,zubron/rust,nham/rust,ktossell/rust,nwin/rust,zachwick/rust,pshc/rust,ruud-v-a/rust,ktossell/rust,ruud-v-a/rust,pshc/rust,zaeleus/rust,aneeshusa/rust,P1start/rust,aturon/rust,pelmers/rust,dwillmer/rust,jashank/rust,jroesch/rust,TheNeikos/rust,AerialX/rust-rt-minimal,LeoTestard/rust,aepsil0n/rust,omasanori/rust,mitsuhiko/rust,graydon/rust,untitaker/rust,omasanori/rust,mitsuhiko/rust,0x73/rust,mitsuhiko/rust,l0kod/rust,philyoon/rust,pythonesque/rust,retep998/rand,kimroen/rust,hauleth/rust |
837b767036f580a8c9d523e0f6c175a75d1dc3b2 | pi_control_service/gpio_service.py | pi_control_service/gpio_service.py | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key,
request_action=self._perform_gpio_action)
def _perform_gpio_action(self, instruction):
result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"}
if instruction['action'] not in ALLOWED_ACTIONS:
result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS))
return result
try:
result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin']))
result['error'] = 0
except ValueError:
result['response'] = "'pin' value must be an integer"
except Exception as e:
result['response'] = e.message
return result
def stop(self):
self.pins.cleanup()
super(GPIOService, self).stop()
| from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read', 'get_config')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key,
request_action=self._perform_gpio_action)
def _perform_gpio_action(self, instruction):
result = {'error': 1, 'response': "An error occurred"}
if instruction['action'] not in ALLOWED_ACTIONS:
result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS))
return result
try:
pin = instruction['pin']
except KeyError:
try:
result['response'] = getattr(self.pins, instruction['action'])()
result['error'] = 0
except Exception as e:
result['response'] = e.message
else:
try:
result['response'] = getattr(self.pins, instruction['action'])(int(pin))
result['error'] = 0
except ValueError:
result['response'] = "'pin' value must be an integer"
except Exception as e:
result['response'] = e.message
return result
def stop(self):
self.pins.cleanup()
super(GPIOService, self).stop()
| Add get_config as GPIO action | Add get_config as GPIO action
| Python | mit | HydAu/ProjectWeekds_Pi-Control-Service,projectweekend/Pi-Control-Service |
6f8b5950a85c79ed33c1d00a35a1def2efc7bff5 | tests/conftest.py | tests/conftest.py | from factories import post_factory, post
| from factories import post_factory, post
import os
import sys
root = os.path.join(os.path.dirname(__file__))
package = os.path.join(root, '..')
sys.path.insert(0, os.path.abspath(package))
| Make the tests run just via py.test | Make the tests run just via py.test
| Python | mit | kalasjocke/hyp |
11bcc53bc80409a0458e3a5b72014c9837561b65 | src/main/python/setup.py | src/main/python/setup.py | import setuptools
__version__ = None # This will get replaced when reading version.py
exec(open('rlbot/version.py').read())
with open("README.md", "r") as readme_file:
long_description = readme_file.read()
setuptools.setup(
name='rlbot',
packages=setuptools.find_packages(),
install_requires=['psutil', 'inputs', 'PyQt5', 'py4j'],
version=__version__,
description='A framework for writing custom Rocket League bots that run offline.',
long_description=long_description,
long_description_content_type="text/markdown",
author='RLBot Community',
author_email='[email protected]',
url='https://github.com/RLBot/RLBot',
keywords=['rocket-league'],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: Microsoft :: Windows",
],
package_data={
'rlbot': [
'**/*.dll',
'**/*.exe',
'**/*.json',
'gui/design/*.ui',
'**/*.png',
'**/*.md',
'utils/prediction/*.dat'
]
},
)
| import setuptools
__version__ = None # This will get replaced when reading version.py
exec(open('rlbot/version.py').read())
with open("README.md", "r") as readme_file:
long_description = readme_file.read()
setuptools.setup(
name='rlbot',
packages=setuptools.find_packages(),
install_requires=['psutil', 'inputs', 'PyQt5', 'py4j'],
version=__version__,
description='A framework for writing custom Rocket League bots that run offline.',
long_description=long_description,
long_description_content_type="text/markdown",
author='RLBot Community',
author_email='[email protected]',
url='https://github.com/RLBot/RLBot',
keywords=['rocket-league'],
license='MIT License',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: Microsoft :: Windows",
],
package_data={
'rlbot': [
'**/*.dll',
'**/*.exe',
'**/*.json',
'gui/design/*.ui',
'**/*.png',
'**/*.md',
'utils/prediction/*.dat'
]
},
)
| Add MIT license that shows up in `pip show rlbot` | Add MIT license that shows up in `pip show rlbot`
| Python | mit | drssoccer55/RLBot,drssoccer55/RLBot |
39c777d6fc5555534628113190bb543c6225c07e | uncurl/bin.py | uncurl/bin.py | from __future__ import print_function
import sys
from .api import parse
def main():
result = parse(sys.argv[1])
print(result)
| from __future__ import print_function
import sys
from .api import parse
def main():
if sys.stdin.isatty():
result = parse(sys.argv[1])
else:
result = parse(sys.stdin.read())
print(result)
| Read from stdin if available. | Read from stdin if available.
| Python | apache-2.0 | weinerjm/uncurl,spulec/uncurl |
899f28e2cd7dbeb6227e8c56eef541cce1a424f4 | alertaclient/commands/cmd_heartbeat.py | alertaclient/commands/cmd_heartbeat.py | import os
import platform
import sys
import click
prog = os.path.basename(sys.argv[0])
@click.command('heartbeat', short_help='Send a heartbeat')
@click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1]))
@click.option('--tag', '-T', 'tags', multiple=True)
@click.option('--timeout', metavar='EXPIRES', help='Seconds before heartbeat is stale')
@click.option('--delete', '-D', metavar='ID', help='Delete hearbeat')
@click.pass_obj
def cli(obj, origin, tags, timeout, delete):
"""Send or delete a heartbeat."""
client = obj['client']
if delete:
if origin or tags or timeout:
raise click.UsageError('Option "--delete" is mutually exclusive.')
client.delete_heartbeat(delete)
else:
try:
heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout)
except Exception as e:
click.echo('ERROR: {}'.format(e))
sys.exit(1)
click.echo(heartbeat.id)
| import os
import platform
import sys
import click
prog = os.path.basename(sys.argv[0])
@click.command('heartbeat', short_help='Send a heartbeat')
@click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1]))
@click.option('--tag', '-T', 'tags', multiple=True)
@click.option('--timeout', metavar='EXPIRES', type=int, help='Seconds before heartbeat is stale')
@click.option('--delete', '-D', metavar='ID', help='Delete hearbeat')
@click.pass_obj
def cli(obj, origin, tags, timeout, delete):
"""Send or delete a heartbeat."""
client = obj['client']
if delete:
if origin or tags or timeout:
raise click.UsageError('Option "--delete" is mutually exclusive.')
client.delete_heartbeat(delete)
else:
try:
heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout)
except Exception as e:
click.echo('ERROR: {}'.format(e))
sys.exit(1)
click.echo(heartbeat.id)
| Add check that heartbeat timeout is integer | Add check that heartbeat timeout is integer
| Python | apache-2.0 | alerta/python-alerta-client,alerta/python-alerta-client,alerta/python-alerta |
ee8cb600c772e4a0f795a0fe00b1e612cb8a8e37 | dirmuncher.py | dirmuncher.py | #!/usr/bin/env python
# -*- Coding: utf-8 -*-
import os
class Dirmuncher:
def __init__(self, directory):
self.directory = directory
def directoryListing(self):
for dirname, dirnames, filenames in os.walk(self.directory):
# Subdirectories
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# Filenames
for filename in filenames:
print(os.path.join(dirname, filename))
if __name__ == "__main__":
muncher = Dirmuncher('movies')
muncher.directoryListing()
| #!/usr/bin/env python
# -*- Coding: utf-8 -*-
import os
class Dirmuncher:
def __init__(self, directory):
self.directory = directory
def getFiles(self):
result = {}
for dirname, dirnames, filenames in os.walk(self.directory):
# Subdirectories
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# Filenames
for filename in filenames:
print(os.path.join(dirname, filename))
result[dirname] = filenames
return result
if __name__ == "__main__":
muncher = Dirmuncher('movies')
print(muncher.getFiles())
| Sort files into dict with dir as key | [py] Sort files into dict with dir as key
| Python | mit | claudemuller/masfir |
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 |
916900aaa29c5a59bcdd78ca05069ea431629de4 | tests/test_cmd.py | tests/test_cmd.py | import unittest
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
cls.cli_run = cli_run
def test_initdb(self):
result = self.cli_run('initdb')
self.assertEqual(0, result.exit_code, msg=result.output)
| import unittest
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
cls.cli_run = cli_run
def test_initdb(self):
result = self.cli_run('initdb')
self.assertEqual(0, result.exit_code, msg=result.exception)
| Fix error message for initdb test | Fix error message for initdb test
| Python | agpl-3.0 | SCUEvals/scuevals-api,SCUEvals/scuevals-api |
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 |
a473e54f5643483efc490f6362f0fca6fcf0c5bd | zappa/__init__.py | zappa/__init__.py |
import sys
SUPPORTED_VERSIONS = [(2, 7), (3, 6)]
python_major_version = sys.version_info[0]
python_minor_version = sys.version_info[1]
if (python_major_version, python_minor_version) not in SUPPORTED_VERSIONS:
formatted_supported_versions = ['{}.{}'.format(mav, miv) for mav, miv in SUPPORTED_VERSIONS]
err_msg = 'This version of Python ({}.{}) is not supported!\n'.format(python_major_version, python_minor_version) +\
'Zappa (and AWS Lambda) support the following versions of Python: {}'.format(formatted_supported_versions)
raise RuntimeError(err_msg)
| Check Python version upon import | Check Python version upon import
| Python | mit | scoates/Zappa,pjz/Zappa,mathom/Zappa,Miserlou/Zappa,anush0247/Zappa,Miserlou/Zappa,mathom/Zappa,scoates/Zappa,pjz/Zappa,anush0247/Zappa |
|
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 |
ecd06f371fb83823494b17e341d7c4cf8bf117d0 | utils/bug_reducer/bug_reducer/bug_reducer.py | utils/bug_reducer/bug_reducer/bug_reducer.py | #!/usr/bin/env python
import argparse
import opt_bug_reducer
import random_bug_finder
def main():
parser = argparse.ArgumentParser(description="""\
A program for reducing sib/sil crashers""")
subparsers = parser.add_subparsers()
opt_subparser = subparsers.add_parser("opt")
opt_subparser.add_argument('swift_build_dir',
help='Path to the swift build directory '
'containing tools to use')
opt_bug_reducer.add_parser_arguments(opt_subparser)
random_search_subparser = subparsers.add_parser("random-search")
random_search_subparser.add_argument('swift_build_dir',
help='Path to the swift build '
'directory containing tools to use')
random_bug_finder.add_parser_arguments(random_search_subparser)
args = parser.parse_args()
args.func(args)
main()
| #!/usr/bin/env python
import argparse
import opt_bug_reducer
import random_bug_finder
def add_subparser(subparsers, module, name):
sparser = subparsers.add_parser(name)
sparser.add_argument('swift_build_dir',
help='Path to the swift build directory '
'containing tools to use')
module.add_parser_arguments(sparser)
def main():
parser = argparse.ArgumentParser(description="""\
A program for reducing sib/sil crashers""")
subparsers = parser.add_subparsers()
add_subparser(subparsers, opt_bug_reducer, 'opt')
add_subparser(subparsers, random_bug_finder, 'random-search')
args = parser.parse_args()
args.func(args)
main()
| Refactor adding subparsers given that all subparsers have a common swift_build_dir arg. | [sil-bug-reducer] Refactor adding subparsers given that all subparsers have a common swift_build_dir arg.
| Python | apache-2.0 | uasys/swift,JaSpa/swift,milseman/swift,harlanhaskins/swift,gregomni/swift,sschiau/swift,austinzheng/swift,xedin/swift,xwu/swift,codestergit/swift,harlanhaskins/swift,huonw/swift,shahmishal/swift,lorentey/swift,deyton/swift,gmilos/swift,sschiau/swift,gregomni/swift,harlanhaskins/swift,shajrawi/swift,stephentyrone/swift,airspeedswift/swift,hooman/swift,tinysun212/swift-windows,jmgc/swift,nathawes/swift,frootloops/swift,tjw/swift,felix91gr/swift,austinzheng/swift,OscarSwanros/swift,roambotics/swift,gribozavr/swift,glessard/swift,ahoppen/swift,arvedviehweger/swift,djwbrown/swift,therealbnut/swift,hooman/swift,nathawes/swift,felix91gr/swift,gribozavr/swift,natecook1000/swift,CodaFi/swift,JGiola/swift,Jnosh/swift,frootloops/swift,shahmishal/swift,jtbandes/swift,roambotics/swift,sschiau/swift,stephentyrone/swift,jtbandes/swift,zisko/swift,arvedviehweger/swift,lorentey/swift,xedin/swift,jckarter/swift,ahoppen/swift,hughbe/swift,zisko/swift,devincoughlin/swift,codestergit/swift,felix91gr/swift,calebd/swift,deyton/swift,jmgc/swift,return/swift,allevato/swift,manavgabhawala/swift,gmilos/swift,harlanhaskins/swift,uasys/swift,zisko/swift,amraboelela/swift,tardieu/swift,nathawes/swift,gmilos/swift,hooman/swift,karwa/swift,harlanhaskins/swift,apple/swift,swiftix/swift,felix91gr/swift,gregomni/swift,deyton/swift,danielmartin/swift,gregomni/swift,frootloops/swift,deyton/swift,felix91gr/swift,codestergit/swift,bitjammer/swift,gmilos/swift,codestergit/swift,danielmartin/swift,manavgabhawala/swift,bitjammer/swift,jckarter/swift,djwbrown/swift,rudkx/swift,manavgabhawala/swift,tardieu/swift,felix91gr/swift,xedin/swift,calebd/swift,practicalswift/swift,glessard/swift,benlangmuir/swift,xedin/swift,shahmishal/swift,milseman/swift,devincoughlin/swift,milseman/swift,apple/swift,sschiau/swift,karwa/swift,jtbandes/swift,glessard/swift,brentdax/swift,stephentyrone/swift,therealbnut/swift,JGiola/swift,austinzheng/swift,zisko/swift,milseman/swift,natecook1000/swift,benlangmuir/swift,frootloops/swift,jckarter/swift,gribozavr/swift,deyton/swift,return/swift,ahoppen/swift,jtbandes/swift,benlangmuir/swift,sschiau/swift,benlangmuir/swift,milseman/swift,austinzheng/swift,OscarSwanros/swift,glessard/swift,hughbe/swift,gmilos/swift,practicalswift/swift,shahmishal/swift,atrick/swift,Jnosh/swift,tinysun212/swift-windows,tkremenek/swift,aschwaighofer/swift,Jnosh/swift,milseman/swift,atrick/swift,alblue/swift,xwu/swift,jmgc/swift,gottesmm/swift,djwbrown/swift,swiftix/swift,airspeedswift/swift,parkera/swift,practicalswift/swift,JaSpa/swift,arvedviehweger/swift,manavgabhawala/swift,huonw/swift,allevato/swift,aschwaighofer/swift,huonw/swift,uasys/swift,parkera/swift,tkremenek/swift,gregomni/swift,uasys/swift,atrick/swift,djwbrown/swift,jopamer/swift,jopamer/swift,parkera/swift,hughbe/swift,uasys/swift,tinysun212/swift-windows,jmgc/swift,OscarSwanros/swift,nathawes/swift,harlanhaskins/swift,alblue/swift,tardieu/swift,brentdax/swift,arvedviehweger/swift,swiftix/swift,lorentey/swift,hughbe/swift,airspeedswift/swift,jmgc/swift,tardieu/swift,ahoppen/swift,JaSpa/swift,swiftix/swift,natecook1000/swift,hooman/swift,aschwaighofer/swift,rudkx/swift,manavgabhawala/swift,OscarSwanros/swift,brentdax/swift,tjw/swift,rudkx/swift,shajrawi/swift,shahmishal/swift,amraboelela/swift,amraboelela/swift,CodaFi/swift,tardieu/swift,karwa/swift,jckarter/swift,OscarSwanros/swift,alblue/swift,aschwaighofer/swift,amraboelela/swift,allevato/swift,devincoughlin/swift,therealbnut/swift,calebd/swift,aschwaighofer/swift,jopamer/swift,alblue/swift,ahoppen/swift,codestergit/swift,jopamer/swift,huonw/swift,CodaFi/swift,swiftix/swift,calebd/swift,xwu/swift,gottesmm/swift,brentdax/swift,atrick/swift,natecook1000/swift,manavgabhawala/swift,tkremenek/swift,Jnosh/swift,amraboelela/swift,practicalswift/swift,austinzheng/swift,stephentyrone/swift,lorentey/swift,jckarter/swift,felix91gr/swift,roambotics/swift,xedin/swift,uasys/swift,hooman/swift,parkera/swift,arvedviehweger/swift,JGiola/swift,djwbrown/swift,gribozavr/swift,shahmishal/swift,tardieu/swift,zisko/swift,hooman/swift,harlanhaskins/swift,JaSpa/swift,stephentyrone/swift,karwa/swift,huonw/swift,tkremenek/swift,djwbrown/swift,glessard/swift,karwa/swift,airspeedswift/swift,shahmishal/swift,amraboelela/swift,bitjammer/swift,swiftix/swift,xedin/swift,tinysun212/swift-windows,tkremenek/swift,parkera/swift,hughbe/swift,therealbnut/swift,therealbnut/swift,therealbnut/swift,shajrawi/swift,tkremenek/swift,tjw/swift,return/swift,lorentey/swift,gottesmm/swift,devincoughlin/swift,karwa/swift,apple/swift,JaSpa/swift,airspeedswift/swift,CodaFi/swift,brentdax/swift,gribozavr/swift,frootloops/swift,roambotics/swift,alblue/swift,huonw/swift,jmgc/swift,allevato/swift,gottesmm/swift,gottesmm/swift,karwa/swift,huonw/swift,atrick/swift,xwu/swift,shajrawi/swift,xwu/swift,gribozavr/swift,lorentey/swift,alblue/swift,bitjammer/swift,Jnosh/swift,allevato/swift,deyton/swift,gregomni/swift,hughbe/swift,danielmartin/swift,devincoughlin/swift,OscarSwanros/swift,aschwaighofer/swift,practicalswift/swift,rudkx/swift,alblue/swift,JaSpa/swift,JaSpa/swift,danielmartin/swift,airspeedswift/swift,manavgabhawala/swift,shajrawi/swift,natecook1000/swift,zisko/swift,natecook1000/swift,apple/swift,jopamer/swift,tjw/swift,parkera/swift,codestergit/swift,benlangmuir/swift,glessard/swift,apple/swift,nathawes/swift,frootloops/swift,gottesmm/swift,jopamer/swift,practicalswift/swift,shajrawi/swift,jtbandes/swift,tjw/swift,roambotics/swift,xedin/swift,return/swift,danielmartin/swift,calebd/swift,JGiola/swift,CodaFi/swift,sschiau/swift,jmgc/swift,airspeedswift/swift,danielmartin/swift,shajrawi/swift,amraboelela/swift,xedin/swift,aschwaighofer/swift,deyton/swift,jtbandes/swift,devincoughlin/swift,return/swift,tinysun212/swift-windows,calebd/swift,parkera/swift,tinysun212/swift-windows,bitjammer/swift,hooman/swift,xwu/swift,lorentey/swift,JGiola/swift,tkremenek/swift,stephentyrone/swift,jtbandes/swift,jckarter/swift,devincoughlin/swift,lorentey/swift,natecook1000/swift,atrick/swift,arvedviehweger/swift,brentdax/swift,tjw/swift,karwa/swift,parkera/swift,tjw/swift,gottesmm/swift,hughbe/swift,sschiau/swift,xwu/swift,zisko/swift,devincoughlin/swift,tinysun212/swift-windows,shahmishal/swift,brentdax/swift,jopamer/swift,apple/swift,uasys/swift,benlangmuir/swift,JGiola/swift,Jnosh/swift,return/swift,rudkx/swift,allevato/swift,gribozavr/swift,shajrawi/swift,austinzheng/swift,stephentyrone/swift,ahoppen/swift,djwbrown/swift,return/swift,gmilos/swift,practicalswift/swift,CodaFi/swift,jckarter/swift,danielmartin/swift,nathawes/swift,frootloops/swift,tardieu/swift,roambotics/swift,codestergit/swift,gmilos/swift,practicalswift/swift,milseman/swift,OscarSwanros/swift,Jnosh/swift,bitjammer/swift,CodaFi/swift,bitjammer/swift,allevato/swift,arvedviehweger/swift,calebd/swift,nathawes/swift,sschiau/swift,swiftix/swift,rudkx/swift,austinzheng/swift,gribozavr/swift,therealbnut/swift |
2d01301e9154045f4b15d1523089ad36fdd7f6f4 | cs251tk/toolkit/process_student.py | cs251tk/toolkit/process_student.py | import os
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
from cs251tk.common import run
from ..common import chdir
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
| import os
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
| Remove leftover imports from testing | Remove leftover imports from testing | Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit |
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 |
fdf014fb0602cbba476b0e35d451f43e86be7cdc | django_project/core/settings/test_travis.py | django_project/core/settings/test_travis.py | # -*- coding: utf-8 -*-
from .test import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
# Set to empty string for default.
'PORT': '',
}
}
| # -*- coding: utf-8 -*-
from .test import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
# Set to empty string for default.
'PORT': '',
}
}
| Fix wrong db name for travis. | Fix wrong db name for travis.
| Python | bsd-2-clause | AIFDR/inasafe-django,timlinux/inasafe-django,timlinux/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django,timlinux/inasafe-django,AIFDR/inasafe-django,timlinux/inasafe-django |
d7624defd7d05e721aeb0ccd074c7172c51295bf | nvchecker_source/git.py | nvchecker_source/git.py | # MIT licensed
# Copyright (c) 2020 Felix Yan <[email protected]>, 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 <[email protected]>, 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 |
36e5af74e6ecaba4cea4bfcd2c1ef997d1e15eb0 | openstack/tests/functional/telemetry/v2/test_meter.py | openstack/tests/functional/telemetry/v2/test_meter.py | # 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.
from openstack.tests.functional import base
class TestMeter(base.BaseFunctionalTest):
def test_list(self):
names = set([o.name for o in self.conn.telemetry.meters()])
self.assertIn('storage.objects', names)
| # 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.
import uuid
from openstack.tests.functional import base
class TestMeter(base.BaseFunctionalTest):
def test_list(self):
# TODO(thowe): Remove this in favor of create_meter call.
# Since we do not have a create meter method at the moment
# make sure there is some data in there
name = uuid.uuid4().hex
tainer = self.conn.object_store.create_container(name=name)
self.conn.object_store.delete_container(tainer)
names = set([o.name for o in self.conn.telemetry.meters()])
self.assertIn('storage.objects', names)
| Make sure there is data for the meter test | Make sure there is data for the meter test
The meter tests relies on someone else creating a meter. If
this test happens to run on a brand new system and it runs before
the object store tests, it may fail. For some object store
activity before the test.
Change-Id: Ie9b7775bad4550842bfdaebd893eb8293590b7ff
| Python | apache-2.0 | openstack/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,dudymas/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,dudymas/python-openstacksdk,briancurtin/python-openstacksdk |
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 |
0e60863d43a5b230839191743f72818763eeee71 | buildPy2app.py | buildPy2app.py | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
| """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
| Update py2app script for Qt 5.11 | Update py2app script for Qt 5.11
| Python | apache-2.0 | Syncplay/syncplay,NeverDecaf/syncplay,NeverDecaf/syncplay,alby128/syncplay,Syncplay/syncplay,alby128/syncplay |
326f0b881d36ed19d0a37495ae34fc24fc1eb707 | connect_ffi.py | connect_ffi.py | from cffi import FFI
ffi = FFI()
print "Loading Spotify library..."
#TODO: Use absolute paths for open() and stuff
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
with open("spotify.processed.h") as file:
header = file.read()
ffi.cdef(header)
ffi.cdef("""
void *malloc(size_t size);
void exit(int status);
""")
C = ffi.dlopen(None)
lib = ffi.verify("""
#include "spotify.h"
""", include_dirs=['./'],
library_dirs=['./'],
libraries=[str('spotify_embedded_shared')]) | from cffi import FFI
ffi = FFI()
print "Loading Spotify library..."
#TODO: Use absolute paths for open() and stuff
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
with open(os.path.join(sys.path[0], "spotify.processed.h")) as file:
header = file.read()
ffi.cdef(header)
ffi.cdef("""
void *malloc(size_t size);
void exit(int status);
""")
C = ffi.dlopen(None)
lib = ffi.verify("""
#include "spotify.h"
""", include_dirs=['./'],
library_dirs=['./'],
libraries=[str('spotify_embedded_shared')]) | Load the spotify header file from an absolute path | Load the spotify header file from an absolute path
| Python | mit | Fornoth/spotify-connect-web,Fornoth/spotify-connect-web,Fornoth/spotify-connect-web,Fornoth/spotify-connect-web,Fornoth/spotify-connect-web |
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 |
a96cb89524f2fa17a015011d972d396e509a1079 | journal.py | journal.py | # -*- coding: utf-8 -*-
from flask import Flask
import os
import psycopg2
from contextlib import closing
DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id serial PRIMARY KEY,
title VARCHAR (127) NOT NULL,
text TEXT NOT NULL,
created TIMESTAMP NOT NULL
)
"""
app = Flask(__name__)
@app.route('/')
def hello():
return u'Hello world!'
app.config['DATABASE'] = os.environ.get(
'DATABASE_URL', 'dbname=learning_journal user=elizabethrives'
)
def connect_db():
"""Return a connection to the configured database"""
return psycopg2.connect(app.config['DATABASE'])
def init_db():
"""Initialize the database using DB_SCHEMA
WARNING: executing this function will drop existing tables.
"""
with closing(connect_db()) as db:
db.cursor().execute(DB_SCHEMA)
db.commit()
if __name__ == '__main__':
app.run(debug=True)
| # -*- coding: utf-8 -*-
from flask import Flask
import os
import psycopg2
from contextlib import closing
from flask import g
DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id serial PRIMARY KEY,
title VARCHAR (127) NOT NULL,
text TEXT NOT NULL,
created TIMESTAMP NOT NULL
)
"""
app = Flask(__name__)
@app.route('/')
def hello():
return u'Hello world!'
app.config['DATABASE'] = os.environ.get(
'DATABASE_URL', 'dbname=learning_journal user=elizabethrives'
)
def connect_db():
"""Return a connection to the configured database"""
return psycopg2.connect(app.config['DATABASE'])
def init_db():
"""Initialize the database using DB_SCHEMA
WARNING: executing this function will drop existing tables.
"""
with closing(connect_db()) as db:
db.cursor().execute(DB_SCHEMA)
db.commit()
def get_database_connection():
db = getattr(g, 'db', None)
if db is None:
g.db = db = connect_db()
return db
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
if exception and isinstance(exception, psycopg2.Error):
db.rollback()
else:
db.commit()
db.close()
if __name__ == '__main__':
app.run(debug=True)
| Add code for getting and releasing a database connection | Add code for getting and releasing a database connection
| Python | mit | rivese/learning_journal,EyuelAbebe/learning_journal,EyuelAbebe/learning_journal |
69705079398391cdc392b18dcd440fbc3b7404fd | celery_cgi.py | celery_cgi.py | import os
import logging
from celery import Celery
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_server = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
celery_tasks = [
'hms_flask.modules.hms_controller',
'pram_flask.tasks'
]
redis = 'redis://' + redis_server + ':' + redis_port + '/0'
logging.info("Celery connecting to redis server: " + redis)
celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks)
celery.conf.update(
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
CELERY_IGNORE_RESULT=False,
CELERY_TRACK_STARTED=True,
)
| import os
import logging
from celery import Celery
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_server = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
celery_tasks = [
'hms_flask.modules.hms_controller',
'pram_flask.tasks'
]
redis = 'redis://' + redis_server + ':' + redis_port + '/0'
logging.info("Celery connecting to redis server: " + redis)
celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks)
celery.conf.update(
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
CELERY_IGNORE_RESULT=True,
CELERY_TRACK_STARTED=True,
)
| Set celery to ignore results | Set celery to ignore results | Python | unlicense | puruckertom/ubertool_ecorest,puruckertom/ubertool_ecorest,quanted/ubertool_ecorest,quanted/ubertool_ecorest,puruckertom/ubertool_ecorest,quanted/ubertool_ecorest,quanted/ubertool_ecorest,puruckertom/ubertool_ecorest |
a6ed56b37bba3f5abff73c297a8a20271d73cab2 | example/random-agent/random-agent.py | example/random-agent/random-agent.py | #!/usr/bin/env python
import argparse
import logging
import sys
import gym
import universe # register the universe environments
from universe import wrappers
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(description=None)
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
args = parser.parse_args()
if args.verbosity == 0:
logger.setLevel(logging.INFO)
elif args.verbosity >= 1:
logger.setLevel(logging.DEBUG)
env = gym.make('flashgames.NeonRace-v0')
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
# keyboard/mouse.)
env = wrappers.SafeActionSpace(env)
observation_n = env.reset()
while True:
# your agent here
#
# Try sending this instead of a random action: ('KeyEvent', 'ArrowUp', True)
action_n = [env.action_space.sample() for ob in observation_n]
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
return 0
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
import argparse
import logging
import sys
import gym
import universe # register the universe environments
from universe import wrappers
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(description=None)
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
args = parser.parse_args()
if args.verbosity == 0:
logger.setLevel(logging.INFO)
elif args.verbosity >= 1:
logger.setLevel(logging.DEBUG)
env = gym.make('flashgames.NeonRace-v0')
env.configure(remotes=1) # automatically creates a local docker container
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
# keyboard/mouse.)
env = wrappers.SafeActionSpace(env)
observation_n = env.reset()
while True:
# your agent here
#
# Try sending this instead of a random action: ('KeyEvent', 'ArrowUp', True)
action_n = [env.action_space.sample() for ob in observation_n]
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
return 0
if __name__ == '__main__':
sys.exit(main())
| Add configure call to random_agent | Add configure call to random_agent
| Python | mit | openai/universe,rht/universe |
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 |
a0fab69d12d64d4e5371fcb26a4ec70365a76fa6 | cref/app/web/tasks.py | cref/app/web/tasks.py | from celery import Celery
from cref.app.terminal import run_cref
app = Celery(
'tasks',
backend='db+sqlite:///results.sqlite',
broker='amqp://guest@localhost//'
)
@app.task
def predict_structure(sequence, params={}):
return run_cref(sequence)
| from celery import Celery
from cref.app.terminal import run_cref
app = Celery(
'tasks',
backend='db+sqlite:///data/results.sqlite',
broker='amqp://guest@localhost//'
)
@app.task
def predict_structure(sequence, params={}):
return run_cref(sequence)
| Move task results database to data dir | Move task results database to data dir
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 |
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 |
921bdcc5d6f6ac4be7dfd0015e5b5fd6d06e6486 | runcommands/__main__.py | runcommands/__main__.py | import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
run_args = read_run_args(run)
run_args.update(cli_args)
run.implementation(
None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
cli_args=cli_args, **run_args)
except RunCommandsError as exc:
printer.error(exc, file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
| import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
debug = None
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
run_args = read_run_args(run)
run_args.update(cli_args)
debug = run_args.get('debug', run.parameters['debug'].default)
run.implementation(
None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
cli_args=cli_args, **run_args)
except RunCommandsError as exc:
if debug or debug is None:
# User specified --debug OR processing didn't get far enough
# to determine whether user specified --debug.
raise
printer.error(exc, file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
| Raise exception when --debug is specified to main script | Raise exception when --debug is specified to main script
I.e., instead of printing the exception and then exiting.
| Python | mit | wylee/runcommands,wylee/runcommands |
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 |
Subsets and Splits