commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
e525db1171ccd75db737cea08c377c8c03400c24
imdb_main.py
imdb_main.py
from AllMovies_imdb import add_empty_data, get_connections, get_business_of_movie, check_worksheets, get_companycredits_of_movie, get_fullcredits_of_movie, get_releaseinfo_of_movie, get_techinfo_of_movie, get_detail_of_movie, register_toServer, upload_data, init_page #Here's the main while True: session= register_toServer() # 1. try to register todo = check_worksheets(session) # 2. obtain the todo list if todo is None: # 3. if no longer things to do, exit print "Done." break else: fileuri= get_all_movies(session, todo, Config.SINGLE_TEST_MODE) # 4. if it has things to do, do work. if fileuri == "": print "There's no file." todo.status = "done" todo.save() else: upload_data(session, todo, fileuri)
from AllMovies_imdb import get_all_movies, add_empty_data, get_connections, get_business_of_movie, check_worksheets, get_companycredits_of_movie, get_fullcredits_of_movie, get_releaseinfo_of_movie, get_techinfo_of_movie, get_detail_of_movie, register_toServer, upload_data, init_page #Here's the main while True: session= register_toServer() # 1. try to register todo = check_worksheets(session) # 2. obtain the todo list if todo is None: # 3. if no longer things to do, exit print "Done." break else: fileuri= get_all_movies(session, todo, Config.SINGLE_TEST_MODE) # 4. if it has things to do, do work. if fileuri == "": print "There's no file." todo.status = "done" todo.save() else: upload_data(session, todo, fileuri)
Add omitted get_all_movies function in main.
Add omitted get_all_movies function in main.
Python
apache-2.0
softinus/IMDB_DataMiner,softinus/Movie_DataMiner,softinus/IMDB_DataMiner,softinus/Movie_DataMiner
--- +++ @@ -1,5 +1,5 @@ -from AllMovies_imdb import add_empty_data, get_connections, get_business_of_movie, check_worksheets, get_companycredits_of_movie, get_fullcredits_of_movie, get_releaseinfo_of_movie, get_techinfo_of_movie, get_detail_of_movie, register_toServer, upload_data, init_page +from AllMovies_imdb import get_all_movies, add_empty_data, get_connections, get_business_of_movie, check_worksheets, get_companycredits_of_movie, get_fullcredits_of_movie, get_releaseinfo_of_movie, get_techinfo_of_movie, get_detail_of_movie, register_toServer, upload_data, init_page #Here's the main while True:
0981fee3834467fcde7f2231ff3b7d35371b9d09
cms/__init__.py
cms/__init__.py
""" A collection of Django extensions that add content-management facilities to Django projects. Developed by Dave Hall. <http://etianen.com/> """ VERSION = (1, 7, 11)
""" A collection of Django extensions that add content-management facilities to Django projects. Developed by Dave Hall. <http://etianen.com/> """ VERSION = (1, 8)
Bump version number for release.
Bump version number for release.
Python
bsd-3-clause
lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,danielsamuels/cms,dan-gamble/cms,dan-gamble/cms,jamesfoley/cms,lewiscollard/cms,danielsamuels/cms,danielsamuels/cms,jamesfoley/cms,jamesfoley/cms,lewiscollard/cms
--- +++ @@ -6,4 +6,4 @@ <http://etianen.com/> """ -VERSION = (1, 7, 11) +VERSION = (1, 8)
67e0d2b943ef467cfef46f71195f205b1be15a0a
cms/__init__.py
cms/__init__.py
# -*- coding: utf-8 -*- __version__ = '2.3.5pbs.19' # patch settings try: from django.conf import settings if 'cms' in settings.INSTALLED_APPS: from conf import patch_settings patch_settings() except ImportError: # pragma: no cover """ This exception means that either the application is being built, or is otherwise installed improperly. Both make running patch_settings irrelevant. """ pass
# -*- coding: utf-8 -*- __version__ = '2.3.5pbs.20' # patch settings try: from django.conf import settings if 'cms' in settings.INSTALLED_APPS: from conf import patch_settings patch_settings() except ImportError: # pragma: no cover """ This exception means that either the application is being built, or is otherwise installed improperly. Both make running patch_settings irrelevant. """ pass
Bump version as instructed by bamboo.
Bump version as instructed by bamboo.
Python
bsd-3-clause
pbs/django-cms,pbs/django-cms,pbs/django-cms,pbs/django-cms
--- +++ @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -__version__ = '2.3.5pbs.19' +__version__ = '2.3.5pbs.20' # patch settings try:
3c534faee2f97dd8e2b5503fdbcac59737489f54
backend/scripts/ddirdenorm.py
backend/scripts/ddirdenorm.py
#!/usr/bin/env python import rethinkdb as r conn = r.connect('localhost', 30815, db='materialscommons') if __name__ == "__main__": selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
#!/usr/bin/env python import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
Add options for setting the port.
Add options for setting the port.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -1,10 +1,16 @@ #!/usr/bin/env python import rethinkdb as r +import optparse -conn = r.connect('localhost', 30815, db='materialscommons') if __name__ == "__main__": + parser = optparse.OptionParser() + parser.add_option("-p", "--port", dest="port", + help="rethinkdb port", default=30815) + (options, args) = parser.parse_args() + conn = r.connect('localhost', int(options.port), db='materialscommons') + selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name'])
8139a3a49e4ee6d1fc8a2a71becbfd6d625b5c5f
apps/accounts/serializers.py
apps/accounts/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.fields import HyperlinkedIdentityField class MemberDetailSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='member-detail') class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'url') class MemberListSerializer(MemberDetailSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'url')
from apps.bluebottle_utils.serializers import SorlImageField from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.fields import HyperlinkedIdentityField class MemberDetailSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='member-detail') picture = SorlImageField('userprofile.picture', '100x100', crop='center') class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture') class MemberListSerializer(MemberDetailSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'url')
Add picture field member detail api.
Add picture field member detail api.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
--- +++ @@ -1,3 +1,4 @@ +from apps.bluebottle_utils.serializers import SorlImageField from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.fields import HyperlinkedIdentityField @@ -6,10 +7,11 @@ class MemberDetailSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='member-detail') + picture = SorlImageField('userprofile.picture', '100x100', crop='center') class Meta: model = User - fields = ('id', 'first_name', 'last_name', 'username', 'url') + fields = ('id', 'first_name', 'last_name', 'username', 'url', 'picture') class MemberListSerializer(MemberDetailSerializer):
88d938fc4050ef99180ff364f0a6d27d31ecc16c
lambdautils/metadata.py
lambdautils/metadata.py
# -*- coding: utf-8 -*- """Project metadata.""" package = "lambdautils" project = "lambdautils" version = '0.2.8' description = "Simple utilities for AWS Lambda functions" authors = ["Innovative Travel Ltd"] authors_string = ', '.join(authors) emails = ['german@innovativetravel.eu'] license = 'MIT' copyright = '2016 ' + authors_string url = 'http://github.com/InnovativeTravel/humilis-lambdautils'
# -*- coding: utf-8 -*- """Project metadata.""" package = "lambdautils" project = "lambdautils" version = '0.2.9' description = "Simple utilities for AWS Lambda functions" authors = ["Innovative Travel Ltd"] authors_string = ', '.join(authors) emails = ['german@innovativetravel.eu'] license = 'MIT' copyright = '2016 ' + authors_string url = 'http://github.com/InnovativeTravel/humilis-lambdautils'
Support for externally produced Kinesis partition keys
Support for externally produced Kinesis partition keys
Python
mit
humilis/humilis-lambdautils
--- +++ @@ -3,7 +3,7 @@ package = "lambdautils" project = "lambdautils" -version = '0.2.8' +version = '0.2.9' description = "Simple utilities for AWS Lambda functions" authors = ["Innovative Travel Ltd"] authors_string = ', '.join(authors)
65b3a7fa7ae7ee467d3e8ef32b9a00b99b095c3e
humblemedia/processing_spooler.py
humblemedia/processing_spooler.py
import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() att = Attachment.objects.get(id=resource_id) for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: instance = cls(att) instance.process() break return uwsgi.SPOOL_OK uwsgi.spooler = content_processing
import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() try: att = Attachment.objects.get(id=resource_id) except Attachment.DoesNotExist: return uwsgi.SPOOL_OK for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: instance = cls(att) instance.process() break return uwsgi.SPOOL_OK uwsgi.spooler = content_processing
Return ok if db object does not exist in spooler
Return ok if db object does not exist in spooler
Python
mit
vladimiroff/humble-media,vladimiroff/humble-media
--- +++ @@ -11,7 +11,10 @@ print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() - att = Attachment.objects.get(id=resource_id) + try: + att = Attachment.objects.get(id=resource_id) + except Attachment.DoesNotExist: + return uwsgi.SPOOL_OK for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name:
b58b270c707b57e9f6c245f1ebb31d68a247471c
mastering-python/ch05/Decorator.py
mastering-python/ch05/Decorator.py
import functools def logParams(function): @functools.wraps(function) # use this to prevent loss of function attributes def wrapper(*args, **kwargs): print("function: {}, args: {}, kwargs: {}".format(function.__name__, args, kwargs)) return function(*args, **kwargs) return wrapper def add(a, b): return a + b @logParams def mul(a, b): return a * b add(1, 1) mul(2, 2) def memo(function): function.cache = dict() @functools.wraps(function) def wrapper(*args): if args not in function.cache: function.cache[args] = function(*args) return function.cache[args] return wrapper @memo def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) for i in range(1, 10): print("fib{}:{}".format(i, fib(i)))
import functools def logParams(function): @functools.wraps(function) # use this to prevent loss of function attributes def wrapper(*args, **kwargs): print("function: {}, args: {}, kwargs: {}".format(function.__name__, args, kwargs)) return function(*args, **kwargs) return wrapper def add(a, b): return a + b @logParams def mul(a, b): return a * b add(1, 1) mul(2, 2) def memo(function): function.cache = dict() @functools.wraps(function) def wrapper(*args): if args not in function.cache: function.cache[args] = function(*args) return function.cache[args] return wrapper @memo def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) for i in range(1, 10): print("fib{}:{}".format(i, fib(i))) def trace(func): @functools.wraps(func) def _trace(self, *args): print("Invoking {} - {}".format(self, args)) func(self, *args) return _trace class FooBar: @trace def dummy(self, s): print(s) fb = FooBar() fb.dummy("Hello")
Add class method decorator demo.
Add class method decorator demo.
Python
apache-2.0
precompiler/python-101
--- +++ @@ -38,3 +38,20 @@ for i in range(1, 10): print("fib{}:{}".format(i, fib(i))) + + +def trace(func): + @functools.wraps(func) + def _trace(self, *args): + print("Invoking {} - {}".format(self, args)) + func(self, *args) + return _trace + + +class FooBar: + @trace + def dummy(self, s): + print(s) + +fb = FooBar() +fb.dummy("Hello")
3f39c9d89da004556bcf53fa815f88a3092f600e
syft/frameworks/torch/tensors/native.py
syft/frameworks/torch/tensors/native.py
import random from syft.frameworks.torch.tensors import PointerTensor import syft class TorchTensor: """ This tensor is simply a more convenient way to add custom functions to all Torch tensor types. """ def __init__(self): self.id = None self.owner = syft.local_worker def create_pointer( self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None ): if owner is None: owner = self.owner if location is None: location = self.owner.id owner = self.owner.get_worker(owner) location = self.owner.get_worker(location) if id_at_location is None: id_at_location = self.id if ptr_id is None: if location.id != self.owner.id: ptr_id = self.id else: ptr_id = int(10e10 * random.random()) # previous_pointer = owner.get_pointer_to(location, id_at_location) previous_pointer = None if previous_pointer is None: ptr = PointerTensor( parent=self, location=location, id_at_location=id_at_location, register=register, owner=owner, id=ptr_id, ) return ptr
import random from syft.frameworks.torch.tensors import PointerTensor class TorchTensor: """ This tensor is simply a more convenient way to add custom functions to all Torch tensor types. """ def __init__(self): self.id = None self.owner = None def create_pointer( self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None ): if owner is None: owner = self.owner if location is None: location = self.owner.id owner = self.owner.get_worker(owner) location = self.owner.get_worker(location) if id_at_location is None: id_at_location = self.id if ptr_id is None: if location.id != self.owner.id: ptr_id = self.id else: ptr_id = int(10e10 * random.random()) # previous_pointer = owner.get_pointer_to(location, id_at_location) previous_pointer = None if previous_pointer is None: ptr = PointerTensor( parent=self, location=location, id_at_location=id_at_location, register=register, owner=owner, id=ptr_id, ) return ptr
Set local worker as default for SyftTensor owner
Undone: Set local worker as default for SyftTensor owner
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
--- +++ @@ -1,8 +1,6 @@ import random from syft.frameworks.torch.tensors import PointerTensor - -import syft class TorchTensor: @@ -13,7 +11,7 @@ def __init__(self): self.id = None - self.owner = syft.local_worker + self.owner = None def create_pointer( self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None
ab0141d4ea11e20482bb1ae9d5642ed0e6fc3fac
saleor/product/utils.py
saleor/product/utils.py
from django.core.exceptions import ObjectDoesNotExist def get_attributes_display(variant, attributes): display = {} for attribute in attributes: value = variant.get_attribute(attribute.pk) if value: try: choice = attribute.values.get(pk=value) except ObjectDoesNotExist: pass except ValueError: display[attribute.pk] = value else: display[attribute.pk] = choice return display
def get_attributes_display(variant, attributes): display = {} for attribute in attributes: value = variant.get_attribute(attribute.pk) if value: choices = attribute.values.all() if choices: for choice in attribute.values.all(): if choice.pk == value: display[attribute.pk] = choice break else: display[attribute.pk] = value return display
Reduce number of queries of getting attributes display
Reduce number of queries of getting attributes display
Python
bsd-3-clause
UITools/saleor,laosunhust/saleor,avorio/saleor,tfroehlich82/saleor,Drekscott/Motlaesaleor,arth-co/saleor,car3oon/saleor,rchav/vinerack,itbabu/saleor,spartonia/saleor,arth-co/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,taedori81/saleor,Drekscott/Motlaesaleor,josesanch/saleor,maferelo/saleor,taedori81/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,dashmug/saleor,UITools/saleor,laosunhust/saleor,paweltin/saleor,taedori81/saleor,mociepka/saleor,mociepka/saleor,jreigel/saleor,dashmug/saleor,tfroehlich82/saleor,paweltin/saleor,KenMutemi/saleor,maferelo/saleor,spartonia/saleor,taedori81/saleor,jreigel/saleor,avorio/saleor,avorio/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,Drekscott/Motlaesaleor,car3oon/saleor,itbabu/saleor,arth-co/saleor,rodrigozn/CW-Shop,UITools/saleor,mociepka/saleor,KenMutemi/saleor,KenMutemi/saleor,UITools/saleor,rchav/vinerack,laosunhust/saleor,spartonia/saleor,rodrigozn/CW-Shop,josesanch/saleor,tfroehlich82/saleor,dashmug/saleor,rchav/vinerack,avorio/saleor,josesanch/saleor,arth-co/saleor,paweltin/saleor,Drekscott/Motlaesaleor,spartonia/saleor,rodrigozn/CW-Shop,laosunhust/saleor,UITools/saleor,maferelo/saleor,paweltin/saleor
--- +++ @@ -1,17 +1,14 @@ -from django.core.exceptions import ObjectDoesNotExist - - def get_attributes_display(variant, attributes): display = {} for attribute in attributes: value = variant.get_attribute(attribute.pk) if value: - try: - choice = attribute.values.get(pk=value) - except ObjectDoesNotExist: - pass - except ValueError: + choices = attribute.values.all() + if choices: + for choice in attribute.values.all(): + if choice.pk == value: + display[attribute.pk] = choice + break + else: display[attribute.pk] = value - else: - display[attribute.pk] = choice return display
4e438122b5715f6a8765f50173c1dca1e18c6f8f
tests/__init__.py
tests/__init__.py
from __future__ import unicode_literals import gc import platform import cffi cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect()
from __future__ import unicode_literals import gc import platform import cffi # Import the module so that ffi.verify() is run before cffi.verifier is used import spotify # noqa cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect()
Make specific test files runnable
tests: Make specific test files runnable
Python
apache-2.0
jodal/pyspotify,jodal/pyspotify,felix1m/pyspotify,mopidy/pyspotify,kotamat/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify
--- +++ @@ -4,6 +4,9 @@ import platform import cffi + +# Import the module so that ffi.verify() is run before cffi.verifier is used +import spotify # noqa cffi.verifier.cleanup_tmpdir()
9d53af13a1f65370414632cd5a8172248c334ce2
tca/tca/settings/production.template.py
tca/tca/settings/production.template.py
""" A template for settings which should be used in production. In order for the settings to be truly useful, they need to be filled out with corresponding values. Use the template to create a ``production.py`` file and then create a symlink to it from a ``local_settings.py`` file, i.e.:: settings/local_settings.py -> settings/production.py """ #: Make sure to provide a real celery broker # BROKER_URL = 'amqp://guest:guest@localhost//' #: Make sure that GCM notifications are enabled TCA_ENABLE_GCM_NOTIFICATIONS = True #: In production HTTPS should be used # TCA_SCHEME = 'https' #: Domain name # TCA_DOMAIN_NAME = '' #: Make sure to provide an API key for GCM # TCA_GCM_API_KEY = "" #: Make sure to provide the credentials to the SMTP server (if any) # EMAIL_HOST_USER = '' # EMAIL_HOST_PASSWORD = ''
""" A template for settings which should be used in production. In order for the settings to be truly useful, they need to be filled out with corresponding values. Use the template to create a ``production.py`` file and then create a symlink to it from a ``local_settings.py`` file, i.e.:: settings/local_settings.py -> settings/production.py """ #: DEBUG should never be set to True in production DEBUG = False #: Make sure to provide a real celery broker # BROKER_URL = 'amqp://guest:guest@localhost//' #: Make sure that GCM notifications are enabled TCA_ENABLE_GCM_NOTIFICATIONS = True #: In production HTTPS should be used # TCA_SCHEME = 'https' #: Domain name # TCA_DOMAIN_NAME = '' #: Make sure to provide an API key for GCM # TCA_GCM_API_KEY = "" #: Make sure to provide the credentials to the SMTP server (if any) # EMAIL_HOST_USER = '' # EMAIL_HOST_PASSWORD = ''
Make DEBUG default to False in production settings
Make DEBUG default to False in production settings It is dangerous to keep the template file for production settings without explicitly specifying that DEBUG needs to be False.
Python
bsd-3-clause
mlalic/TumCampusAppBackend,mlalic/TumCampusAppBackend
--- +++ @@ -9,6 +9,9 @@ settings/local_settings.py -> settings/production.py """ + +#: DEBUG should never be set to True in production +DEBUG = False #: Make sure to provide a real celery broker # BROKER_URL = 'amqp://guest:guest@localhost//'
5fbf410e0042c82e524b3b08276b2d628d00b3c6
stickytape/prelude.py
stickytape/prelude.py
#!/usr/bin/env python import contextlib as __stickytape_contextlib @__stickytape_contextlib.contextmanager def __stickytape_temporary_dir(): import tempfile import shutil dir_path = tempfile.mkdtemp() try: yield dir_path finally: shutil.rmtree(dir_path) with __stickytape_temporary_dir() as __stickytape_working_dir: def __stickytape_write_module(path, contents): import os, os.path, errno def make_package(path): parts = path.split("/") partial_path = __stickytape_working_dir for part in parts: partial_path = os.path.join(partial_path, part) if not os.path.exists(partial_path): os.mkdir(partial_path) open(os.path.join(partial_path, "__init__.py"), "w").write("\n") make_package(os.path.dirname(path)) full_path = os.path.join(__stickytape_working_dir, path) with open(full_path, "w") as module_file: module_file.write(contents) import sys sys.path.insert(0, __stickytape_working_dir)
#!/usr/bin/env python import contextlib as __stickytape_contextlib @__stickytape_contextlib.contextmanager def __stickytape_temporary_dir(): import tempfile import shutil dir_path = tempfile.mkdtemp() try: yield dir_path finally: shutil.rmtree(dir_path) with __stickytape_temporary_dir() as __stickytape_working_dir: def __stickytape_write_module(path, contents): import os, os.path, errno def make_package(path): parts = path.split("/") partial_path = __stickytape_working_dir for part in parts: partial_path = os.path.join(partial_path, part) if not os.path.exists(partial_path): os.mkdir(partial_path) open(os.path.join(partial_path, "__init__.py"), "w").write("\n") make_package(os.path.dirname(path)) full_path = os.path.join(__stickytape_working_dir, path) with open(full_path, "w") as module_file: module_file.write(contents) import sys as __stickytape_sys __stickytape_sys.path.insert(0, __stickytape_working_dir)
Undo accidental global leakage of sys
Undo accidental global leakage of sys
Python
bsd-2-clause
mwilliamson/stickytape
--- +++ @@ -32,6 +32,6 @@ with open(full_path, "w") as module_file: module_file.write(contents) - import sys - sys.path.insert(0, __stickytape_working_dir) + import sys as __stickytape_sys + __stickytape_sys.path.insert(0, __stickytape_working_dir)
a253eac5e4d7319a7a31dc33c90ce60fe77dfe60
bin/commands/upstream.py
bin/commands/upstream.py
"""Get the current upstream branch.""" import re from subprocess import check_output def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA-Z0-9]+/([-_a-zA-Z0-9]+))(?:\s\[.*\])?$' match = re.match(regex, branch_info) upstream_info = '' if match is not None: upstream_info = match.group(1) if include_remote else match.group(2) return upstream_info
"""Get the current upstream branch.""" import re from subprocess import check_output, PIPE, Popen _MERGE_CONFIG = 'git config --local branch.{}.merge' _REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_name = check_output('git rev-parse --abbrev-ref HEAD'.split()).splitlines()[0] # get remote branch name proc = Popen(_MERGE_CONFIG.format(branch_name).split(), stdout=PIPE) upstream_info = proc.communicate()[0].strip() upstream_info = upstream_info.rsplit('/', 1)[-1] # optionally, get remote name if upstream_info and include_remote: remote_name = check_output(_REMOTE_CONFIG.format(branch_name).split()).strip() upstream_info = remote_name + '/' + upstream_info return upstream_info
Refactor how remote info is retrieved
Refactor how remote info is retrieved The old way of retrieving remote information was to parse `git status`. This was brittle and lazy. Now the config values storing the remote information are used.
Python
mit
Brickstertwo/git-commands
--- +++ @@ -1,18 +1,24 @@ """Get the current upstream branch.""" import re -from subprocess import check_output +from subprocess import check_output, PIPE, Popen +_MERGE_CONFIG = 'git config --local branch.{}.merge' +_REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" - branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] - regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA-Z0-9]+/([-_a-zA-Z0-9]+))(?:\s\[.*\])?$' - match = re.match(regex, branch_info) + branch_name = check_output('git rev-parse --abbrev-ref HEAD'.split()).splitlines()[0] - upstream_info = '' - if match is not None: - upstream_info = match.group(1) if include_remote else match.group(2) + # get remote branch name + proc = Popen(_MERGE_CONFIG.format(branch_name).split(), stdout=PIPE) + upstream_info = proc.communicate()[0].strip() + upstream_info = upstream_info.rsplit('/', 1)[-1] + + # optionally, get remote name + if upstream_info and include_remote: + remote_name = check_output(_REMOTE_CONFIG.format(branch_name).split()).strip() + upstream_info = remote_name + '/' + upstream_info return upstream_info
eba49ba765f0ff64d7415ad84116f7ea0781ad38
tests/integration/integration/runner.py
tests/integration/integration/runner.py
import os import subprocess def load_variables_from_env(prefix="XII_INTEGRATION_"): length = len(prefix) vars = {} for var in filter(lambda x: x.startswith(prefix), os.environ): vars[var[length:]] = os.environ[var] return vars def run_xii(deffile, cmd, variables={}, gargs="", cargs=""): xii_env = os.environ.copy() for key, value in variables.items(): print("=> XII_" + key + " defined") xii_env["XII_" + key] = value call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs] print("calling `{}`".format(" ".join(call))) process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env) for line in process.stdout: print("> " + line.rstrip(os.linesep)) if process.returncode != 0: raise RuntimeError("running xii failed")
import os import subprocess def load_variables_from_env(prefix="XII_INTEGRATION_"): length = len(prefix) vars = {} for var in filter(lambda x: x.startswith(prefix), os.environ): vars[var[length:]] = os.environ[var] return vars def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None): xii_env = os.environ.copy() for key, value in variables.items(): print("=> XII_" + key + " defined") xii_env["XII_" + key] = value call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs] print("calling `{}`".format(" ".join(call))) process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env) for line in process.stdout: print("> " + line.rstrip(os.linesep)) if process.returncode != 0: raise RuntimeError("running xii failed")
Make cargs and gargs truly optional
Make cargs and gargs truly optional
Python
apache-2.0
xii/xii,xii/xii
--- +++ @@ -10,7 +10,7 @@ return vars -def run_xii(deffile, cmd, variables={}, gargs="", cargs=""): +def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None): xii_env = os.environ.copy()
88a04efd1a7aa56a69b76b127908a5eca0c817bd
test/services/tv_remote/test_service.py
test/services/tv_remote/test_service.py
from roku import Roku from app.core.messaging import Receiver from app.core.servicemanager import ServiceManager from app.services.tv_remote.service import RokuScanner, RokuTV class TestRokuScanner(object): @classmethod def setup_class(cls): cls.service_manager = ServiceManager(None) cls.service_manager.start_services(["messaging"]) @classmethod def teardown_class(cls): cls.service_manager.stop() def test_basic_discovery(self): roku1 = Roku("abc") scanner = RokuScanner("/devices", scan_interval=10) scanner.discover_devices = lambda: [roku1] scanner.get_device_id = lambda: "deviceid" scanner.start() receiver = Receiver("/devices") msg = receiver.receive() expected = { "deviceid": { "device_id": "deviceid", "device_command_queue": "devices/tv/command", "device_commands": RokuTV(None, None).read_commands() } } assert msg == expected
import os from roku import Roku from app.core.messaging import Receiver from app.core.servicemanager import ServiceManager from app.services.tv_remote.service import RokuScanner, RokuTV class TestRokuScanner(object): @classmethod def setup_class(cls): os.environ["USE_FAKE_REDIS"] = "TRUE" cls.service_manager = ServiceManager(None) cls.service_manager.start_services(["messaging"]) @classmethod def teardown_class(cls): del os.environ["USE_FAKE_REDIS"] cls.service_manager.stop() def test_basic_discovery(self): roku1 = Roku("abc") scanner = RokuScanner("/devices", scan_interval=10) scanner.discover_devices = lambda: [roku1] scanner.get_device_id = lambda: "deviceid" scanner.start() receiver = Receiver("/devices") msg = receiver.receive() expected = { "deviceid": { "device_id": "deviceid", "device_command_queue": "devices/tv/command", "device_commands": RokuTV(None, None).read_commands() } } assert msg == expected
Use Fake redis for tests.
Use Fake redis for tests.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
--- +++ @@ -1,3 +1,5 @@ +import os + from roku import Roku from app.core.messaging import Receiver @@ -8,11 +10,13 @@ class TestRokuScanner(object): @classmethod def setup_class(cls): + os.environ["USE_FAKE_REDIS"] = "TRUE" cls.service_manager = ServiceManager(None) cls.service_manager.start_services(["messaging"]) @classmethod def teardown_class(cls): + del os.environ["USE_FAKE_REDIS"] cls.service_manager.stop() def test_basic_discovery(self):
c4e791ea6175fbefce0ef0671051936a27fc9684
tests/vec_test.py
tests/vec_test.py
"""Tests for vectors.""" from sympy import sympify from drudge import Vec def test_vecs_has_basic_properties(): """Tests the basic properties of vector instances.""" base = Vec('v') v_ab = Vec('v', indices=['a', 'b']) v_ab_1 = base['a', 'b'] v_ab_2 = (base['a'])['b'] indices_ref = (sympify('a'), sympify('b')) hash_ref = hash(v_ab) str_ref = 'v[a, b]' repr_ref = "Vec('v', (a, b))" for i in [v_ab, v_ab_1, v_ab_2]: assert i.label == base.label assert i.base == base assert i.indices == indices_ref assert hash(i) == hash_ref assert i == v_ab assert str(i) == str_ref assert repr(i) == repr_ref
"""Tests for vectors.""" import pytest from sympy import sympify from drudge import Vec def test_vecs_has_basic_properties(): """Tests the basic properties of vector instances.""" base = Vec('v') v_ab = Vec('v', indices=['a', 'b']) v_ab_1 = base['a', 'b'] v_ab_2 = (base['a'])['b'] indices_ref = (sympify('a'), sympify('b')) hash_ref = hash(v_ab) str_ref = 'v[a, b]' repr_ref = "Vec('v', (a, b))" for i in [v_ab, v_ab_1, v_ab_2]: assert i.label == base.label assert i.base == base assert i.indices == indices_ref assert hash(i) == hash_ref assert i == v_ab assert str(i) == str_ref assert repr(i) == repr_ref # Vectors should not be sympified. with pytest.raises(TypeError): sympify(i)
Add tests for disabled sympification of vectors
Add tests for disabled sympification of vectors
Python
mit
tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge
--- +++ @@ -1,4 +1,6 @@ """Tests for vectors.""" + +import pytest from sympy import sympify @@ -26,3 +28,7 @@ assert i == v_ab assert str(i) == str_ref assert repr(i) == repr_ref + + # Vectors should not be sympified. + with pytest.raises(TypeError): + sympify(i)
2263ea4ec0322e09db92ae368aa219c4e34125d3
src/foremast/__init__.py
src/foremast/__init__.py
"""Tools for creating infrastructure and Spinnaker Applications."""
"""Tools for creating infrastructure and Spinnaker Applications.""" from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils, consts, destroyer, exceptions, runner)
Bring modules into package level
fix: Bring modules into package level
Python
apache-2.0
gogoair/foremast,gogoair/foremast
--- +++ @@ -1 +1,3 @@ """Tools for creating infrastructure and Spinnaker Applications.""" +from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils, + consts, destroyer, exceptions, runner)
50e92d3394cfaf1035c6dc29563ce45437efb9c9
wagtailstartproject/project_template/tests/test_settings.py
wagtailstartproject/project_template/tests/test_settings.py
import logging from {{ project_name }}.settings import * # noqa logging.disable(logging.CRITICAL) DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '{{ project_name }}', 'USER': 'postgres' }, } # Add middleware to add a meta tag with the response status code for Selenium MIDDLEWARE += [ 'tests.middleware.PageStatusMiddleware' ] # Fixture location FIXTURE_DIRS = ['tests/fixtures/'] # Set the default cache to be a dummy cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # Use dummy backend for safety and performance EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
import logging from {{ project_name }}.settings import * # noqa logging.disable(logging.CRITICAL) DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '{{ project_name }}', 'USER': 'postgres' }, } # Add middleware to add a meta tag with the response status code for Selenium MIDDLEWARE += [ 'tests.middleware.PageStatusMiddleware' ] # Fixture location FIXTURE_DIRS = ['tests/fixtures/'] # Set the default cache to be a dummy cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # Use dummy backend for safety and performance EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend' # Disable the automatic indexing (sigals) of your search backend # In WAGTAILSEARCH_BACKENDS set AUTO_UPDATE for each backend to False
Add comment to test settings to advice disabling search indexing
Add comment to test settings to advice disabling search indexing
Python
mit
leukeleu/wagtail-startproject,leukeleu/wagtail-startproject
--- +++ @@ -31,3 +31,6 @@ # Use dummy backend for safety and performance EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend' + +# Disable the automatic indexing (sigals) of your search backend +# In WAGTAILSEARCH_BACKENDS set AUTO_UPDATE for each backend to False
d6c5f3f8ae7a830b49ebb87fdda4b0b1d0bbf916
easy_thumbnails/migrations/__init__.py
easy_thumbnails/migrations/__init__.py
""" Django migrations for easy_thumbnails app This package does not contain South migrations. South migrations can be found in the ``south_migrations`` package. """ SOUTH_ERROR_MESSAGE = """\n For South support, customize the SOUTH_MIGRATION_MODULES setting like so: SOUTH_MIGRATION_MODULES = { 'easy_thumbnails': 'easy_thumbnails.south_migrations', } """ # Ensure the user is not using Django 1.6 or below with South try: from django.db import migrations # noqa except ImportError: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE)
Raise error if migrations imported for old Django
Raise error if migrations imported for old Django
Python
bsd-3-clause
siovene/easy-thumbnails,Mactory/easy-thumbnails,sandow-digital/easy-thumbnails-cropman,jaddison/easy-thumbnails,SmileyChris/easy-thumbnails,sandow-digital/easy-thumbnails-cropman
--- +++ @@ -0,0 +1,21 @@ +""" +Django migrations for easy_thumbnails app + +This package does not contain South migrations. South migrations can be found +in the ``south_migrations`` package. +""" + +SOUTH_ERROR_MESSAGE = """\n +For South support, customize the SOUTH_MIGRATION_MODULES setting like so: + + SOUTH_MIGRATION_MODULES = { + 'easy_thumbnails': 'easy_thumbnails.south_migrations', + } +""" + +# Ensure the user is not using Django 1.6 or below with South +try: + from django.db import migrations # noqa +except ImportError: + from django.core.exceptions import ImproperlyConfigured + raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE)
bbe7431736afeae575fb3430437d3a0000d4b653
collectd_haproxy/__init__.py
collectd_haproxy/__init__.py
try: import collectd collectd.register_config collectd_present = True except (ImportError, AttributeError): collectd_present = False from .plugin import HAProxyPlugin version_info = (1, 1, 1) __version__ = ".".join(map(str, version_info)) if collectd_present: HAProxyPlugin.register(collectd)
try: import collectd collectd.register_config # pragma: no cover collectd_present = True # pragma: no cover except (ImportError, AttributeError): collectd_present = False from .plugin import HAProxyPlugin version_info = (1, 1, 1) __version__ = ".".join(map(str, version_info)) if collectd_present: HAProxyPlugin.register(collectd) # pragma: no cover
Exclude init file from coverage reporting.
Exclude init file from coverage reporting.
Python
mit
wglass/collectd-haproxy
--- +++ @@ -1,7 +1,7 @@ try: import collectd - collectd.register_config - collectd_present = True + collectd.register_config # pragma: no cover + collectd_present = True # pragma: no cover except (ImportError, AttributeError): collectd_present = False @@ -13,4 +13,4 @@ if collectd_present: - HAProxyPlugin.register(collectd) + HAProxyPlugin.register(collectd) # pragma: no cover
d5f782fc7a8c7835af0d4d2810a923d218dea938
mplwidget.py
mplwidget.py
from PyQt4 import QtGui import matplotlib as mpl from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import matplotlib.mlab as mlab import matplotlib.gridspec as gridspec class MplCanvas(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def resizeEvent(self, event): FigureCanvas.resizeEvent(self, event) class MplWidget(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.canvas = MplCanvas() self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar(self.canvas, self)
from PyQt4 import QtGui,QtCore import matplotlib as mpl from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import matplotlib.mlab as mlab import matplotlib.gridspec as gridspec class MplCanvas(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def sizeHint(self): w, h = self.get_width_height() return QtCore.QSize(w,h) class MplWidget(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.canvas = MplCanvas() self.mpl_toolbar = NavigationToolbar(self.canvas, self) layout = QtGui.QVBoxLayout() self.setLayout(layout) layout.addWidget(self.canvas)
Expand figure when window is resized
Expand figure when window is resized
Python
apache-2.0
scholi/pyOmicron
--- +++ @@ -1,4 +1,4 @@ -from PyQt4 import QtGui +from PyQt4 import QtGui,QtCore import matplotlib as mpl from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar @@ -14,12 +14,15 @@ QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) - def resizeEvent(self, event): - FigureCanvas.resizeEvent(self, event) + def sizeHint(self): + w, h = self.get_width_height() + return QtCore.QSize(w,h) class MplWidget(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.canvas = MplCanvas() - self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar(self.canvas, self) + layout = QtGui.QVBoxLayout() + self.setLayout(layout) + layout.addWidget(self.canvas)
6510705d47a035279e1aa0cb6ce52f79935b2d10
bin/monitor/check_participant_status.py
bin/monitor/check_participant_status.py
import emission.core.get_database as edb for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"}) last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1)) last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, last trip = {last_trip_time}")
import emission.core.get_database as edb for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"}) first_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", 1).limit(1)) first_trip_time = first_trip[0]["data"]["end_fmt_time"] if len(first_trip) > 0 else None last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1)) last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, first trip = {first_trip_time}, last trip = {last_trip_time}")
Add first trip details as well
Add first trip details as well
Python
bsd-3-clause
e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server
--- +++ @@ -3,6 +3,8 @@ for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"}) + first_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", 1).limit(1)) + first_trip_time = first_trip[0]["data"]["end_fmt_time"] if len(first_trip) > 0 else None last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1)) last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None - print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, last trip = {last_trip_time}") + print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, first trip = {first_trip_time}, last trip = {last_trip_time}")
1dcbaeca1d487e2eb773580f66600389ffbb1e34
test/integration/ggrc/converters/test_import_issues.py
test/integration/ggrc/converters/test_import_issues.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # pylint: disable=maybe-no-member, invalid-name """Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "user@example.com"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) )
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # pylint: disable=maybe-no-member, invalid-name """Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from ggrc.converters import errors from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "user@example.com"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) def test_audit_change(self): audit = factories.AuditFactory() issue = factories.IssueFactory() response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", issue.slug), ("audit", audit.slug), ])) self._check_csv_response(response, { "Issue": { "row_warnings": { errors.UNMODIFIABLE_COLUMN.format(line=3, column_name="Audit") } } })
Add tests for audit changes on issue import
Add tests for audit changes on issue import
Python
apache-2.0
AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core
--- +++ @@ -8,6 +8,7 @@ from collections import OrderedDict from ggrc import models +from ggrc.converters import errors from integration.ggrc.models import factories from integration.ggrc import TestCase @@ -40,3 +41,19 @@ "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) + + def test_audit_change(self): + audit = factories.AuditFactory() + issue = factories.IssueFactory() + response = self.import_data(OrderedDict([ + ("object_type", "Issue"), + ("Code*", issue.slug), + ("audit", audit.slug), + ])) + self._check_csv_response(response, { + "Issue": { + "row_warnings": { + errors.UNMODIFIABLE_COLUMN.format(line=3, column_name="Audit") + } + } + })
4ad8b1412be2da07e4713b54741aa22064ff33c5
gen_settings.py
gen_settings.py
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='undefined'): global settings_template if '__dirname' in fonts or '__dirname' in input_plugins: settings_template = "var path = require('path');\n" + settings_template open(settings,'w').write(settings_template % (fonts,input_plugins)) if __name__ == '__main__': settings_dict = {} # settings for fonts and input plugins settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='undefined'): global settings_template if '__dirname' in fonts or '__dirname' in input_plugins: settings_template = "var path = require('path');\n" + settings_template open(settings,'w').write(settings_template % (fonts,input_plugins)) if __name__ == '__main__': settings_dict = {} # settings for fonts and input plugins if os.environ.has_key('MAPNIK_INPUT_PLUGINS_DIRECTORY'): settings_dict['input_plugins'] = os.environ['MAPNIK_INPUT_PLUGINS_DIRECTORY'] else: settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() if os.environ.has_key('MAPNIK_FONT_DIRECTORY'): settings_dict['fonts'] = os.environ['MAPNIK_FONT_DIRECTORY'] else: settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows"
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows" This reverts commit d87c71142ba7bcc0d99d84886f3534dea7617b0c.
Python
bsd-3-clause
mojodna/node-mapnik,mapnik/node-mapnik,mapnik/node-mapnik,Uli1/node-mapnik,tomhughes/node-mapnik,stefanklug/node-mapnik,mapnik/node-mapnik,mojodna/node-mapnik,langateam/node-mapnik,Uli1/node-mapnik,stefanklug/node-mapnik,tomhughes/node-mapnik,stefanklug/node-mapnik,gravitystorm/node-mapnik,Uli1/node-mapnik,CartoDB/node-mapnik,MaxSem/node-mapnik,mapnik/node-mapnik,stefanklug/node-mapnik,gravitystorm/node-mapnik,tomhughes/node-mapnik,tomhughes/node-mapnik,langateam/node-mapnik,gravitystorm/node-mapnik,mojodna/node-mapnik,langateam/node-mapnik,MaxSem/node-mapnik,Uli1/node-mapnik,CartoDB/node-mapnik,MaxSem/node-mapnik,gravitystorm/node-mapnik,langateam/node-mapnik,mojodna/node-mapnik,MaxSem/node-mapnik,mapnik/node-mapnik,langateam/node-mapnik,CartoDB/node-mapnik,CartoDB/node-mapnik,CartoDB/node-mapnik,tomhughes/node-mapnik
--- +++ @@ -21,8 +21,14 @@ settings_dict = {} # settings for fonts and input plugins - settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() + if os.environ.has_key('MAPNIK_INPUT_PLUGINS_DIRECTORY'): + settings_dict['input_plugins'] = os.environ['MAPNIK_INPUT_PLUGINS_DIRECTORY'] + else: + settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() - settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() + if os.environ.has_key('MAPNIK_FONT_DIRECTORY'): + settings_dict['fonts'] = os.environ['MAPNIK_FONT_DIRECTORY'] + else: + settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
6bc5fe6c2ef7cc06436b81150639cf7039b9deeb
flocker/node/functional/test_script.py
flocker/node/functional/test_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from os import getuid from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version__ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") _require_root = skipUnless(getuid() == 0, "Root required to run these tests.") class FlockerChangeStateTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed def test_version(self): """ ``flocker-changestate`` is a command available on the system path """ result = check_output([b"flocker-changestate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,)) class FlockerReportStateTests(TestCase): """Tests for ``flocker-reportstate``.""" @_require_installed def test_version(self): """ ``flocker-reportstate`` is a command available on the system path """ result = check_output([b"flocker-reportstate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version__ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") class FlockerChangeStateTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed def test_version(self): """ ``flocker-changestate`` is a command available on the system path """ result = check_output([b"flocker-changestate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,)) class FlockerReportStateTests(TestCase): """Tests for ``flocker-reportstate``.""" @_require_installed def test_version(self): """ ``flocker-reportstate`` is a command available on the system path """ result = check_output([b"flocker-reportstate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,))
Address review comment: Remove another root check.
Address review comment: Remove another root check.
Python
apache-2.0
mbrukman/flocker,moypray/flocker,hackday-profilers/flocker,adamtheturtle/flocker,moypray/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,moypray/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,achanda/flocker,AndyHuu/flocker,hackday-profilers/flocker,AndyHuu/flocker,1d4Nf6/flocker,LaynePeng/flocker,LaynePeng/flocker,mbrukman/flocker,agonzalezro/flocker,w4ngyi/flocker,lukemarsden/flocker,achanda/flocker,Azulinho/flocker,jml/flocker,wallnerryan/flocker-profiles,achanda/flocker,jml/flocker,runcom/flocker,lukemarsden/flocker,1d4Nf6/flocker,agonzalezro/flocker,runcom/flocker,lukemarsden/flocker,1d4Nf6/flocker,jml/flocker,mbrukman/flocker,runcom/flocker,AndyHuu/flocker,hackday-profilers/flocker,Azulinho/flocker,agonzalezro/flocker,LaynePeng/flocker,adamtheturtle/flocker,w4ngyi/flocker,w4ngyi/flocker
--- +++ @@ -4,7 +4,6 @@ Functional tests for the ``flocker-changestate`` command line tool. """ -from os import getuid from subprocess import check_output from unittest import skipUnless @@ -16,8 +15,6 @@ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") -_require_root = skipUnless(getuid() == 0, - "Root required to run these tests.") class FlockerChangeStateTests(TestCase):
8aeaac1afa501ddc2a7b7992ceeb42a3f409bac0
tests/test_default.py
tests/test_default.py
import re def test_tmp_file_is_gone(host): tmpfile = '/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress' f = host.file(tmpfile) assert not f.exists def test_command_line_tools_dir(host): f = host.file('/Library/Developer/CommandLineTools') assert f.exists assert f.is_directory assert f.user == 'root' assert f.group == 'admin' assert f.mode == 0o755 def test_clt_package_metadata(host): c = host.command('pkgutil --pkg-info=com.apple.pkg.CLTools_Executables') assert c.rc == 0 def test_git_is_useable(host): c = host.command('/usr/bin/git --version') assert c.rc == 0 assert re.match('^git version \d+(.\d+)* \(Apple Git-\d+\)$', c.stdout)
import re def test_tmp_file_is_gone(host): tmpfile = '/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress' f = host.file(tmpfile) assert not f.exists def test_command_line_tools_dir(host): f = host.file('/Library/Developer/CommandLineTools') assert f.exists assert f.is_directory assert f.user == 'root' assert f.group == 'admin' assert f.mode == 0o755 def test_clt_package_metadata(host): c = host.command('pkgutil --pkg-info=com.apple.pkg.CLTools_Executables') assert c.rc == 0 def test_git_is_useable(host): c = host.command('/usr/bin/git --version') assert c.rc == 0 assert re.match('^git version \d+(.\d+)* \(Apple Git-\d+(\.\d+)*\)$', c.stdout)
Fix failing test w/ incomplete regex
Fix failing test w/ incomplete regex
Python
mit
elliotweiser/ansible-osx-command-line-tools,elliotweiser/ansible-osx-command-line-tools
--- +++ @@ -24,4 +24,4 @@ def test_git_is_useable(host): c = host.command('/usr/bin/git --version') assert c.rc == 0 - assert re.match('^git version \d+(.\d+)* \(Apple Git-\d+\)$', c.stdout) + assert re.match('^git version \d+(.\d+)* \(Apple Git-\d+(\.\d+)*\)$', c.stdout)
d8fa685640f674b6f22dacc45c5a9b0152115fce
paystackapi/tests/test_tcontrol.py
paystackapi/tests/test_tcontrol.py
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.tcontrol import TransferControl class TestTransfer(BaseTestCase): @httpretty.activate def test_check_balance(self): """Method defined to test check_balance.""" httpretty.register_uri( httpretty.GET, self.endpoint_url("/balance"), content_type='text/json', body='{"status": true, "message": "Balances retrieved"}', status=201, ) response = TransferControl.check_balance() self.assertTrue(response['status']) @httpretty.activate def test_resend_otp(self): """Method defined to test resend_otp.""" httpretty.register_uri( httpretty.POST, self.endpoint_url("/transfer/resend_otp"), content_type='text/json', body='{"status": true, "message": "OTP has been resent"}', status=201, ) response = TransferControl.resend_otp( transfer_code="TRF_vsyqdmlzble3uii", reason="Just do it." ) self.assertTrue(response['status'])
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.tcontrol import TransferControl class TestTransfer(BaseTestCase): @httpretty.activate def test_check_balance(self): """Method defined to test check_balance.""" httpretty.register_uri( httpretty.GET, self.endpoint_url("/balance"), content_type='text/json', body='{"status": true, "message": "Balances retrieved"}', status=201, ) response = TransferControl.check_balance() self.assertTrue(response['status']) @httpretty.activate def test_resend_otp(self): """Method defined to test resend_otp.""" httpretty.register_uri( httpretty.POST, self.endpoint_url("/transfer/resend_otp"), content_type='text/json', body='{"status": true, "message": "OTP has been resent"}', status=201, ) response = TransferControl.resend_otp( transfer_code="TRF_vsyqdmlzble3uii", reason="Just do it." ) self.assertTrue(response['status']) @httpretty.activate def test_disable_otp(self): """Method defined to test disable_otp.""" httpretty.register_uri( httpretty.POST, self.endpoint_url("/transfer/disable_otp"), content_type='text/json', body='{"status": true,\ "message": "OTP has been sent to mobile number ending with 4321"}', status=201, ) response = TransferControl.disable_otp() self.assertTrue(response['status'])
Add test for transfer control disable otp
Add test for transfer control disable otp
Python
mit
andela-sjames/paystack-python
--- +++ @@ -36,4 +36,18 @@ reason="Just do it." ) self.assertTrue(response['status']) + + @httpretty.activate + def test_disable_otp(self): + """Method defined to test disable_otp.""" + httpretty.register_uri( + httpretty.POST, + self.endpoint_url("/transfer/disable_otp"), + content_type='text/json', + body='{"status": true,\ + "message": "OTP has been sent to mobile number ending with 4321"}', + status=201, + ) + response = TransferControl.disable_otp() + self.assertTrue(response['status'])
628e3cb67fefd32382614af6816d380d36c0b32f
froide/publicbody/migrations/0007_auto_20171224_0744.py
froide/publicbody/migrations/0007_auto_20171224_0744.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-24 06:44 from __future__ import unicode_literals from django.db import migrations def create_classifications(apps, schema_editor): from ..models import Classification, PublicBody # Use treebeard API # Classification = apps.get_model('publicbody', 'Classification') # PublicBody = apps.get_model('publicbody', 'PublicBody') classifications = {} for pb in PublicBody.objects.exclude(classification_slug=''): if pb.classification_slug in classifications: pb.classification = classifications[pb.classification_slug] else: root = Classification.add_root( name=pb.classification_name, slug=pb.classification_slug ) pb.classification = root classifications[pb.classification_slug] = root pb.save() class Migration(migrations.Migration): dependencies = [ ('publicbody', '0006_auto_20171224_0732'), ] operations = [ migrations.RunPython(create_classifications), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-24 06:44 from __future__ import unicode_literals from django.db import migrations def create_classifications(apps, schema_editor): from ..models import Classification # Use treebeard API # Classification = apps.get_model('publicbody', 'Classification') PublicBody = apps.get_model('publicbody', 'PublicBody') classifications = {} for pb in PublicBody.objects.exclude(classification_slug=''): if pb.classification_slug in classifications: pb.classification = classifications[pb.classification_slug] else: root = Classification.add_root( name=pb.classification_name, slug=pb.classification_slug ) pb.classification = root classifications[pb.classification_slug] = root pb.save() class Migration(migrations.Migration): dependencies = [ ('publicbody', '0006_auto_20171224_0732'), ] operations = [ migrations.RunPython(create_classifications), ]
Use historic PublicBody in data migration
Use historic PublicBody in data migration
Python
mit
stefanw/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide
--- +++ @@ -6,9 +6,9 @@ def create_classifications(apps, schema_editor): - from ..models import Classification, PublicBody # Use treebeard API + from ..models import Classification # Use treebeard API # Classification = apps.get_model('publicbody', 'Classification') - # PublicBody = apps.get_model('publicbody', 'PublicBody') + PublicBody = apps.get_model('publicbody', 'PublicBody') classifications = {} for pb in PublicBody.objects.exclude(classification_slug=''): if pb.classification_slug in classifications:
50d35de34bf6c2f90d0b8a4595c6d1459355d8fa
zakopane/__init__.py
zakopane/__init__.py
version = (0, 0, 1) DEBUG = False from zakopane.file import SumFile
version = (0, 0, 1) DEBUG = False import os from zakopane.file import SumFile, newSumFile from zakopane.hash import readHashLine, doHashFile, formatHashLine def main(): if "POSIX_ME_HARDER" in os.environ: raise OSError("POSIXing you harder.") return 0
Expand package and module extents.
Expand package and module extents.
Python
bsd-3-clause
j39m/zakopane
--- +++ @@ -2,4 +2,13 @@ DEBUG = False -from zakopane.file import SumFile + +import os +from zakopane.file import SumFile, newSumFile +from zakopane.hash import readHashLine, doHashFile, formatHashLine + +def main(): + if "POSIX_ME_HARDER" in os.environ: + raise OSError("POSIXing you harder.") + + return 0
37c0eea76d6aba1180f2a3eae90d7f38566bfc3f
packages/mono-master.py
packages/mono-master.py
import os class MonoMasterPackage(Package): def __init__(self): Package.__init__(self, 'mono', os.getenv('MONO_VERSION'), sources = ['git://github.com/mono/mono.git'], revision = os.getenv('MONO_BUILD_REVISION'), configure_flags = [ '--enable-nls=no', '--prefix=' + Package.profile.prefix, '--with-ikvm=yes', '--with-moonlight=no' ] ) if Package.profile.name == 'darwin': if not Package.profile.m64: self.configure_flags.extend([ # fix build on lion, it uses 64-bit host even with -m32 '--build=i386-apple-darwin11.2.0', ]) self.configure_flags.extend([ '--enable-loadedllvm' ]) self.sources.extend ([ # Fixes up pkg-config usage on the Mac 'patches/mcs-pkgconfig.patch' ]) self.configure = expand_macros ('CFLAGS="%{env.CFLAGS} -O2" ./autogen.sh', Package.profile) def prep (self): Package.prep (self) if Package.profile.name == 'darwin': for p in range (1, len (self.sources)): self.sh ('patch -p1 < "%{sources[' + str (p) + ']}"') MonoMasterPackage()
import os class MonoMasterPackage(Package): def __init__(self): Package.__init__(self, 'mono', os.getenv('MONO_VERSION'), sources = [os.getenv('MONO_REPOSITORY') or 'git://github.com/mono/mono.git'], revision = os.getenv('MONO_BUILD_REVISION'), configure_flags = [ '--enable-nls=no', '--prefix=' + Package.profile.prefix, '--with-ikvm=yes', '--with-moonlight=no' ] ) if Package.profile.name == 'darwin': if not Package.profile.m64: self.configure_flags.extend([ # fix build on lion, it uses 64-bit host even with -m32 '--build=i386-apple-darwin11.2.0', ]) self.configure_flags.extend([ '--enable-loadedllvm' ]) self.sources.extend ([ # Fixes up pkg-config usage on the Mac 'patches/mcs-pkgconfig.patch' ]) self.configure = expand_macros ('CFLAGS="%{env.CFLAGS} -O2" ./autogen.sh', Package.profile) def prep (self): Package.prep (self) if Package.profile.name == 'darwin': for p in range (1, len (self.sources)): self.sh ('patch -p1 < "%{sources[' + str (p) + ']}"') MonoMasterPackage()
Use MONO_REPOSITORY to set the repo URL
Use MONO_REPOSITORY to set the repo URL
Python
mit
mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild
--- +++ @@ -4,7 +4,7 @@ def __init__(self): Package.__init__(self, 'mono', os.getenv('MONO_VERSION'), - sources = ['git://github.com/mono/mono.git'], + sources = [os.getenv('MONO_REPOSITORY') or 'git://github.com/mono/mono.git'], revision = os.getenv('MONO_BUILD_REVISION'), configure_flags = [ '--enable-nls=no',
ab88748dcd5f48dce753655e0e0802a8b4d7d8b8
pages/search_indexes.py
pages/search_indexes.py
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(model_attr='title') publication_date = DateTimeField(model_attr='publication_date') def get_queryset(self): """Used when the entire index for model is updated.""" return Page.objects.published() site.register(Page, PageIndex)
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(model_attr='title') url = CharField(model_attr='get_absolute_url') publication_date = DateTimeField(model_attr='publication_date') def get_queryset(self): """Used when the entire index for model is updated.""" return Page.objects.published() site.register(Page, PageIndex)
Add a url attribute to the SearchIndex for pages.
Add a url attribute to the SearchIndex for pages. This is useful when displaying a list of search results because we can create a link to the result without having to hit the database for every object in the result list.
Python
bsd-3-clause
remik/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,batiste/django-page-cms
--- +++ @@ -9,6 +9,7 @@ """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(model_attr='title') + url = CharField(model_attr='get_absolute_url') publication_date = DateTimeField(model_attr='publication_date') def get_queryset(self):
bbbeca09a978d26fa2638c21802d9a27e1159b59
massa/api.py
massa/api.py
# -*- coding: utf-8 -*- from flask import Blueprint from flask.views import MethodView class MeasurementList(MethodView): def get(self): return 'GET: measurement list' class MeasurementItem(MethodView): def get(self, id): return 'GET: measurement item with ID %s' % id bp = Blueprint('api', __name__) bp.add_url_rule( '/measurements/', view_func=MeasurementList.as_view('measurement_list'), methods=['GET'] ) bp.add_url_rule( '/measurements/<id>', view_func=MeasurementItem.as_view('measurement_item'), methods=['GET'] )
# -*- coding: utf-8 -*- from flask import Blueprint, jsonify, g from flask.views import MethodView class MeasurementList(MethodView): def get(self): service = g.sl('measurement_service') return jsonify(items=service.find_all()) class MeasurementItem(MethodView): def get(self, id): service = g.sl('measurement_service') return jsonify(service.find(id)) bp = Blueprint('api', __name__) bp.add_url_rule( '/measurements/', view_func=MeasurementList.as_view('measurement_list'), methods=['GET'] ) bp.add_url_rule( '/measurements/<id>', view_func=MeasurementItem.as_view('measurement_item'), methods=['GET'] )
Replace dummy response with measurements.
Replace dummy response with measurements.
Python
mit
jaapverloop/massa
--- +++ @@ -1,16 +1,19 @@ # -*- coding: utf-8 -*- -from flask import Blueprint +from flask import Blueprint, jsonify, g from flask.views import MethodView class MeasurementList(MethodView): def get(self): - return 'GET: measurement list' + service = g.sl('measurement_service') + return jsonify(items=service.find_all()) + class MeasurementItem(MethodView): def get(self, id): - return 'GET: measurement item with ID %s' % id + service = g.sl('measurement_service') + return jsonify(service.find(id)) bp = Blueprint('api', __name__)
91c6c00a16252b2a43a1017ee17b7f6f0302e4be
controlbeast/__init__.py
controlbeast/__init__.py
# -*- coding: utf-8 -*- """ controlbeast ~~~~~~~~~~~~ :copyright: Copyright 2013 by the ControlBeast team, see AUTHORS. :license: ISC, see LICENSE for details. """ VERSION = (0, 1, 0, 'alpha', 0) COPYRIGHT = ('2013', 'the ControlBeast team') def get_version(*args, **kwargs): """ Returns PEP 386 compliant version number for the Pytain package """ from controlbeast.utils.version import get_version return get_version(*args, **kwargs)
# -*- coding: utf-8 -*- """ controlbeast ~~~~~~~~~~~~ :copyright: Copyright 2013 by the ControlBeast team, see AUTHORS. :license: ISC, see LICENSE for details. """ VERSION = (0, 1, 0, 'alpha', 0) COPYRIGHT = ('2013', 'the ControlBeast team') DEFAULTS = { 'scm': 'Git' } def get_conf(key): """ Get a global configuration value by its key :param key: string identifying the requested configuration value :returns the requested configuration value or None """ if key in DEFAULTS: return DEFAULTS[key] else: return None def get_version(*args, **kwargs): """ Returns PEP 386 compliant version number for the Pytain package """ from controlbeast.utils.version import get_version return get_version(*args, **kwargs)
Implement simple mechanism for configuration handling
Implement simple mechanism for configuration handling
Python
isc
daemotron/controlbeast,daemotron/controlbeast
--- +++ @@ -10,6 +10,24 @@ VERSION = (0, 1, 0, 'alpha', 0) COPYRIGHT = ('2013', 'the ControlBeast team') +DEFAULTS = { + 'scm': 'Git' +} + + +def get_conf(key): + """ + Get a global configuration value by its key + + :param key: string identifying the requested configuration value + :returns the requested configuration value or None + """ + if key in DEFAULTS: + return DEFAULTS[key] + else: + return None + + def get_version(*args, **kwargs): """ Returns PEP 386 compliant version number for the Pytain package
6f28e097fb292493c8313854ecc468b491aa562a
getyourdata/getyourdata/dev_settings.py
getyourdata/getyourdata/dev_settings.py
from .settings import * import os DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'getyourdatadevdb', 'USER': 'getyourdatadevuser', 'PASSWORD': 'getyourdatadevpwd', 'HOST': 'localhost', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } AUTH_PASSWORD_VALIDATORS = [] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' if TESTING: EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' os.environ["RECAPTCHA_TESTING"] = 'True' PIPELINE['PIPELINE_ENABLED'] = False STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
from .settings import * import os DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'getyourdatadevdb', 'USER': 'getyourdatadevuser', 'PASSWORD': 'getyourdatadevpwd', 'HOST': 'localhost', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } if TESTING: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } AUTH_PASSWORD_VALIDATORS = [] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' if TESTING: EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' os.environ["RECAPTCHA_TESTING"] = 'True' PIPELINE['PIPELINE_ENABLED'] = False STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
Enable in-memory cache backend for development environment, but not tests
Enable in-memory cache backend for development environment, but not tests
Python
mit
sakset/getyourdata,sakset/getyourdata,sakset/getyourdata,sakset/getyourdata
--- +++ @@ -17,9 +17,16 @@ CACHES = { 'default': { - 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } + +if TESTING: + CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', + } + } AUTH_PASSWORD_VALIDATORS = []
dfe43823c32cf6181ef873095c6cecd13664079d
Algorithmia/errors.py
Algorithmia/errors.py
class ApiError(Exception): '''General error from the Algorithmia API''' pass class ApiInternalError(ApiError): '''Error representing a server error, typically a 5xx status code''' pass class DataApiError(ApiError): '''Error returned from the Algorithmia data API''' pass
class ApiError(Exception): '''General error from the Algorithmia API''' pass class ApiInternalError(ApiError): '''Error representing a server error, typically a 5xx status code''' pass class DataApiError(ApiError): '''Error returned from the Algorithmia data API''' pass class AlgorithmException(ApiError): '''Base algorithm error exception''' def __init__(self, message, errorType=None): self.message = message self.errorType = errorType def __str__(self): return repr(self.message)
Add new Algorithm Exception class
Add new Algorithm Exception class
Python
mit
algorithmiaio/algorithmia-python
--- +++ @@ -10,3 +10,10 @@ '''Error returned from the Algorithmia data API''' pass +class AlgorithmException(ApiError): + '''Base algorithm error exception''' + def __init__(self, message, errorType=None): + self.message = message + self.errorType = errorType + def __str__(self): + return repr(self.message)
ec37dae820e49d816014c62f00711eaaeaf64597
transaction_hooks/test/settings_pg.py
transaction_hooks/test/settings_pg.py
import os from .settings import * # noqa DATABASES = { 'default': { 'ENGINE': 'transaction_hooks.backends.postgresql_psycopg2', 'NAME': 'dtc', }, } if 'DTC_PG_USERNAME' in os.environ: DATABASES['default'].update( { 'USER': os.environ['DTC_PG_USERNAME'], 'PASSWORD': '', 'HOST': 'localhost', } )
import os try: from psycopg2cffi import compat compat.register() except ImportError: pass from .settings import * # noqa DATABASES = { 'default': { 'ENGINE': 'transaction_hooks.backends.postgresql_psycopg2', 'NAME': 'dtc', }, } if 'DTC_PG_USERNAME' in os.environ: DATABASES['default'].update( { 'USER': os.environ['DTC_PG_USERNAME'], 'PASSWORD': '', 'HOST': 'localhost', } )
Enable postgresql CFFI compatability if available.
Enable postgresql CFFI compatability if available.
Python
bsd-3-clause
carljm/django-transaction-hooks
--- +++ @@ -1,4 +1,10 @@ import os + +try: + from psycopg2cffi import compat + compat.register() +except ImportError: + pass from .settings import * # noqa
fa7a96559b1eea8ee7c7c6ec48b5d01e4b3f1b05
bugle_project/configs/live/settings.py
bugle_project/configs/live/settings.py
from bugle_project.configs.settings import * FAYE_URL = 'http://bugle.fort:8001/faye' DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'bugle' DATABASE_USER = 'bugle' DATABASE_PASSWORD = 'bugle'
from bugle_project.configs.settings import * FAYE_URL = 'http://bugle.fort:8001/faye' DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'bugle' DATABASE_USER = 'bugle' DATABASE_PASSWORD = 'bugle' DATABASE_HOST = 'localhost'
Connect to DB on localhost
Connect to DB on localhost
Python
bsd-2-clause
devfort/bugle,devfort/bugle,devfort/bugle
--- +++ @@ -6,3 +6,4 @@ DATABASE_NAME = 'bugle' DATABASE_USER = 'bugle' DATABASE_PASSWORD = 'bugle' +DATABASE_HOST = 'localhost'
992950cb4e04fc8db8e55924bfe6ea9fdcac3450
armstrong/apps/series/models.py
armstrong/apps/series/models.py
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models # TODO: Refactor this into a generic utils app to remove the wells dep from armstrong.core.arm_wells.querysets import GenericForeignKeyQuerySet class Series(models.Model): title = models.CharField(max_length=250) description = models.TextField() slug = models.SlugField() def __unicode__(self): return self.title def get_items(self): return GenericForeignKeyQuerySet(self.nodes.all().select_related()) @property def items(self): if not getattr(self, '_items', False): self._items = self.get_items() return self._items class SeriesNode(models.Model): series = models.ForeignKey(Series, related_name='nodes') order = models.IntegerField(default=0) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id')
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models # TODO: Refactor this into a generic utils app to remove the wells dep from armstrong.core.arm_wells.querysets import GenericForeignKeyQuerySet class Series(models.Model): title = models.CharField(max_length=250) description = models.TextField() slug = models.SlugField() def __unicode__(self): return self.title def get_items(self): return GenericForeignKeyQuerySet(self.nodes.all().select_related()) @property def items(self): if not getattr(self, '_items', False): self._items = self.get_items() return self._items class SeriesNode(models.Model): class Meta: ordering = ['order', ] series = models.ForeignKey(Series, related_name='nodes') order = models.IntegerField(default=0) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id')
Add in missing default order
Add in missing default order
Python
apache-2.0
armstrong/armstrong.apps.series,armstrong/armstrong.apps.series
--- +++ @@ -25,6 +25,9 @@ class SeriesNode(models.Model): + class Meta: + ordering = ['order', ] + series = models.ForeignKey(Series, related_name='nodes') order = models.IntegerField(default=0)
12780b68aff0da1c123f3516fc6a020cfddb327d
pywikibot/families/wikidata_family.py
pywikibot/families/wikidata_family.py
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105 Patch #3605769 by Legoktm Because of various issues [1], using wikidata.org may cause random problems. Using www.wikidata.org will fix these. [1] https://bugzilla.wikimedia.org/show_bug.cgi?id=45005 git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11106 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
Python
mit
legoktm/pywikipedia-rewrite
--- +++ @@ -11,7 +11,7 @@ super(Family, self).__init__() self.name = 'wikidata' self.langs = { - 'wikidata': 'wikidata.org', + 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', }
7e054868d0df4e69c4b23cb1fb966505d559157f
calico_containers/tests/st/__init__.py
calico_containers/tests/st/__init__.py
import os import sh from sh import docker def setup_package(): """ Sets up docker images and host containers for running the STs. """ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/calico-node.tar", "calico/node") if not os.path.isfile("busybox.tar"): docker.pull("busybox:latest") docker.save("--output", "calico_containers/busybox.tar", "busybox:latest") # Create the calicoctl binary here so it will be in the volume mounted on the hosts. print sh.bash("./create_binary.sh") def teardown_package(): pass
import os import sh from sh import docker def setup_package(): """ Sets up docker images and host containers for running the STs. """ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/calico-node.tar", "calico/node") if not os.path.isfile("calico_containers/busybox.tar"): docker.pull("busybox:latest") docker.save("--output", "calico_containers/busybox.tar", "busybox:latest") # Create the calicoctl binary here so it will be in the volume mounted on the hosts. print sh.bash("./create_binary.sh") def teardown_package(): pass
Fix bug in file path.
Fix bug in file path. Former-commit-id: a1e1f0661331f5bf8faa81210eae2cad0c2ad7b3
Python
apache-2.0
alexhersh/libcalico,tomdee/libcalico,TrimBiggs/libnetwork-plugin,plwhite/libcalico,L-MA/libcalico,TrimBiggs/libnetwork-plugin,Symmetric/libcalico,insequent/libcalico,TrimBiggs/libcalico,projectcalico/libnetwork-plugin,caseydavenport/libcalico,djosborne/libcalico,tomdee/libnetwork-plugin,robbrockbank/libcalico,projectcalico/libcalico
--- +++ @@ -10,7 +10,7 @@ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/calico-node.tar", "calico/node") - if not os.path.isfile("busybox.tar"): + if not os.path.isfile("calico_containers/busybox.tar"): docker.pull("busybox:latest") docker.save("--output", "calico_containers/busybox.tar", "busybox:latest")
c50d470492ed38aa05f147ad554c58877e5050ec
Execute/execute.py
Execute/execute.py
from importlib import import_module _modules = ['branching', 'data_processing'] class Execute(object): def __init__(self, registers, process_mode, memory): self.instruction = {} for module_name in _modules: mod = import_module("Execute." + module_name) for cls in [obj for obj in mod.__dict__ if type(mod.__dict__[obj]) == type]: cls_instance = mod.__dict__[cls](registers, process_mode, memory) for cls_instr in [func for func in mod.__dict__[cls].__dict__ if '_' not in func]: self.instruction[cls_instr] = cls_instance[cls_instr] def __call__(self, args): try: self.instruction[args['instr']](args) except (KeyError, NotImplementedError): print('unhandled: %s - %s' % (args['instr'], args['encoding']))
from importlib import import_module _modules = ['branching', 'data_processing'] class Execute(object): def __init__(self, registers, process_mode, memory): self.instruction = {} for module_name in _modules: mod = import_module("Execute." + module_name) for cls in [obj for obj in mod.__dict__ if type(mod.__dict__[obj]) == type]: cls_instance = mod.__dict__[cls](registers, process_mode, memory) for cls_instr in [func for func in mod.__dict__[cls].__dict__ if not func.startswith('_')]: try: self.instruction[cls_instr] except KeyError: self.instruction[cls_instr] = cls_instance[cls_instr] else: raise Warning('Multiple instruction handlers detected for "%s"' % cls_instr) def __call__(self, args): try: self.instruction[args['instr']](args) except (KeyError, NotImplementedError): print('unhandled: %s - %s' % (args['instr'], args['encoding']))
Check for duplicate instruction handlers
Check for duplicate instruction handlers
Python
mit
tdpearson/armdecode
--- +++ @@ -10,8 +10,13 @@ mod = import_module("Execute." + module_name) for cls in [obj for obj in mod.__dict__ if type(mod.__dict__[obj]) == type]: cls_instance = mod.__dict__[cls](registers, process_mode, memory) - for cls_instr in [func for func in mod.__dict__[cls].__dict__ if '_' not in func]: - self.instruction[cls_instr] = cls_instance[cls_instr] + for cls_instr in [func for func in mod.__dict__[cls].__dict__ if not func.startswith('_')]: + try: + self.instruction[cls_instr] + except KeyError: + self.instruction[cls_instr] = cls_instance[cls_instr] + else: + raise Warning('Multiple instruction handlers detected for "%s"' % cls_instr) def __call__(self, args): try:
96968f9f2d38d45d3154fa3c95860091cc909dd9
pylibchorus/__init__.py
pylibchorus/__init__.py
#!/usr/bin/env python '''PyLibChorus -- Python Chorus API Library''' import logging from pylibchorus.chorus_api import login from pylibchorus.chorus_api import logout from pylibchorus.chorus_api import check_login_status from pylibchorus.chorus_api import create_workfile from pylibchorus.chorus_api import update_workfile_version from pylibchorus.chorus_api import delete_workfile LOG = logging.getLogger(__name__) #pylint: disable=R0903 class ChorusSession(object): '''Chorus User Session Object''' def __init__(self, config): self.config = config self.sid = None self.cookies = None def __enter__(self): '''create session and return sid and cookies''' LOG.debug("Opening Chorus Session") post = login( self.config.get('alpine', 'username'), self.config.get('alpine', 'password'), self) json = post.json() self.sid = json['response']['session_id'] self.cookies = post.cookies return self def __exit__(self, _type, _value, _traceback): '''Close chorus session''' LOG.debug("Closing Chorus Session") logout(self)
#!/usr/bin/env python '''PyLibChorus -- Python Chorus API Library''' import logging from pylibchorus.chorus_api import login from pylibchorus.chorus_api import logout from pylibchorus.chorus_api import check_login_status from pylibchorus.chorus_api import create_workfile from pylibchorus.chorus_api import update_workfile_version from pylibchorus.chorus_api import delete_workfile LOG = logging.getLogger(__name__) #pylint: disable=R0903 class ChorusSession(object): '''Chorus User Session Object''' def __init__(self, config): self.config = config self.sid = None self.cookies = None def __enter__(self): '''create session and return sid and cookies''' LOG.debug("Opening Chorus Session") post = login( self.config.get('alpine', 'username'), self.config.get('alpine', 'password'), self) json = post.json() self.sid = json['response']['session_id'] self.cookies = dict(post.cookies) return self def __exit__(self, _type, _value, _traceback): '''Close chorus session''' LOG.debug("Closing Chorus Session") logout(self)
Store session cookies as a dictionary
Store session cookies as a dictionary
Python
mit
kennyballou/pylibchorus
--- +++ @@ -31,7 +31,7 @@ json = post.json() self.sid = json['response']['session_id'] - self.cookies = post.cookies + self.cookies = dict(post.cookies) return self def __exit__(self, _type, _value, _traceback):
9ac496491fccc1bd1ba55d3302608a0fe34957a1
tests/test_population.py
tests/test_population.py
import os from neat.population import Population from neat.config import Config def test_minimal(): # sample fitness function def eval_fitness(population): for individual in population: individual.fitness = 1.0 # creates the population local_dir = os.path.dirname(__file__) config = Config(os.path.join(local_dir, 'test_configuration')) pop = Population(config) # runs the simulation for 250 epochs pop.epoch(eval_fitness, 250) def test_config_options(): # sample fitness function def eval_fitness(population): for individual in population: individual.fitness = 1.0 local_dir = os.path.dirname(__file__) config = Config(os.path.join(local_dir, 'test_configuration')) for hn in (0, 1, 2): config.hidden_nodes = hn for fc in (0, 1): config.fully_connected = fc for act in ('exp', 'tanh'): config.nn_activation = act for ff in (0, 1): config.feedforward = ff pop = Population(config) pop.epoch(eval_fitness, 250)
import os from neat.population import Population from neat.config import Config from neat.statistics import get_average_fitness def test_minimal(): # sample fitness function def eval_fitness(population): for individual in population: individual.fitness = 1.0 # creates the population local_dir = os.path.dirname(__file__) config = Config(os.path.join(local_dir, 'test_configuration')) pop = Population(config) # runs the simulation for up to 20 epochs pop.epoch(eval_fitness, 20) # get statistics avg_fitness = get_average_fitness(pop) assert len(avg_fitness) == 1 assert all(f == 1 for f in avg_fitness) # Change fitness threshold and do another run. config.max_fitness_threshold = 1.1 pop = Population(config) # runs the simulation for 20 epochs pop.epoch(eval_fitness, 20) # get statistics avg_fitness = get_average_fitness(pop) assert len(avg_fitness) == 20 assert all(f == 1 for f in avg_fitness) def test_config_options(): # sample fitness function def eval_fitness(population): for individual in population: individual.fitness = 1.0 local_dir = os.path.dirname(__file__) config = Config(os.path.join(local_dir, 'test_configuration')) for hn in (0, 1, 2): config.hidden_nodes = hn for fc in (0, 1): config.fully_connected = fc for act in ('exp', 'tanh'): config.nn_activation = act for ff in (0, 1): config.feedforward = ff pop = Population(config) pop.epoch(eval_fitness, 250)
Include statistics usage in existing tests.
Include statistics usage in existing tests.
Python
bsd-3-clause
drallensmith/neat-python,machinebrains/neat-python,CodeReclaimers/neat-python
--- +++ @@ -1,6 +1,7 @@ import os from neat.population import Population from neat.config import Config +from neat.statistics import get_average_fitness def test_minimal(): @@ -14,8 +15,25 @@ config = Config(os.path.join(local_dir, 'test_configuration')) pop = Population(config) - # runs the simulation for 250 epochs - pop.epoch(eval_fitness, 250) + # runs the simulation for up to 20 epochs + pop.epoch(eval_fitness, 20) + + # get statistics + avg_fitness = get_average_fitness(pop) + assert len(avg_fitness) == 1 + assert all(f == 1 for f in avg_fitness) + + # Change fitness threshold and do another run. + config.max_fitness_threshold = 1.1 + pop = Population(config) + # runs the simulation for 20 epochs + pop.epoch(eval_fitness, 20) + + # get statistics + avg_fitness = get_average_fitness(pop) + assert len(avg_fitness) == 20 + assert all(f == 1 for f in avg_fitness) + def test_config_options():
9018093933e7f8d04ad5d7f753651e3c77c0cf12
pushbullet.py
pushbullet.py
import weechat from yapbl import PushBullet apikey = "" p = PushBullet(apikey) weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test Skript", "", "") weechat.prnt("", "Hallo, von einem python Skript!") def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(ishilight): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat Hilight', buffer+": "+message) elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat MSG from '+buffer, buffer+": "+message) return weechat.WEECHAT_RC_OK weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
import weechat from yapbl import PushBullet apikey = "" p = PushBullet(apikey) weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test Skript", "", "") weechat.prnt("", "Hallo, von einem python Skript!") def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(ishilight): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat Hilight', buffer+": <"+prefix+"> "+message) elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat MSG from '+buffer, buffer+": "+message) return weechat.WEECHAT_RC_OK weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
Fix Nano (m() stuff and add nick name
Fix Nano (m() stuff and add nick name
Python
mit
sspssp/weechat-pushbullet
--- +++ @@ -13,13 +13,10 @@ def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(ishilight): - buffer = (weechat.buffer_get_string(bufferp, "short_name") or -weechat.buffer_get_string(bufferp, "name")) - p.push_note('Weechat Hilight', buffer+": "+message) - elif(weechat.buffer_get_string(bufferp, "localvar_type") == -"private"): - buffer = (weechat.buffer_get_string(bufferp, "short_name") or -weechat.buffer_get_string(bufferp, "name")) + buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) + p.push_note('Weechat Hilight', buffer+": <"+prefix+"> "+message) + elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"): + buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat MSG from '+buffer, buffer+": "+message) return weechat.WEECHAT_RC_OK
572b9e2919b7c1107fafb0871cbc8b0e403eb187
examples/keyassignedlistview.py
examples/keyassignedlistview.py
from clubsandwich.director import DirectorLoop from clubsandwich.ui import UIScene, WindowView, KeyAssignedListView, ButtonView class BasicScene(UIScene): def __init__(self): button_generator = (ButtonView( text="Item {}".format(i), callback=lambda: print("Called Item {}".format(i))) for i in range(0, 100) ) self.key_assign = KeyAssignedListView( value_controls=button_generator ) super().__init__(WindowView( "Scrolling Text", subviews=[self.key_assign])) class DemoLoop(DirectorLoop): def get_initial_scene(self): return BasicScene() if __name__ == '__main__': DemoLoop().run()
from clubsandwich.director import DirectorLoop from clubsandwich.ui import UIScene, WindowView, KeyAssignedListView, ButtonView class BasicScene(UIScene): def __init__(self): button_generator = (ButtonView( text="Item {}".format(i), callback=lambda x=i: print("Called Item {}".format(x))) for i in range(0, 100) ) self.key_assign = KeyAssignedListView( value_controls=button_generator ) super().__init__(WindowView( "Scrolling Text", subviews=[self.key_assign])) class DemoLoop(DirectorLoop): def get_initial_scene(self): return BasicScene() if __name__ == '__main__': DemoLoop().run()
Fix incorrectly captured value in closure in KeyAssignedListView example.
Fix incorrectly captured value in closure in KeyAssignedListView example.
Python
mit
irskep/clubsandwich
--- +++ @@ -6,7 +6,7 @@ def __init__(self): button_generator = (ButtonView( text="Item {}".format(i), - callback=lambda: print("Called Item {}".format(i))) + callback=lambda x=i: print("Called Item {}".format(x))) for i in range(0, 100) ) self.key_assign = KeyAssignedListView(
5079ef52751288758596e1c9e0ffed119540a05e
framework/sentry/__init__.py
framework/sentry/__init__.py
#!/usr/bin/env python # encoding: utf-8 import logging from raven.contrib.flask import Sentry from framework.sessions import get_session from website import settings logger = logging.getLogger(__name__) sentry = Sentry(dsn=settings.SENTRY_DSN) # Nothing in this module should send to Sentry if debug mode is on # or if Sentry isn't configured. enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN def get_session_data(): try: return get_session().data except (RuntimeError, AttributeError): return {} def log_exception(): if not enabled: logger.warning('Sentry called to log exception, but is not active') return None return sentry.captureException(extra={ 'session': get_session_data(), }) def log_message(message): if not enabled: logger.warning( 'Sentry called to log message, but is not active: %s' % message ) return None return sentry.captureMessage(message, extra={ 'session': get_session_data(), })
#!/usr/bin/env python # encoding: utf-8 import logging from raven.contrib.flask import Sentry from framework.sessions import get_session from website import settings logger = logging.getLogger(__name__) sentry = Sentry(dsn=settings.SENTRY_DSN) # Nothing in this module should send to Sentry if debug mode is on # or if Sentry isn't configured. enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN def get_session_data(): try: return get_session().data except (RuntimeError, AttributeError): return {} def log_exception(): if not enabled: logger.warning('Sentry called to log exception, but is not active') return None return sentry.captureException(extra={ 'session': get_session_data(), }) def log_message(message, extra={}): if not enabled: logger.warning( 'Sentry called to log message, but is not active: %s' % message ) return None return sentry.captureMessage(message, extra=extra)
Allow passing extra data to sentry
Allow passing extra data to sentry
Python
apache-2.0
TomBaxter/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,adlius/osf.io,caneruguz/osf.io,chrisseto/osf.io,TomBaxter/osf.io,TomBaxter/osf.io,crcresearch/osf.io,felliott/osf.io,icereval/osf.io,caneruguz/osf.io,sloria/osf.io,mfraezz/osf.io,binoculars/osf.io,brianjgeiger/osf.io,icereval/osf.io,felliott/osf.io,saradbowman/osf.io,caneruguz/osf.io,sloria/osf.io,binoculars/osf.io,Johnetordoff/osf.io,erinspace/osf.io,binoculars/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,sloria/osf.io,caseyrollins/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,laurenrevere/osf.io,mfraezz/osf.io,caseyrollins/osf.io,caneruguz/osf.io,chrisseto/osf.io,icereval/osf.io,erinspace/osf.io,leb2dg/osf.io,leb2dg/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,leb2dg/osf.io,adlius/osf.io,felliott/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,felliott/osf.io,pattisdr/osf.io,crcresearch/osf.io,mattclark/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,chennan47/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,chrisseto/osf.io,crcresearch/osf.io,aaxelb/osf.io,cslzchen/osf.io,aaxelb/osf.io,pattisdr/osf.io,pattisdr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,erinspace/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,caseyrollins/osf.io,adlius/osf.io,mfraezz/osf.io,aaxelb/osf.io,mattclark/osf.io,baylee-d/osf.io
--- +++ @@ -35,13 +35,11 @@ }) -def log_message(message): +def log_message(message, extra={}): if not enabled: logger.warning( 'Sentry called to log message, but is not active: %s' % message ) return None - return sentry.captureMessage(message, extra={ - 'session': get_session_data(), - }) + return sentry.captureMessage(message, extra=extra)
879ea9c4234a5d8435f213c6f9b082a86a794ecc
employees/serializers.py
employees/serializers.py
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'role', 'skype_id', 'last_month_score', 'current_month_score', 'level', 'score', 'is_active', 'last_login') class EmployeeListSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'level', 'avatar', 'score') class EmployeeAvatarSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'avatar')
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'role', 'skype_id', 'last_month_score', 'current_month_score', 'level', 'score', 'categories', 'is_active', 'last_login') class EmployeeListSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'level', 'avatar', 'score') class EmployeeAvatarSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'avatar')
Add 1 level depth and also categories fields to employee serializer
Add 1 level depth and also categories fields to employee serializer
Python
apache-2.0
belatrix/BackendAllStars
--- +++ @@ -5,6 +5,7 @@ class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee + depth = 1 fields = ('pk', 'username', 'email', @@ -16,6 +17,7 @@ 'current_month_score', 'level', 'score', + 'categories', 'is_active', 'last_login')
b26bf17154e478ee02e0e2936d7623d71698e1f2
subprocrunner/_which.py
subprocrunner/_which.py
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import errno import shutil from typing import Optional from .error import CommandError class Which: @property def command(self): return self.__command def __init__(self, command: str) -> None: if not command: raise CommandError( "invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL ) self.__command = command self.__abspath = None # type: Optional[str] def __repr__(self) -> str: item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())] if self.is_exist(): item_list.append("abspath={}".format(self.abspath())) return ", ".join(item_list) def is_exist(self) -> bool: return self.abspath() is not None def verify(self) -> None: if not self.is_exist(): raise CommandError( "command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT ) def abspath(self) -> Optional[str]: if self.__abspath: return self.__abspath self.__abspath = shutil.which(self.command) return self.__abspath
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import errno import shutil from typing import Optional from .error import CommandError class Which: @property def command(self): return self.__command def __init__(self, command: str) -> None: if not command: raise ValueError("require a command") self.__command = command self.__abspath = None # type: Optional[str] def __repr__(self) -> str: item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())] if self.is_exist(): item_list.append("abspath={}".format(self.abspath())) return ", ".join(item_list) def is_exist(self) -> bool: return self.abspath() is not None def verify(self) -> None: if not self.is_exist(): raise CommandError( "command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT ) def abspath(self) -> Optional[str]: if self.__abspath: return self.__abspath self.__abspath = shutil.which(self.command) return self.__abspath
Modify an error handling when a command not specified for Which
Modify an error handling when a command not specified for Which
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
--- +++ @@ -17,9 +17,7 @@ def __init__(self, command: str) -> None: if not command: - raise CommandError( - "invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL - ) + raise ValueError("require a command") self.__command = command self.__abspath = None # type: Optional[str]
ae5a8bb000702ee4e0bbce863bc72d603ec6ca3d
polycircles/test/test_exceptions.py
polycircles/test/test_exceptions.py
import unittest from polycircles import polycircles from nose.tools import raises class TestExceptions(unittest.TestCase): @raises(ValueError) def test_less_than_3_vertices_no_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=2) @raises(ValueError) def test_less_than_3_vertices_no_2(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=-3) @raises(ValueError) def test_less_than_3_vertices_no_3(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=0) if __name__ == '__main__': unittest.main(verbose=2)
import unittest from polycircles import polycircles from nose.tools import raises class TestExceptions(unittest.TestCase): @raises(ValueError) def test_less_than_3_vertices_no_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=2) @raises(ValueError) def test_less_than_3_vertices_no_2(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=-3) @raises(ValueError) def test_less_than_3_vertices_no_3(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=0) @raises(ValueError) def test_erroneous_latitude_1(self): polycircle = polycircles.Polycircle(latitude=-100, longitude=30, radius=100) @raises(ValueError) def test_erroneous_latitude_2(self): polycircle = polycircles.Polycircle(latitude=100, longitude=30, radius=100) @raises(ValueError) def test_erroneous_latitude_3(self): polycircle = polycircles.Polycircle(latitude=200, longitude=30, radius=100) @raises(ValueError) def test_erroneous_longitude_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=-200, radius=100) @raises(ValueError) def test_erroneous_longitude_2(self): polycircle = polycircles.Polycircle(latitude=30, longitude=200, radius=100) if __name__ == '__main__': unittest.main(verbose=2)
Add nose tests to validate Exception raising.
Add nose tests to validate Exception raising.
Python
mit
adamatan/polycircles
--- +++ @@ -25,7 +25,34 @@ radius=100, number_of_vertices=0) + @raises(ValueError) + def test_erroneous_latitude_1(self): + polycircle = polycircles.Polycircle(latitude=-100, + longitude=30, + radius=100) + @raises(ValueError) + def test_erroneous_latitude_2(self): + polycircle = polycircles.Polycircle(latitude=100, + longitude=30, + radius=100) + + @raises(ValueError) + def test_erroneous_latitude_3(self): + polycircle = polycircles.Polycircle(latitude=200, + longitude=30, + radius=100) + @raises(ValueError) + def test_erroneous_longitude_1(self): + polycircle = polycircles.Polycircle(latitude=30, + longitude=-200, + radius=100) + + @raises(ValueError) + def test_erroneous_longitude_2(self): + polycircle = polycircles.Polycircle(latitude=30, + longitude=200, + radius=100) if __name__ == '__main__': unittest.main(verbose=2)
1993a0adad94b0ed22557e2ee87326fc1eca0793
cumulusci/robotframework/locators_50.py
cumulusci/robotframework/locators_50.py
from cumulusci.robotframework import locators_49 import copy lex_locators = copy.deepcopy(locators_49.lex_locators) lex_locators["object"][ "button" ] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]" lex_locators["record"]["header"][ "field_value_link" ] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a" lex_locators["record"]["related"][ "card" ] = "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]"
from cumulusci.robotframework import locators_49 import copy lex_locators = copy.deepcopy(locators_49.lex_locators) lex_locators["object"][ "button" ] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]" lex_locators["record"]["header"][ "field_value_link" ] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a" lex_locators["record"]["related"] = { "button": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//a[@title='{}']", "card": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]", "count": "//*[@data-component-id='force_relatedListContainer']//article//span[@title='{}']/following-sibling::span", "link": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//*[text()='{}']", "popup_trigger": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//span[text()='Show Actions']", }
Update all related list locators
Update all related list locators
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
--- +++ @@ -11,6 +11,11 @@ "field_value_link" ] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a" -lex_locators["record"]["related"][ - "card" -] = "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]" + +lex_locators["record"]["related"] = { + "button": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//a[@title='{}']", + "card": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]", + "count": "//*[@data-component-id='force_relatedListContainer']//article//span[@title='{}']/following-sibling::span", + "link": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//*[text()='{}']", + "popup_trigger": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//span[text()='Show Actions']", +}
d292a81e95bd558f3902f88fa4d6d5641a4aa388
tests/io/open_append.py
tests/io/open_append.py
import sys try: import _os as os except ImportError: import os if not hasattr(os, "unlink"): print("SKIP") sys.exit() try: os.unlink("testfile") except OSError: pass # Should create a file f = open("testfile", "a") f.write("foo") f.close() f = open("testfile") print(f.read()) f.close() f = open("testfile", "a") f.write("bar") f.close() f = open("testfile") print(f.read()) f.close()
import sys try: import _os as os except ImportError: import os if not hasattr(os, "unlink"): print("SKIP") sys.exit() # cleanup in case testfile exists try: os.unlink("testfile") except OSError: pass # Should create a file f = open("testfile", "a") f.write("foo") f.close() f = open("testfile") print(f.read()) f.close() f = open("testfile", "a") f.write("bar") f.close() f = open("testfile") print(f.read()) f.close() # cleanup try: os.unlink("testfile") except OSError: pass
Make io test cleanup after itself by removing 'testfile'.
tests: Make io test cleanup after itself by removing 'testfile'.
Python
mit
tobbad/micropython,ahotam/micropython,adafruit/circuitpython,mhoffma/micropython,noahchense/micropython,adamkh/micropython,vitiral/micropython,orionrobots/micropython,adafruit/circuitpython,pozetroninc/micropython,lowRISC/micropython,ernesto-g/micropython,SHA2017-badge/micropython-esp32,ChuckM/micropython,misterdanb/micropython,henriknelson/micropython,cwyark/micropython,micropython/micropython-esp32,adafruit/micropython,dhylands/micropython,xyb/micropython,blmorris/micropython,dxxb/micropython,tobbad/micropython,pramasoul/micropython,xuxiaoxin/micropython,alex-robbins/micropython,selste/micropython,turbinenreiter/micropython,trezor/micropython,drrk/micropython,adafruit/circuitpython,stonegithubs/micropython,xyb/micropython,stonegithubs/micropython,infinnovation/micropython,cloudformdesign/micropython,mhoffma/micropython,turbinenreiter/micropython,tobbad/micropython,praemdonck/micropython,tralamazza/micropython,ahotam/micropython,oopy/micropython,xhat/micropython,chrisdearman/micropython,kerneltask/micropython,utopiaprince/micropython,skybird6672/micropython,firstval/micropython,dinau/micropython,lowRISC/micropython,blmorris/micropython,mhoffma/micropython,PappaPeppar/micropython,feilongfl/micropython,praemdonck/micropython,henriknelson/micropython,turbinenreiter/micropython,ahotam/micropython,PappaPeppar/micropython,Timmenem/micropython,pozetroninc/micropython,mianos/micropython,kerneltask/micropython,tralamazza/micropython,mianos/micropython,oopy/micropython,vitiral/micropython,ChuckM/micropython,dinau/micropython,mianos/micropython,supergis/micropython,infinnovation/micropython,ruffy91/micropython,EcmaXp/micropython,firstval/micropython,ganshun666/micropython,cwyark/micropython,MrSurly/micropython,alex-march/micropython,martinribelotta/micropython,deshipu/micropython,firstval/micropython,chrisdearman/micropython,pfalcon/micropython,neilh10/micropython,galenhz/micropython,ruffy91/micropython,feilongfl/micropython,omtinez/micropython,micropython/micropython-esp32,dmazzella/micropython,dxxb/micropython,noahchense/micropython,PappaPeppar/micropython,hosaka/micropython,xuxiaoxin/micropython,vriera/micropython,infinnovation/micropython,adafruit/micropython,vitiral/micropython,jlillest/micropython,torwag/micropython,henriknelson/micropython,dmazzella/micropython,alex-march/micropython,martinribelotta/micropython,torwag/micropython,firstval/micropython,Timmenem/micropython,ganshun666/micropython,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,puuu/micropython,mhoffma/micropython,turbinenreiter/micropython,noahwilliamsson/micropython,xuxiaoxin/micropython,pfalcon/micropython,orionrobots/micropython,redbear/micropython,blazewicz/micropython,bvernoux/micropython,hosaka/micropython,ryannathans/micropython,deshipu/micropython,emfcamp/micropython,trezor/micropython,pfalcon/micropython,dxxb/micropython,drrk/micropython,utopiaprince/micropython,danicampora/micropython,jmarcelino/pycom-micropython,praemdonck/micropython,ernesto-g/micropython,alex-robbins/micropython,rubencabrera/micropython,rubencabrera/micropython,ericsnowcurrently/micropython,puuu/micropython,hiway/micropython,ryannathans/micropython,galenhz/micropython,danicampora/micropython,redbear/micropython,SHA2017-badge/micropython-esp32,TDAbboud/micropython,dmazzella/micropython,ericsnowcurrently/micropython,cloudformdesign/micropython,deshipu/micropython,ganshun666/micropython,MrSurly/micropython,omtinez/micropython,jlillest/micropython,AriZuu/micropython,ernesto-g/micropython,rubencabrera/micropython,chrisdearman/micropython,vitiral/micropython,kerneltask/micropython,pfalcon/micropython,neilh10/micropython,selste/micropython,Peetz0r/micropython-esp32,mpalomer/micropython,selste/micropython,xhat/micropython,noahchense/micropython,EcmaXp/micropython,feilongfl/micropython,dhylands/micropython,drrk/micropython,ernesto-g/micropython,ahotam/micropython,EcmaXp/micropython,toolmacher/micropython,omtinez/micropython,drrk/micropython,adafruit/circuitpython,hiway/micropython,TDAbboud/micropython,blazewicz/micropython,torwag/micropython,xyb/micropython,ernesto-g/micropython,Timmenem/micropython,firstval/micropython,feilongfl/micropython,ryannathans/micropython,AriZuu/micropython,feilongfl/micropython,alex-robbins/micropython,EcmaXp/micropython,dinau/micropython,mpalomer/micropython,supergis/micropython,adafruit/micropython,jmarcelino/pycom-micropython,emfcamp/micropython,TDAbboud/micropython,vriera/micropython,xhat/micropython,xuxiaoxin/micropython,turbinenreiter/micropython,oopy/micropython,rubencabrera/micropython,swegener/micropython,oopy/micropython,orionrobots/micropython,tuc-osg/micropython,skybird6672/micropython,vriera/micropython,henriknelson/micropython,tobbad/micropython,drrk/micropython,puuu/micropython,adafruit/micropython,hiway/micropython,pramasoul/micropython,skybird6672/micropython,ericsnowcurrently/micropython,infinnovation/micropython,toolmacher/micropython,pramasoul/micropython,jlillest/micropython,martinribelotta/micropython,mhoffma/micropython,blmorris/micropython,EcmaXp/micropython,swegener/micropython,blmorris/micropython,MrSurly/micropython,AriZuu/micropython,MrSurly/micropython-esp32,jmarcelino/pycom-micropython,mpalomer/micropython,Peetz0r/micropython-esp32,danicampora/micropython,micropython/micropython-esp32,pfalcon/micropython,henriknelson/micropython,stonegithubs/micropython,adamkh/micropython,galenhz/micropython,stonegithubs/micropython,stonegithubs/micropython,HenrikSolver/micropython,adamkh/micropython,noahwilliamsson/micropython,praemdonck/micropython,cloudformdesign/micropython,adamkh/micropython,HenrikSolver/micropython,blmorris/micropython,neilh10/micropython,chrisdearman/micropython,neilh10/micropython,ganshun666/micropython,oopy/micropython,swegener/micropython,pramasoul/micropython,torwag/micropython,bvernoux/micropython,ganshun666/micropython,PappaPeppar/micropython,cloudformdesign/micropython,jlillest/micropython,mpalomer/micropython,cwyark/micropython,ChuckM/micropython,martinribelotta/micropython,emfcamp/micropython,dxxb/micropython,dxxb/micropython,mianos/micropython,misterdanb/micropython,utopiaprince/micropython,mpalomer/micropython,jlillest/micropython,Peetz0r/micropython-esp32,ChuckM/micropython,supergis/micropython,neilh10/micropython,tralamazza/micropython,swegener/micropython,noahwilliamsson/micropython,matthewelse/micropython,selste/micropython,matthewelse/micropython,blazewicz/micropython,dhylands/micropython,noahchense/micropython,trezor/micropython,rubencabrera/micropython,toolmacher/micropython,bvernoux/micropython,misterdanb/micropython,ruffy91/micropython,trezor/micropython,chrisdearman/micropython,infinnovation/micropython,dhylands/micropython,lowRISC/micropython,pozetroninc/micropython,adafruit/circuitpython,Peetz0r/micropython-esp32,ryannathans/micropython,mianos/micropython,vriera/micropython,lowRISC/micropython,puuu/micropython,matthewelse/micropython,jmarcelino/pycom-micropython,dinau/micropython,micropython/micropython-esp32,danicampora/micropython,Timmenem/micropython,matthewelse/micropython,ryannathans/micropython,galenhz/micropython,skybird6672/micropython,AriZuu/micropython,ericsnowcurrently/micropython,alex-march/micropython,hiway/micropython,dmazzella/micropython,hosaka/micropython,misterdanb/micropython,SHA2017-badge/micropython-esp32,pramasoul/micropython,MrSurly/micropython,ericsnowcurrently/micropython,xhat/micropython,hosaka/micropython,deshipu/micropython,pozetroninc/micropython,HenrikSolver/micropython,supergis/micropython,vitiral/micropython,blazewicz/micropython,redbear/micropython,TDAbboud/micropython,noahwilliamsson/micropython,redbear/micropython,torwag/micropython,alex-robbins/micropython,adafruit/micropython,utopiaprince/micropython,bvernoux/micropython,supergis/micropython,skybird6672/micropython,alex-march/micropython,kerneltask/micropython,hiway/micropython,dhylands/micropython,omtinez/micropython,MrSurly/micropython-esp32,lowRISC/micropython,redbear/micropython,misterdanb/micropython,MrSurly/micropython-esp32,alex-march/micropython,tuc-osg/micropython,adafruit/circuitpython,swegener/micropython,cwyark/micropython,danicampora/micropython,toolmacher/micropython,AriZuu/micropython,praemdonck/micropython,dinau/micropython,orionrobots/micropython,deshipu/micropython,micropython/micropython-esp32,tuc-osg/micropython,jmarcelino/pycom-micropython,blazewicz/micropython,TDAbboud/micropython,orionrobots/micropython,galenhz/micropython,puuu/micropython,matthewelse/micropython,martinribelotta/micropython,noahwilliamsson/micropython,adamkh/micropython,HenrikSolver/micropython,matthewelse/micropython,tobbad/micropython,HenrikSolver/micropython,omtinez/micropython,tuc-osg/micropython,PappaPeppar/micropython,emfcamp/micropython,kerneltask/micropython,MrSurly/micropython-esp32,bvernoux/micropython,ChuckM/micropython,MrSurly/micropython-esp32,alex-robbins/micropython,MrSurly/micropython,tralamazza/micropython,ahotam/micropython,hosaka/micropython,Peetz0r/micropython-esp32,ruffy91/micropython,xyb/micropython,cwyark/micropython,Timmenem/micropython,tuc-osg/micropython,xhat/micropython,pozetroninc/micropython,selste/micropython,vriera/micropython,emfcamp/micropython,xyb/micropython,trezor/micropython,utopiaprince/micropython,toolmacher/micropython,cloudformdesign/micropython,noahchense/micropython,xuxiaoxin/micropython,ruffy91/micropython
--- +++ @@ -8,6 +8,7 @@ print("SKIP") sys.exit() +# cleanup in case testfile exists try: os.unlink("testfile") except OSError: @@ -29,3 +30,9 @@ f = open("testfile") print(f.read()) f.close() + +# cleanup +try: + os.unlink("testfile") +except OSError: + pass
eb9fa38f2c4c82a5674474f9a535bc8c35f8e38e
tests/test_bookmarks.py
tests/test_bookmarks.py
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() # def tearDown(self): # os.close(self.db_fd) # os.unlink(bookmarks.app.config['DATABASE']) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
Adjust test file to match new env config options
Adjust test file to match new env config options
Python
apache-2.0
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
--- +++ @@ -4,15 +4,15 @@ class FlaskrTestCase(unittest.TestCase): def setUp(self): - bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] - bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() - # def tearDown(self): - # os.close(self.db_fd) - # os.unlink(bookmarks.app.config['DATABASE']) + def tearDown(self): + with bookmarks.app.app_context(): + bookmarks.database.db_session.remove() + bookmarks.database.Base.metadata.drop_all( + bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/')
45e0605a178c36a4075b59026952ef5a797e09aa
examples/pystray_icon.py
examples/pystray_icon.py
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys if sys.platform == 'darwin': raise NotImplementedError('This example does not work on macOS.') from threading import Thread from queue import Queue """ This example demonstrates running pywebview alongside with pystray to display a system tray icon. """ def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() def run_pystray(queue: Queue): def on_open(icon, item): queue.put('open') def on_exit(icon, item): icon.stop() queue.put('exit') image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, "Pystray", menu) icon.run() if __name__ == '__main__': queue = Queue() icon_thread = Thread(target=run_pystray, args=(queue,)) icon_thread.start() run_webview() while True: event = queue.get() if event == 'open': run_webview() if event == 'exit': break icon_thread.join()
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys import multiprocessing if sys.platform == 'darwin': ctx = multiprocessing.get_context('spawn') Process = ctx.Process Queue = ctx.Queue else: Process = multiprocessing.Process Queue = multiprocessing.Queue """ This example demonstrates running pywebview alongside with pystray to display a system tray icon. """ webview_process = None def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() if __name__ == '__main__': def start_webview_process(): global webview_process webview_process = Process(target=run_webview) webview_process.start() def on_open(icon, item): global webview_process if not webview_process.is_alive(): start_webview_process() def on_exit(icon, item): icon.stop() start_webview_process() image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, menu=menu) icon.run() webview_process.terminate()
Improve example, start pystray in main thread and webview in new process
Improve example, start pystray in main thread and webview in new process
Python
bsd-3-clause
r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview
--- +++ @@ -2,12 +2,15 @@ from pystray import Icon, Menu, MenuItem import webview import sys +import multiprocessing if sys.platform == 'darwin': - raise NotImplementedError('This example does not work on macOS.') - -from threading import Thread -from queue import Queue + ctx = multiprocessing.get_context('spawn') + Process = ctx.Process + Queue = ctx.Queue +else: + Process = multiprocessing.Process + Queue = multiprocessing.Queue """ @@ -15,39 +18,34 @@ """ +webview_process = None + + def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() -def run_pystray(queue: Queue): +if __name__ == '__main__': + + def start_webview_process(): + global webview_process + webview_process = Process(target=run_webview) + webview_process.start() def on_open(icon, item): - queue.put('open') + global webview_process + if not webview_process.is_alive(): + start_webview_process() def on_exit(icon, item): icon.stop() - queue.put('exit') + + start_webview_process() image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) - icon = Icon('Pystray', image, "Pystray", menu) + icon = Icon('Pystray', image, menu=menu) icon.run() - -if __name__ == '__main__': - queue = Queue() - - icon_thread = Thread(target=run_pystray, args=(queue,)) - icon_thread.start() - - run_webview() - - while True: - event = queue.get() - if event == 'open': - run_webview() - if event == 'exit': - break - - icon_thread.join() + webview_process.terminate()
50cff5854983c0235630538ed0b4d909d9cc7890
memegen/routes/latest.py
memegen/routes/latest.py
from flask import Blueprint, render_template from flask_api.decorators import set_renderers from flask_api.renderers import HTMLRenderer from ._common import route, get_tid blueprint = Blueprint('latest', __name__, url_prefix="/latest") @blueprint.route("") @set_renderers(HTMLRenderer) def get(): return render_template( 'latest.html', srcs=[route('image.get_latest', index=i + 1) for i in range(9)], refresh=5, ga_tid=get_tid(), )
from flask import Blueprint, render_template from flask_api.decorators import set_renderers from flask_api.renderers import HTMLRenderer from ._common import route, get_tid blueprint = Blueprint('latest', __name__, url_prefix="/latest") @blueprint.route("") @set_renderers(HTMLRenderer) def get(): return render_template( 'latest.html', srcs=[route('image.get_latest', index=i + 1) for i in range(9)], refresh=10, ga_tid=get_tid(), )
Set refresh rate to 10 seconds
Set refresh rate to 10 seconds
Python
mit
DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen
--- +++ @@ -14,6 +14,6 @@ return render_template( 'latest.html', srcs=[route('image.get_latest', index=i + 1) for i in range(9)], - refresh=5, + refresh=10, ga_tid=get_tid(), )
5d4572f08c6e65a062fd2f00590f6eeb5e12ce38
src/zeit/content/article/edit/browser/tests/test_template.py
src/zeit/content/article/edit/browser/tests/test_template.py
# coding: utf8 import zeit.content.article.edit.browser.testing class ArticleTemplateTest( zeit.content.article.edit.browser.testing.EditorTestCase): def setUp(self): super(ArticleTemplateTest, self).setUp() self.add_article() self.selenium.waitForElementPresent('id=options-template.template') def test_changing_template_should_update_header_layout_list(self): s = self.selenium s.click('css=#edit-form-misc .edit-bar .fold-link') s.assertSelectedLabel( 'id=options-template.template', '(nothing selected)') s.assertNotVisible('css=.fieldname-header_layout') s.select('id=options-template.template', 'Kolumne') s.pause(100) kolumne_layouts = [ u'(nothing selected)', u'Heiter bis glücklich', u'Ich habe einen Traum', u'Martenstein', u'Standard', u'Von A nach B', ] s.assertVisible('css=.fieldname-header_layout') self.assertEqual( kolumne_layouts, s.getSelectOptions('id=options-template.header_layout')) s.type('id=options-template.header_layout', '\t') s.pause(500) self.assertEqual( kolumne_layouts, s.getSelectOptions('id=options-template.header_layout'))
# coding: utf8 import zeit.content.article.edit.browser.testing class ArticleTemplateTest( zeit.content.article.edit.browser.testing.EditorTestCase): def setUp(self): super(ArticleTemplateTest, self).setUp() self.add_article() self.selenium.waitForElementPresent('id=options-template.template') def test_changing_template_should_update_header_layout_list(self): s = self.selenium s.click('css=#edit-form-misc .edit-bar .fold-link') s.assertSelectedLabel( 'id=options-template.template', 'Artikel') s.select('id=options-template.template', 'Kolumne') s.pause(100) kolumne_layouts = [ u'(nothing selected)', u'Heiter bis glücklich', u'Ich habe einen Traum', u'Martenstein', u'Standard', u'Von A nach B', ] s.assertVisible('css=.fieldname-header_layout') self.assertEqual( kolumne_layouts, s.getSelectOptions('id=options-template.header_layout')) s.type('id=options-template.header_layout', '\t') s.pause(500) self.assertEqual( kolumne_layouts, s.getSelectOptions('id=options-template.header_layout'))
Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
ZON-3178: Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
Python
bsd-3-clause
ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article
--- +++ @@ -15,8 +15,7 @@ s.click('css=#edit-form-misc .edit-bar .fold-link') s.assertSelectedLabel( - 'id=options-template.template', '(nothing selected)') - s.assertNotVisible('css=.fieldname-header_layout') + 'id=options-template.template', 'Artikel') s.select('id=options-template.template', 'Kolumne') s.pause(100)
7cc76c2716ce54882b7eced67f4435acd100cd83
example/src/hello-world/hello-world.py
example/src/hello-world/hello-world.py
# Include the directory where cvui is so we can load it import sys sys.path.append('../../../') import numpy as np import cv2 import cvui cvui.random_number_generator(1, 2) # Create a black image img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('Window') # Draw a diagonal blue line with thickness of 5 px cv2.line(img,(0,0),(511,511),(255,0,0),5) cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) cv2.circle(img,(447,63), 63, (0,0,255), -1) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA) cv2.imshow('Window', img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows()
# Include the directory where cvui is so we can load it import sys sys.path.append('../../../') import numpy as np import cv2 import cvui cvui.random_number_generator(1, 2) # Create a black image img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('Window') # Change background color img[:] = (49, 52, 49) # Draw a diagonal blue line with thickness of 5 px cv2.line(img,(0,0),(511,511),(255,0,0),5) cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) cv2.circle(img,(447,63), 63, (0,0,255), -1) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA) cv2.imshow('Window', img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows()
Add a nice background color
Add a nice background color
Python
mit
Dovyski/cvui,Dovyski/cvui,Dovyski/cvui
--- +++ @@ -13,6 +13,9 @@ cv2.namedWindow('Window') +# Change background color +img[:] = (49, 52, 49) + # Draw a diagonal blue line with thickness of 5 px cv2.line(img,(0,0),(511,511),(255,0,0),5)
3cf4ff417c36dfa6e858265b2a3daea24a1e00f6
openfisca_country_template/entities.py
openfisca_country_template/entities.py
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) """ A group entity. Contains multiple natural persons with specific roles. From zero to two parents with 'first_parent' and 'second_parent' subroles. And an unlimited number of children. """ Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) """ The minimal legal entity on which a legislation might be applied. Represents a natural person. """ entities = [Household, Person]
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', doc = ''' A group entity. Contains multiple natural persons with specific roles. From zero to two parents with 'first_parent' and 'second_parent' subroles. And an unlimited number of children. ''', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) Person = build_entity( key = "person", plural = "persons", label = u'Person', doc = ''' The minimal legal entity on which a legislation might be applied. Represents a natural person. ''', is_person = True, ) entities = [Household, Person]
Add documentation on every entity
Add documentation on every entity
Python
agpl-3.0
openfisca/country-template,openfisca/country-template
--- +++ @@ -8,6 +8,12 @@ key = "household", plural = "households", label = u'Household', + doc = ''' + A group entity. + Contains multiple natural persons with specific roles. + From zero to two parents with 'first_parent' and 'second_parent' subroles. + And an unlimited number of children. + ''', roles = [ { 'key': 'parent', @@ -23,22 +29,18 @@ } ] ) -""" -A group entity. -Contains multiple natural persons with specific roles. -From zero to two parents with 'first_parent' and 'second_parent' subroles. -And an unlimited number of children. -""" + Person = build_entity( key = "person", plural = "persons", label = u'Person', + doc = ''' + The minimal legal entity on which a legislation might be applied. + Represents a natural person. + ''', is_person = True, ) -""" -The minimal legal entity on which a legislation might be applied. -Represents a natural person. -""" + entities = [Household, Person]
a7af81244972ae6ac30bd55260af46b7ce25a6e1
pre_commit_hooks/no_commit_to_branch.py
pre_commit_hooks/no_commit_to_branch.py
from __future__ import print_function import argparse import re from typing import Optional from typing import Sequence from typing import Set from pre_commit_hooks.util import CalledProcessError from pre_commit_hooks.util import cmd_output def is_on_branch(protected, patterns=set()): # type: (Set[str], Set[str]) -> bool try: ref_name = cmd_output('git', 'symbolic-ref', 'HEAD') except CalledProcessError: return False chunks = ref_name.strip().split('/') branch_name = '/'.join(chunks[2:]) return branch_name in protected or any( re.match(p, branch_name) for p in patterns ) def main(argv=None): # type: (Optional[Sequence[str]]) -> int parser = argparse.ArgumentParser() parser.add_argument( '-b', '--branch', action='append', help='branch to disallow commits to, may be specified multiple times', ) parser.add_argument( '-p', '--pattern', action='append', help=( 'regex pattern for branch name to disallow commits to, ' 'May be specified multiple times' ), ) args = parser.parse_args(argv) protected = set(args.branch or ('master',)) patterns = set(args.pattern or ()) return int(is_on_branch(protected, patterns)) if __name__ == '__main__': exit(main())
from __future__ import print_function import argparse import re from typing import FrozenSet from typing import Optional from typing import Sequence from pre_commit_hooks.util import CalledProcessError from pre_commit_hooks.util import cmd_output def is_on_branch(protected, patterns=frozenset()): # type: (FrozenSet[str], FrozenSet[str]) -> bool try: ref_name = cmd_output('git', 'symbolic-ref', 'HEAD') except CalledProcessError: return False chunks = ref_name.strip().split('/') branch_name = '/'.join(chunks[2:]) return branch_name in protected or any( re.match(p, branch_name) for p in patterns ) def main(argv=None): # type: (Optional[Sequence[str]]) -> int parser = argparse.ArgumentParser() parser.add_argument( '-b', '--branch', action='append', help='branch to disallow commits to, may be specified multiple times', ) parser.add_argument( '-p', '--pattern', action='append', help=( 'regex pattern for branch name to disallow commits to, ' 'may be specified multiple times' ), ) args = parser.parse_args(argv) protected = frozenset(args.branch or ('master',)) patterns = frozenset(args.pattern or ()) return int(is_on_branch(protected, patterns)) if __name__ == '__main__': exit(main())
Make optional argument use an immutable set for the default value in no-commit-to-branch. Make other sets immutable to satisfy type-checking and be consistent
Make optional argument use an immutable set for the default value in no-commit-to-branch. Make other sets immutable to satisfy type-checking and be consistent
Python
mit
pre-commit/pre-commit-hooks
--- +++ @@ -2,16 +2,16 @@ import argparse import re +from typing import FrozenSet from typing import Optional from typing import Sequence -from typing import Set from pre_commit_hooks.util import CalledProcessError from pre_commit_hooks.util import cmd_output -def is_on_branch(protected, patterns=set()): - # type: (Set[str], Set[str]) -> bool +def is_on_branch(protected, patterns=frozenset()): + # type: (FrozenSet[str], FrozenSet[str]) -> bool try: ref_name = cmd_output('git', 'symbolic-ref', 'HEAD') except CalledProcessError: @@ -33,13 +33,13 @@ '-p', '--pattern', action='append', help=( 'regex pattern for branch name to disallow commits to, ' - 'May be specified multiple times' + 'may be specified multiple times' ), ) args = parser.parse_args(argv) - protected = set(args.branch or ('master',)) - patterns = set(args.pattern or ()) + protected = frozenset(args.branch or ('master',)) + patterns = frozenset(args.pattern or ()) return int(is_on_branch(protected, patterns))
df24541dc5fff6098c3d3c0d920359c34910221c
tests/test_ratelimit.py
tests/test_ratelimit.py
from disco.test import DiscoJobTestFixture, DiscoTestCase from disco.error import JobError class RateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): inputs = [1] def getdata(self, path): return 'badger\n' * 1000 @staticmethod def map(e, params): msg(e) return [] def runTest(self): self.assertRaises(JobError, self.job.wait) self.assertEquals(self.job.jobinfo()['active'], 'dead') class AnotherRateLimitTestCase(RateLimitTestCase): @staticmethod def map(e, params): return [] def runTest(self): self.job.wait() self.assertEquals(self.job.jobinfo()['active'], 'ready') class YetAnotherRateLimitTestCase(RateLimitTestCase): @staticmethod def map(e, params): for i in xrange(100000): print 'foobar' return []
from disco.test import DiscoJobTestFixture, DiscoTestCase from disco.error import JobError from disco.events import Status class RateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): inputs = [1] def getdata(self, path): return 'badger\n' * 1000 @staticmethod def map(e, params): msg(e) return [] def runTest(self): self.assertRaises(JobError, self.job.wait) self.assertEquals(self.job.jobinfo()['active'], 'dead') class InternalRateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): inputs = [1] def getdata(self, path): return 'badger\n' * 1000 @staticmethod def map(e, params): Status("Internal msg") return [] def runTest(self): self.job.wait() self.assertEquals(self.job.jobinfo()['active'], 'ready') class AnotherRateLimitTestCase(RateLimitTestCase): @staticmethod def map(e, params): return [] def runTest(self): self.job.wait() self.assertEquals(self.job.jobinfo()['active'], 'ready') class YetAnotherRateLimitTestCase(RateLimitTestCase): @staticmethod def map(e, params): for i in xrange(100000): print 'foobar' return []
Add rate-limit test case for internal messages.
Add rate-limit test case for internal messages.
Python
bsd-3-clause
pavlobaron/disco_playground,simudream/disco,pombredanne/disco,pavlobaron/disco_playground,pooya/disco,simudream/disco,ktkt2009/disco,discoproject/disco,pombredanne/disco,simudream/disco,pavlobaron/disco_playground,beni55/disco,mwilliams3/disco,ErikDubbelboer/disco,oldmantaiter/disco,seabirdzh/disco,mozilla/disco,ErikDubbelboer/disco,mozilla/disco,scrapinghub/disco,discoproject/disco,scrapinghub/disco,oldmantaiter/disco,ErikDubbelboer/disco,ktkt2009/disco,seabirdzh/disco,beni55/disco,mozilla/disco,ktkt2009/disco,beni55/disco,beni55/disco,mozilla/disco,ErikDubbelboer/disco,ErikDubbelboer/disco,pavlobaron/disco_playground,seabirdzh/disco,scrapinghub/disco,oldmantaiter/disco,seabirdzh/disco,pombredanne/disco,mwilliams3/disco,pombredanne/disco,scrapinghub/disco,simudream/disco,ktkt2009/disco,discoproject/disco,pooya/disco,mwilliams3/disco,ktkt2009/disco,discoproject/disco,oldmantaiter/disco,simudream/disco,pombredanne/disco,pooya/disco,beni55/disco,oldmantaiter/disco,pooya/disco,mwilliams3/disco,mwilliams3/disco,seabirdzh/disco,discoproject/disco
--- +++ @@ -1,5 +1,6 @@ from disco.test import DiscoJobTestFixture, DiscoTestCase from disco.error import JobError +from disco.events import Status class RateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): inputs = [1] @@ -16,6 +17,21 @@ self.assertRaises(JobError, self.job.wait) self.assertEquals(self.job.jobinfo()['active'], 'dead') +class InternalRateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): + inputs = [1] + + def getdata(self, path): + return 'badger\n' * 1000 + + @staticmethod + def map(e, params): + Status("Internal msg") + return [] + + def runTest(self): + self.job.wait() + self.assertEquals(self.job.jobinfo()['active'], 'ready') + class AnotherRateLimitTestCase(RateLimitTestCase): @staticmethod def map(e, params):
0fa0d792bfc8ea22cd807b3b822edeb67a97943a
examples/connection.py
examples/connection.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. """ Example Connection Command Make sure you can authenticate before running this command. For example: python -m examples.connection """ import sys import os_client_config from examples import common from openstack import connection def make_connection(opts): occ = os_client_config.OpenStackConfig() cloud = occ.get_one_cloud(opts.cloud, opts) auth = cloud.config['auth'] if 'insecure' in cloud.config: auth['verify'] = cloud.config['insecure'] conn = connection.Connection(preference=opts.user_preferences, **auth) return conn def run_connection(opts): conn = make_connection(opts) print("Connection: %s" % conn) for flavor in conn.compute.flavors(): print(flavor.id + " " + flavor.name) return if __name__ == "__main__": opts = common.setup() sys.exit(common.main(opts, run_connection))
# 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. """ Example Connection Command Make sure you can authenticate before running this command. For example: python -m examples.connection """ import sys import os_client_config from examples import common from openstack import connection def make_connection(opts): occ = os_client_config.OpenStackConfig() cloud = occ.get_one_cloud(opts.cloud, opts) opts.user_preferences.set_region(opts.user_preferences.ALL, cloud.region) auth = cloud.config['auth'] if 'insecure' in cloud.config: auth['verify'] = cloud.config['insecure'] conn = connection.Connection(preference=opts.user_preferences, **auth) return conn def run_connection(opts): conn = make_connection(opts) print("Connection: %s" % conn) for flavor in conn.compute.flavors(): print(flavor.id + " " + flavor.name) return if __name__ == "__main__": opts = common.setup() sys.exit(common.main(opts, run_connection))
Enable occ cloud region for example
Enable occ cloud region for example Change-Id: I4f6fb7840b684e024ceca37bc5b7e2c858574665
Python
apache-2.0
dtroyer/python-openstacksdk,dudymas/python-openstacksdk,mtougeron/python-openstacksdk,stackforge/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,mtougeron/python-openstacksdk,dudymas/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk
--- +++ @@ -30,6 +30,7 @@ def make_connection(opts): occ = os_client_config.OpenStackConfig() cloud = occ.get_one_cloud(opts.cloud, opts) + opts.user_preferences.set_region(opts.user_preferences.ALL, cloud.region) auth = cloud.config['auth'] if 'insecure' in cloud.config: auth['verify'] = cloud.config['insecure']
f0c1c078e7edd76b418940f3cbddef405440b5d4
GPflowOpt/_version.py
GPflowOpt/_version.py
# Copyright 2017 Joachim van der Herten # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = "pre-release"
# Copyright 2017 Joachim van der Herten # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = "pre-release" # pragma: no cover
Exclude version file from test coverage
Exclude version file from test coverage
Python
apache-2.0
GPflow/GPflowOpt
--- +++ @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "pre-release" +__version__ = "pre-release" # pragma: no cover
d4b32d8f1beb16f9f7309d1cceb16b37e491bea3
controllers/event_wizard_controller.py
controllers/event_wizard_controller.py
import os from google.appengine.ext.webapp import template from base_controller import CacheableHandler class EventWizardHandler(CacheableHandler): CACHE_VERSION = 1 CACHE_KEY_FORMAT = "event_wizard" def __init__(self, *args, **kw): super(EventWizardHandler, self).__init__(*args, **kw) self.cache_expiration = 60 * 60 def _render(self, *args, **kw): path = os.path.join(os.path.dirname(__file__), "../templates/eventwizard.html") return template.render(path, self.template_values) class ReactEventWizardHandler(CacheableHandler): CACHE_VERSION = 1 CACHE_KEY_FORMAT = "event_wizard" def __init__(self, *args, **kw): super(ReactEventWizardHandler, self).__init__(*args, **kw) self.cache_expiration = 60 * 60 def _render(self, *args, **kw): path = os.path.join(os.path.dirname(__file__), "../templates/react-eventwizard.html") return template.render(path, self.template_values)
import os from google.appengine.ext.webapp import template from base_controller import CacheableHandler class EventWizardHandler(CacheableHandler): CACHE_VERSION = 1 CACHE_KEY_FORMAT = "event_wizard" def __init__(self, *args, **kw): super(EventWizardHandler, self).__init__(*args, **kw) self.cache_expiration = 60 * 60 def _render(self, *args, **kw): path = os.path.join(os.path.dirname(__file__), "../templates/eventwizard.html") return template.render(path, self.template_values) class ReactEventWizardHandler(CacheableHandler): CACHE_VERSION = 1 CACHE_KEY_FORMAT = "event_wizard_react" def __init__(self, *args, **kw): super(ReactEventWizardHandler, self).__init__(*args, **kw) self.cache_expiration = 60 * 60 def _render(self, *args, **kw): path = os.path.join(os.path.dirname(__file__), "../templates/react-eventwizard.html") return template.render(path, self.template_values)
Fix event wizard cache keys
Fix event wizard cache keys
Python
mit
fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance
--- +++ @@ -20,7 +20,7 @@ class ReactEventWizardHandler(CacheableHandler): CACHE_VERSION = 1 - CACHE_KEY_FORMAT = "event_wizard" + CACHE_KEY_FORMAT = "event_wizard_react" def __init__(self, *args, **kw): super(ReactEventWizardHandler, self).__init__(*args, **kw)
b4e29b5e63e4cd93d4244e7a52f772a40f9a7772
testing/util.py
testing/util.py
from __future__ import absolute_import from __future__ import unicode_literals import contextlib import io import os.path TESTING_DIR = os.path.abspath(os.path.dirname(__file__)) @contextlib.contextmanager def cwd(path): pwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(pwd) def get_resource_path(path): return os.path.join(TESTING_DIR, 'resources', path) def write_file(filename, contents): """Hax because coveragepy chokes on nested context managers.""" with io.open(filename, 'w') as file_obj: file_obj.write(contents)
from __future__ import absolute_import from __future__ import unicode_literals import contextlib import io import os.path TESTING_DIR = os.path.abspath(os.path.dirname(__file__)) @contextlib.contextmanager def cwd(path): pwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(pwd) def get_resource_path(path): return os.path.join(TESTING_DIR, 'resources', path) def write_file(filename, contents): """Hax because coveragepy chokes on nested context managers.""" with io.open(filename, 'w', newline='') as file_obj: file_obj.write(contents)
Use newline='' to avoid automatic newline translation
Use newline='' to avoid automatic newline translation
Python
mit
pre-commit/pre-commit-hooks,Harwood/pre-commit-hooks,Coverfox/pre-commit-hooks
--- +++ @@ -25,5 +25,5 @@ def write_file(filename, contents): """Hax because coveragepy chokes on nested context managers.""" - with io.open(filename, 'w') as file_obj: + with io.open(filename, 'w', newline='') as file_obj: file_obj.write(contents)
27fde5a910c5274e6f56bbb0b46dbb375822296d
server/lib/python/cartodb_services/cartodb_services/google/client_factory.py
server/lib/python/cartodb_services/cartodb_services/google/client_factory.py
#!/usr/local/bin/python # -*- coding: utf-8 -*- import googlemaps import base64 from exceptions import InvalidGoogleCredentials class GoogleMapsClientFactory(): clients = {} @classmethod def get(cls, client_id, client_secret): client = cls.clients.get(client_id) if not client: cls.assert_valid_crendentials(client_secret) client = googlemaps.Client( client_id=client_id, client_secret=client_secret) cls.clients[client_id] = client return client @classmethod def assert_valid_crendentials(cls, client_secret): if not cls.valid_credentials(client_secret): raise InvalidGoogleCredentials @staticmethod def valid_credentials(client_secret): try: # Only fails if the string dont have a correct padding for b64 # but this way we could provide a more clear error than # TypeError: Incorrect padding b64_secret = client_secret.replace('-', '+').replace('_', '/') base64.b64decode(b64_secret) return True except TypeError: return False
#!/usr/local/bin/python # -*- coding: utf-8 -*- import googlemaps import base64 from exceptions import InvalidGoogleCredentials class GoogleMapsClientFactory(): clients = {} @classmethod def get(cls, client_id, client_secret): cache_key = "{}:{}".format(client_id, client_secret) client = cls.clients.get(cache_key) if not client: cls.assert_valid_crendentials(client_secret) client = googlemaps.Client( client_id=client_id, client_secret=client_secret) cls.clients[cache_key] = client return client @classmethod def assert_valid_crendentials(cls, client_secret): if not cls.valid_credentials(client_secret): raise InvalidGoogleCredentials @staticmethod def valid_credentials(client_secret): try: # Only fails if the string dont have a correct padding for b64 # but this way we could provide a more clear error than # TypeError: Incorrect padding b64_secret = client_secret.replace('-', '+').replace('_', '/') base64.b64decode(b64_secret) return True except TypeError: return False
Use "{id}:{secret}" as caching key
Use "{id}:{secret}" as caching key
Python
bsd-3-clause
CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/dataservices-api
--- +++ @@ -10,13 +10,14 @@ @classmethod def get(cls, client_id, client_secret): - client = cls.clients.get(client_id) + cache_key = "{}:{}".format(client_id, client_secret) + client = cls.clients.get(cache_key) if not client: cls.assert_valid_crendentials(client_secret) client = googlemaps.Client( client_id=client_id, client_secret=client_secret) - cls.clients[client_id] = client + cls.clients[cache_key] = client return client @classmethod
c057f4865052c893af9abcae2c2f37ec02d56118
example_test_set/tests/test_set_root.py
example_test_set/tests/test_set_root.py
# test set for plugin testing # from IPython import embed import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) @pytest.yield_fixture(params=[1, 2, 3]) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2
# test set for plugin testing # from IPython import embed import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) @pytest.yield_fixture(params=['dog', 'cat', 'mouse']) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2
Tweak some example fixture ids
Tweak some example fixture ids
Python
mit
tgoodlet/pytest-interactive
--- +++ @@ -33,7 +33,7 @@ dut.set_mode(orig_mode) -@pytest.yield_fixture(params=[1, 2, 3]) +@pytest.yield_fixture(params=['dog', 'cat', 'mouse']) def inputs(request): yield request.param
d05db8b8074503d927847272f53b32edc42fe043
geotrek/trekking/apps.py
geotrek/trekking/apps.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking")
from django.apps import AppConfig from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") def ready(self): from .forms import TrekForm def check_hidden_fields_settings(app_configs, **kwargs): # Check all Forms hidden fields settings errors = TrekForm.check_fields_to_hide() return errors register(check_hidden_fields_settings, Tags.security)
Add system checks for Trek form
Add system checks for Trek form
Python
bsd-2-clause
makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
--- +++ @@ -1,7 +1,18 @@ from django.apps import AppConfig +from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") + + def ready(self): + from .forms import TrekForm + + def check_hidden_fields_settings(app_configs, **kwargs): + # Check all Forms hidden fields settings + errors = TrekForm.check_fields_to_hide() + return errors + + register(check_hidden_fields_settings, Tags.security)
8402244112dfbd45f6d05ba5f89c7311a019fbe7
web/portal/views/home.py
web/portal/views/home.py
from flask import redirect, url_for from portal import app @app.route('/', methods=['GET']) def index(): return redirect(url_for('practices_index'))
from flask import redirect, url_for from portal import app @app.route('/', methods=['GET']) def index(): return redirect(url_for('practices_index', _external=True))
Fix incorrect protocol being using when behin reverse proxy
Fix incorrect protocol being using when behin reverse proxy
Python
mit
LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal
--- +++ @@ -3,4 +3,4 @@ @app.route('/', methods=['GET']) def index(): - return redirect(url_for('practices_index')) + return redirect(url_for('practices_index', _external=True))
affae124162f03ce8783ced01916c11777cff25f
flocker/cli/test/test_deploy_script.py
flocker/cli/test/test_deploy_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Unit tests for the implementation ``flocker-deploy``. """ from twisted.trial.unittest import TestCase, SynchronousTestCase from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin from ..script import DeployScript, DeployOptions class FlockerDeployTests(FlockerScriptTestsMixin, TestCase): """Tests for ``flocker-deploy``.""" script = DeployScript options = DeployOptions command_name = u'flocker-deploy' class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase): """Tests for :class:`DeployOptions`.""" options = DeployOptions class FlockerDeployMainTests(SynchronousTestCase): """ Tests for ``DeployScript.main``. """ def test_deferred_result(self): """ ``DeployScript.main`` returns ``True`` on success. """ script = DeployScript() self.assertTrue(script.main(reactor=object(), options={}))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Unit tests for the implementation ``flocker-deploy``. """ from twisted.trial.unittest import TestCase, SynchronousTestCase from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin from ..script import DeployScript, DeployOptions class FlockerDeployTests(FlockerScriptTestsMixin, TestCase): """Tests for ``flocker-deploy``.""" script = DeployScript options = DeployOptions command_name = u'flocker-deploy' class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase): """Tests for :class:`DeployOptions`.""" options = DeployOptions def test_custom_configs(self): """Custom config files can be specified.""" options = self.options() options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"]) self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"}) class FlockerDeployMainTests(SynchronousTestCase): """ Tests for ``DeployScript.main``. """ def test_success(self): """ ``DeployScript.main`` returns ``True`` on success. """ script = DeployScript() self.assertTrue(script.main(reactor=object(), options={}))
Test that DeployOptions sets two options
Test that DeployOptions sets two options
Python
apache-2.0
mbrukman/flocker,runcom/flocker,LaynePeng/flocker,w4ngyi/flocker,LaynePeng/flocker,AndyHuu/flocker,hackday-profilers/flocker,runcom/flocker,achanda/flocker,achanda/flocker,Azulinho/flocker,1d4Nf6/flocker,lukemarsden/flocker,runcom/flocker,AndyHuu/flocker,hackday-profilers/flocker,agonzalezro/flocker,Azulinho/flocker,moypray/flocker,hackday-profilers/flocker,agonzalezro/flocker,LaynePeng/flocker,lukemarsden/flocker,jml/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,Azulinho/flocker,adamtheturtle/flocker,AndyHuu/flocker,moypray/flocker,beni55/flocker,1d4Nf6/flocker,jml/flocker,mbrukman/flocker,beni55/flocker,achanda/flocker,w4ngyi/flocker,agonzalezro/flocker,mbrukman/flocker,wallnerryan/flocker-profiles,jml/flocker,moypray/flocker,beni55/flocker,1d4Nf6/flocker,adamtheturtle/flocker,w4ngyi/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles
--- +++ @@ -21,14 +21,21 @@ """Tests for :class:`DeployOptions`.""" options = DeployOptions + def test_custom_configs(self): + """Custom config files can be specified.""" + options = self.options() + options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"]) + self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"}) + class FlockerDeployMainTests(SynchronousTestCase): """ Tests for ``DeployScript.main``. """ - def test_deferred_result(self): + def test_success(self): """ ``DeployScript.main`` returns ``True`` on success. """ script = DeployScript() self.assertTrue(script.main(reactor=object(), options={})) +
ba10a22c47ec2f6a27ddbc1cbddbfe8ec31e9955
netdumplings/__init__.py
netdumplings/__init__.py
from .dumpling import Dumpling, DumplingDriver from .dumplingchef import DumplingChef from .dumplingeater import DumplingEater from .dumplinghub import DumplingHub from .dumplingkitchen import DumplingKitchen from ._version import __version__ # Workaround to avoid F401 "imported but unused" linter errors. ( Dumpling, DumplingDriver, DumplingChef, DumplingEater, DumplingHub, DumplingKitchen, __version__, )
from .dumpling import Dumpling, DumplingDriver from .dumplingchef import DumplingChef from .dumplingeater import DumplingEater from .exceptions import ( InvalidDumpling, InvalidDumplingPayload, NetDumplingsError, ) from .dumplinghub import DumplingHub from .dumplingkitchen import DumplingKitchen from ._version import __version__ # Workaround to avoid F401 "imported but unused" linter errors. ( Dumpling, DumplingDriver, DumplingChef, DumplingEater, DumplingHub, DumplingKitchen, InvalidDumpling, InvalidDumplingPayload, NetDumplingsError, __version__, )
Make exceptions available at top-level netdumplings module
Make exceptions available at top-level netdumplings module
Python
mit
mjoblin/netdumplings,mjoblin/netdumplings,mjoblin/netdumplings
--- +++ @@ -1,6 +1,9 @@ from .dumpling import Dumpling, DumplingDriver from .dumplingchef import DumplingChef from .dumplingeater import DumplingEater +from .exceptions import ( + InvalidDumpling, InvalidDumplingPayload, NetDumplingsError, +) from .dumplinghub import DumplingHub from .dumplingkitchen import DumplingKitchen from ._version import __version__ @@ -13,5 +16,8 @@ DumplingEater, DumplingHub, DumplingKitchen, + InvalidDumpling, + InvalidDumplingPayload, + NetDumplingsError, __version__, )
5564ed32acd3baae009096b2240190ff485a0431
cms/admin/utils.py
cms/admin/utils.py
from django.template import loader, Context, TemplateDoesNotExist from django.template.loader_tags import ExtendsNode from cms.utils import get_template_from_request import re # must be imported like this for isinstance from django.templatetags.cms_tags import PlaceholderNode #do not remove def get_placeholders(request, template_name): """ Return a list of PlaceholderNode found in the given template """ try: temp = loader.get_template(template_name) except TemplateDoesNotExist: return [] context = Context()#RequestContext(request)#details(request, no404=True, only_context=True) template = get_template_from_request(request) request.current_page = "dummy" context.update({'template':template, 'request':request, 'display_placeholder_names_only': True, }) # lacks - it requests context in admin and eats user messages, # standard context will be hopefully enough here # temp.render(RequestContext(request, context)) output = temp.render(context) return re.findall("<!-- PlaceholderNode: (\w+?) -->", output)
from django.template import loader, Context, TemplateDoesNotExist from django.template.loader_tags import ExtendsNode from cms.utils import get_template_from_request import re # must be imported like this for isinstance from django.templatetags.cms_tags import PlaceholderNode #do not remove def get_placeholders(request, template_name): """ Return a list of PlaceholderNode found in the given template """ try: temp = loader.get_template(template_name) except TemplateDoesNotExist: return [] context = Context()#RequestContext(request)#details(request, no404=True, only_context=True) template = get_template_from_request(request) request.current_page = "dummy" context.update({'template':template, 'request':request, 'display_placeholder_names_only': True, }) # lacks - it requests context in admin and eats user messages, # standard context will be hopefully enough here # temp.render(RequestContext(request, context)) output = temp.render(context) return re.findall("<!-- PlaceholderNode: (.*?) -->", output)
Allow other characters in placeholder name
Allow other characters in placeholder name
Python
bsd-3-clause
ojii/django-cms,dhorelik/django-cms,intip/django-cms,iddqd1/django-cms,bittner/django-cms,petecummings/django-cms,stefanfoulis/django-cms,benzkji/django-cms,leture/django-cms,selecsosi/django-cms,mkoistinen/django-cms,robmagee/django-cms,vad/django-cms,driesdesmet/django-cms,wuzhihui1123/django-cms,evildmp/django-cms,timgraham/django-cms,jsma/django-cms,yakky/django-cms,saintbird/django-cms,donce/django-cms,ojii/django-cms,11craft/django-cms,astagi/django-cms,yakky/django-cms,irudayarajisawa/django-cms,datakortet/django-cms,wyg3958/django-cms,jrief/django-cms,keimlink/django-cms,webu/django-cms,chkir/django-cms,VillageAlliance/django-cms,pbs/django-cms,AlexProfi/django-cms,jproffitt/django-cms,VillageAlliance/django-cms,netzkolchose/django-cms,wuzhihui1123/django-cms,jsma/django-cms,keimlink/django-cms,ScholzVolkmer/django-cms,nimbis/django-cms,frnhr/django-cms,nimbis/django-cms,chmberl/django-cms,Livefyre/django-cms,benzkji/django-cms,chrisglass/django-cms,irudayarajisawa/django-cms,vstoykov/django-cms,rsalmaso/django-cms,foobacca/django-cms,cyberintruder/django-cms,Livefyre/django-cms,datakortet/django-cms,FinalAngel/django-cms,jsma/django-cms,intgr/django-cms,pancentric/django-cms,cyberintruder/django-cms,chkir/django-cms,petecummings/django-cms,robmagee/django-cms,stefanfoulis/django-cms,kk9599/django-cms,takeshineshiro/django-cms,intgr/django-cms,liuyisiyisi/django-cms,webu/django-cms,timgraham/django-cms,mkoistinen/django-cms,jrclaramunt/django-cms,benzkji/django-cms,farhaadila/django-cms,jeffreylu9/django-cms,ScholzVolkmer/django-cms,wuzhihui1123/django-cms,rsalmaso/django-cms,leture/django-cms,MagicSolutions/django-cms,saintbird/django-cms,Vegasvikk/django-cms,jalaziz/django-cms-grappelli-old,stefanw/django-cms,kk9599/django-cms,vad/django-cms,memnonila/django-cms,nostalgiaz/django-cms,yakky/django-cms,rryan/django-cms,rryan/django-cms,sephii/django-cms,vstoykov/django-cms,jproffitt/django-cms,intip/django-cms,selecsosi/django-cms,sephii/django-cms,foobacca/django-cms,DylannCordel/django-cms,stefanfoulis/django-cms,SinnerSchraderMobileMirrors/django-cms,SofiaReis/django-cms,rryan/django-cms,keimlink/django-cms,vxsx/django-cms,rscnt/django-cms,josjevv/django-cms,netzkolchose/django-cms,driesdesmet/django-cms,astagi/django-cms,qnub/django-cms,sznekol/django-cms,divio/django-cms,VillageAlliance/django-cms,youprofit/django-cms,liuyisiyisi/django-cms,jeffreylu9/django-cms,nostalgiaz/django-cms,andyzsf/django-cms,11craft/django-cms,stefanw/django-cms,emiquelito/django-cms-2.0,foobacca/django-cms,netzkolchose/django-cms,sznekol/django-cms,stefanfoulis/django-cms,kk9599/django-cms,wuzhihui1123/django-cms,vad/django-cms,saintbird/django-cms,dhorelik/django-cms,adaptivelogic/django-cms,frnhr/django-cms,benzkji/django-cms,netzkolchose/django-cms,SofiaReis/django-cms,jeffreylu9/django-cms,ojii/django-cms,intip/django-cms,evildmp/django-cms,vad/django-cms,bittner/django-cms,wyg3958/django-cms,evildmp/django-cms,vxsx/django-cms,jrief/django-cms,memnonila/django-cms,SmithsonianEnterprises/django-cms,pancentric/django-cms,jalaziz/django-cms-grappelli-old,iddqd1/django-cms,andyzsf/django-cms,andyzsf/django-cms,SinnerSchraderMobileMirrors/django-cms,rryan/django-cms,nimbis/django-cms,Vegasvikk/django-cms,intip/django-cms,DylannCordel/django-cms,SachaMPS/django-cms,leture/django-cms,nimbis/django-cms,iddqd1/django-cms,robmagee/django-cms,Jaccorot/django-cms,adaptivelogic/django-cms,frnhr/django-cms,evildmp/django-cms,Livefyre/django-cms,rscnt/django-cms,pixbuffer/django-cms,FinalAngel/django-cms,selecsosi/django-cms,qnub/django-cms,SmithsonianEnterprises/django-cms,philippze/django-cms,bittner/django-cms,takeshineshiro/django-cms,frnhr/django-cms,stefanw/django-cms,rsalmaso/django-cms,SachaMPS/django-cms,nostalgiaz/django-cms,divio/django-cms,isotoma/django-cms,selecsosi/django-cms,pancentric/django-cms,jeffreylu9/django-cms,rscnt/django-cms,owers19856/django-cms,Jaccorot/django-cms,datakortet/django-cms,jrclaramunt/django-cms,chrisglass/django-cms,jrclaramunt/django-cms,jrief/django-cms,jsma/django-cms,ScholzVolkmer/django-cms,isotoma/django-cms,czpython/django-cms,vxsx/django-cms,mkoistinen/django-cms,farhaadila/django-cms,intgr/django-cms,czpython/django-cms,chmberl/django-cms,AlexProfi/django-cms,webu/django-cms,vstoykov/django-cms,dhorelik/django-cms,SmithsonianEnterprises/django-cms,intgr/django-cms,mkoistinen/django-cms,philippze/django-cms,memnonila/django-cms,SofiaReis/django-cms,Vegasvikk/django-cms,takeshineshiro/django-cms,foobacca/django-cms,chkir/django-cms,MagicSolutions/django-cms,petecummings/django-cms,360youlun/django-cms,pixbuffer/django-cms,yakky/django-cms,jproffitt/django-cms,SachaMPS/django-cms,jrief/django-cms,donce/django-cms,czpython/django-cms,timgraham/django-cms,owers19856/django-cms,adaptivelogic/django-cms,Jaccorot/django-cms,pbs/django-cms,jalaziz/django-cms-grappelli-old,bittner/django-cms,pbs/django-cms,astagi/django-cms,11craft/django-cms,DylannCordel/django-cms,emiquelito/django-cms-2.0,divio/django-cms,isotoma/django-cms,cyberintruder/django-cms,donce/django-cms,sephii/django-cms,qnub/django-cms,irudayarajisawa/django-cms,driesdesmet/django-cms,youprofit/django-cms,czpython/django-cms,FinalAngel/django-cms,rsalmaso/django-cms,farhaadila/django-cms,andyzsf/django-cms,emiquelito/django-cms-2.0,MagicSolutions/django-cms,sznekol/django-cms,wyg3958/django-cms,vxsx/django-cms,jproffitt/django-cms,josjevv/django-cms,owers19856/django-cms,pixbuffer/django-cms,chmberl/django-cms,sephii/django-cms,stefanw/django-cms,FinalAngel/django-cms,josjevv/django-cms,liuyisiyisi/django-cms,youprofit/django-cms,11craft/django-cms,divio/django-cms,datakortet/django-cms,Livefyre/django-cms,SinnerSchraderMobileMirrors/django-cms,360youlun/django-cms,pbs/django-cms,philippze/django-cms,nostalgiaz/django-cms,isotoma/django-cms,AlexProfi/django-cms,360youlun/django-cms
--- +++ @@ -26,4 +26,4 @@ # temp.render(RequestContext(request, context)) output = temp.render(context) - return re.findall("<!-- PlaceholderNode: (\w+?) -->", output) + return re.findall("<!-- PlaceholderNode: (.*?) -->", output)
82700c4a5d11f01b971b8c031d8864cff2737f0e
accounts/models.py
accounts/models.py
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.set_unusable_password()
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin) class UserManager(BaseUserManager): def create_user(self, email): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email) ) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = 'email' def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.set_unusable_password()
Add user manager to pass token tests
Add user manager to pass token tests
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
--- +++ @@ -1,9 +1,25 @@ from django.db import models -from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin +from django.contrib.auth.models import ( + BaseUserManager, AbstractBaseUser, PermissionsMixin) + + +class UserManager(BaseUserManager): + def create_user(self, email): + if not email: + raise ValueError('Users must have an email address') + + user = self.model( + email=self.normalize_email(email) + ) + + user.save(using=self._db) + return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) + + objects = UserManager() USERNAME_FIELD = 'email'
12b6814e558402032e0c12170c678657f1455d08
kpi/deployment_backends/mock_backend.py
kpi/deployment_backends/mock_backend.py
#!/usr/bin/python # -*- coding: utf-8 -*- from base_backend import BaseDeploymentBackend class MockDeploymentBackend(BaseDeploymentBackend): ''' only used for unit testing and interface testing. defines the interface for a deployment backend. ''' def connect(self, identifier=None, active=False): if not identifier: identifier = '/assets/%s/deployment/' % self.asset.uid self.store_data({ 'backend': 'mock', 'identifier': identifier, 'active': active, }) def set_active(self, active): self.store_data({ 'active': bool(active), })
#!/usr/bin/python # -*- coding: utf-8 -*- from base_backend import BaseDeploymentBackend class MockDeploymentBackend(BaseDeploymentBackend): ''' only used for unit testing and interface testing. defines the interface for a deployment backend. ''' def connect(self, identifier=None, active=False): if not identifier: identifier = '/assets/%s/deployment/' % self.asset.uid self.store_data({ 'backend': 'mock', 'identifier': identifier, 'active': active, }) def set_active(self, active): self.store_data({ 'active': bool(active), }) def get_enketo_survey_links(self): # `self` is a demo Enketo form, but there's no guarantee it'll be # around forever. return { 'url': 'https://enke.to/::self', 'iframe_url': 'https://enke.to/i/::self', 'offline_url': 'https://enke.to/_/#self', 'preview_url': 'https://enke.to/preview/::self', 'preview_iframe_url': 'https://enke.to/preview/i/::self', }
Add `get_enketo_survey_links` to mock backend
Add `get_enketo_survey_links` to mock backend
Python
agpl-3.0
onaio/kpi,onaio/kpi,kobotoolbox/kpi,onaio/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,onaio/kpi
--- +++ @@ -23,3 +23,14 @@ self.store_data({ 'active': bool(active), }) + + def get_enketo_survey_links(self): + # `self` is a demo Enketo form, but there's no guarantee it'll be + # around forever. + return { + 'url': 'https://enke.to/::self', + 'iframe_url': 'https://enke.to/i/::self', + 'offline_url': 'https://enke.to/_/#self', + 'preview_url': 'https://enke.to/preview/::self', + 'preview_iframe_url': 'https://enke.to/preview/i/::self', + }
4d4148ea831d425327a3047ebb9be8c3129eaff6
health_check/contrib/celery/backends.py
health_check/contrib/celery/backends.py
from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3) try: result = add.apply_async( args=[4, 4], expires=timeout, queue=self.queue ) result.get(timeout=timeout) if result.result != 8: self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result")) except IOError as e: self.add_error(ServiceUnavailable("IOError"), e) except NotImplementedError as e: self.add_error(ServiceUnavailable("NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"), e) except BaseException as e: self.add_error(ServiceUnavailable("Unknown error"), e)
from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3) try: result = add.apply_async( args=[4, 4], expires=timeout, queue=self.queue ) result.get(timeout=timeout) if result.result != 8: self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result")) add.forget() except IOError as e: self.add_error(ServiceUnavailable("IOError"), e) except NotImplementedError as e: self.add_error(ServiceUnavailable("NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"), e) except BaseException as e: self.add_error(ServiceUnavailable("Unknown error"), e)
Clean results task Health Check
Clean results task Health Check
Python
mit
KristianOellegaard/django-health-check,KristianOellegaard/django-health-check
--- +++ @@ -21,6 +21,7 @@ result.get(timeout=timeout) if result.result != 8: self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result")) + add.forget() except IOError as e: self.add_error(ServiceUnavailable("IOError"), e) except NotImplementedError as e:
d87491bbc8262b6d448e946d99cb523689f8ef5a
vesper/external_urls.py
vesper/external_urls.py
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
Change doc setting for development.
Change doc setting for development.
Python
mit
HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper
--- +++ @@ -6,7 +6,7 @@ import vesper.version as vesper_version -_USE_LATEST_DOCUMENTATION_VERSION = False +_USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release."""
7a3ee543960495ed720cfcaccbbe7a8afcfed0dd
l10n_br_coa_generic/hooks.py
l10n_br_coa_generic/hooks.py
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): env.user.company_id = env.ref( 'l10n_br_fiscal.empresa_lucro_presumido') coa_generic_tmpl.try_loading_for_current_company()
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): user_admin = env.ref('base.user_admin') user_admin.company_id = env.ref( 'l10n_br_base.empresa_lucro_presumido') coa_generic_tmpl.sudo( user=user_admin.id).try_loading_for_current_company() user_admin.company_id = env.ref('base.main_company')
Use admin user to create COA
[FIX] l10n_br_coa_generic: Use admin user to create COA
Python
agpl-3.0
akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil
--- +++ @@ -18,6 +18,9 @@ # Load COA to Demo Company if not tools.config.get('without_demo'): - env.user.company_id = env.ref( - 'l10n_br_fiscal.empresa_lucro_presumido') - coa_generic_tmpl.try_loading_for_current_company() + user_admin = env.ref('base.user_admin') + user_admin.company_id = env.ref( + 'l10n_br_base.empresa_lucro_presumido') + coa_generic_tmpl.sudo( + user=user_admin.id).try_loading_for_current_company() + user_admin.company_id = env.ref('base.main_company')
fefd2ed137c59830fb3f8872beec8cac8c8e5cc7
aiohttp/signals.py
aiohttp/signals.py
from inspect import signature import asyncio class Signal(object): def __init__(self, parameters): self._parameters = frozenset(parameters) self._receivers = set() def connect(self, receiver): # Check that the callback can be called with the given parameter names if __debug__: signature(receiver).bind(**{p: None for p in self._parameters}) self._receivers.add(receiver) def disconnect(self, receiver): self._receivers.remove(receiver) def send(self, **kwargs): for receiver in self._receivers: receiver(**kwargs) class AsyncSignal(Signal): def connect(self, receiver): assert asyncio.iscoroutinefunction(receiver), receiver super().connect(receiver) @asyncio.coroutine def send(self, **kwargs): for receiver in self._receivers: yield from receiver(**kwargs)
from inspect import signature import asyncio class Signal(object): def __init__(self, parameters): self._parameters = frozenset(parameters) self._receivers = set() def connect(self, receiver): # Check that the callback can be called with the given parameter names if __debug__: signature(receiver).bind(**{p: None for p in self._parameters}) self._receivers.add(receiver) def disconnect(self, receiver): self._receivers.remove(receiver) def send(self, **kwargs): for receiver in self._receivers: receiver(**kwargs) class CoroutineSignal(Signal): def connect(self, receiver): assert asyncio.iscoroutinefunction(receiver), receiver super().connect(receiver) @asyncio.coroutine def send(self, **kwargs): for receiver in self._receivers: yield from receiver(**kwargs)
Rename AsyncSignal to CoroutineSignal for clarity of purpose
Rename AsyncSignal to CoroutineSignal for clarity of purpose
Python
apache-2.0
rutsky/aiohttp,rutsky/aiohttp,z2v/aiohttp,esaezgil/aiohttp,pfreixes/aiohttp,decentfox/aiohttp,AraHaanOrg/aiohttp,panda73111/aiohttp,panda73111/aiohttp,playpauseandstop/aiohttp,hellysmile/aiohttp,jashandeep-sohi/aiohttp,elastic-coders/aiohttp,jashandeep-sohi/aiohttp,singulared/aiohttp,Eyepea/aiohttp,vaskalas/aiohttp,esaezgil/aiohttp,alex-eri/aiohttp-1,moden-py/aiohttp,mind1master/aiohttp,elastic-coders/aiohttp,hellysmile/aiohttp,arthurdarcet/aiohttp,vaskalas/aiohttp,singulared/aiohttp,mind1master/aiohttp,jettify/aiohttp,KeepSafe/aiohttp,juliatem/aiohttp,panda73111/aiohttp,alex-eri/aiohttp-1,decentfox/aiohttp,alex-eri/aiohttp-1,arthurdarcet/aiohttp,singulared/aiohttp,decentfox/aiohttp,z2v/aiohttp,elastic-coders/aiohttp,KeepSafe/aiohttp,jashandeep-sohi/aiohttp,KeepSafe/aiohttp,jettify/aiohttp,mind1master/aiohttp,juliatem/aiohttp,esaezgil/aiohttp,Insoleet/aiohttp,vaskalas/aiohttp,rutsky/aiohttp,arthurdarcet/aiohttp,jettify/aiohttp,AraHaanOrg/aiohttp,moden-py/aiohttp,pfreixes/aiohttp,z2v/aiohttp,moden-py/aiohttp
--- +++ @@ -20,7 +20,7 @@ for receiver in self._receivers: receiver(**kwargs) -class AsyncSignal(Signal): +class CoroutineSignal(Signal): def connect(self, receiver): assert asyncio.iscoroutinefunction(receiver), receiver super().connect(receiver)
9efe4325e685b040a4af87a65e0885b950b0cc5a
pa11ycrawler/settings.py
pa11ycrawler/settings.py
# -*- coding: utf-8 -*- """ Scrapy settings for a11y project For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: http://doc.scrapy.org/en/latest/topics/settings.html http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html """ # Main settings used by crawler: handle with care! -------- SPIDER_MODULES = ['pa11ycrawler.spiders'] NEWSPIDER_MODULE = 'pa11ycrawler.spiders' DEFAULT_ITEM_CLASS = 'pa11ycrawler.items.A11yItem' # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'pa11ycrawler.pipelines.DuplicatesPipeline': 200, 'pa11ycrawler.pipelines.DropDRFPipeline': 250, 'pa11ycrawler.pipelines.Pa11yPipeline': 300, } # Other items you are likely to want to override --------------- CONCURRENT_REQUESTS = 16 CONCURRENT_REQUESTS_PER_DOMAIN = 8 COOKIES_DEBUG = False COOKIES_ENABLED = True DEPTH_LIMIT = 2 LOG_LEVEL = 'INFO' LOG_FORMAT = '%(asctime)s [%(levelname)s] [%(name)s]: %(message)s'
# -*- coding: utf-8 -*- """ Scrapy settings for a11y project For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: http://doc.scrapy.org/en/latest/topics/settings.html http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html """ # Main settings used by crawler: handle with care! -------- SPIDER_MODULES = ['pa11ycrawler.spiders'] NEWSPIDER_MODULE = 'pa11ycrawler.spiders' DEFAULT_ITEM_CLASS = 'pa11ycrawler.items.A11yItem' # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'pa11ycrawler.pipelines.DuplicatesPipeline': 200, 'pa11ycrawler.pipelines.DropDRFPipeline': 250, 'pa11ycrawler.pipelines.Pa11yPipeline': 300, } # Other items you are likely to want to override --------------- CONCURRENT_REQUESTS = 16 CONCURRENT_REQUESTS_PER_DOMAIN = 8 COOKIES_DEBUG = False COOKIES_ENABLED = True DEPTH_LIMIT = 6 LOG_LEVEL = 'INFO' LOG_FORMAT = '%(asctime)s [%(levelname)s] [%(name)s]: %(message)s'
Increase max depth to 6
Increase max depth to 6 At 2, it only has enough depth to log in.
Python
apache-2.0
singingwolfboy/pa11ycrawler,singingwolfboy/pa11ycrawler,singingwolfboy/pa11ycrawler
--- +++ @@ -28,6 +28,6 @@ CONCURRENT_REQUESTS_PER_DOMAIN = 8 COOKIES_DEBUG = False COOKIES_ENABLED = True -DEPTH_LIMIT = 2 +DEPTH_LIMIT = 6 LOG_LEVEL = 'INFO' LOG_FORMAT = '%(asctime)s [%(levelname)s] [%(name)s]: %(message)s'
93057b0bf30e1d4c4449fb5f3322042bf74d76e5
satchmo/shop/management/commands/satchmo_copy_static.py
satchmo/shop/management/commands/satchmo_copy_static.py
from django.core.management.base import NoArgsCommand import os import shutil class Command(NoArgsCommand): help = "Copy the satchmo static directory and files to the local project." def handle_noargs(self, **options): import satchmo static_src = os.path.join(satchmo.__path__[0],'static') static_dest = os.path.join(os.getcwd(), 'static') shutil.copytree(static_src, static_dest) print "Copied %s to %s" % (static_src, static_dest)
from django.core.management.base import NoArgsCommand import os import shutil class Command(NoArgsCommand): help = "Copy the satchmo static directory and files to the local project." def handle_noargs(self, **options): import satchmo static_src = os.path.join(satchmo.__path__[0],'static') static_dest = os.path.join(os.getcwd(), 'static') if os.path.exists(static_dest): print "Static directory exists. You must manually copy the files you need." else: shutil.copytree(static_src, static_dest) print "Copied %s to %s" % (static_src, static_dest)
Add an error check to static copying
Add an error check to static copying
Python
bsd-3-clause
grengojbo/satchmo,grengojbo/satchmo
--- +++ @@ -9,5 +9,8 @@ import satchmo static_src = os.path.join(satchmo.__path__[0],'static') static_dest = os.path.join(os.getcwd(), 'static') - shutil.copytree(static_src, static_dest) - print "Copied %s to %s" % (static_src, static_dest) + if os.path.exists(static_dest): + print "Static directory exists. You must manually copy the files you need." + else: + shutil.copytree(static_src, static_dest) + print "Copied %s to %s" % (static_src, static_dest)
5d5d2e90e821a7d377e23d63bc0c7fbba223a1d7
easy_thumbnails/signals.py
easy_thumbnails/signals.py
import django.dispatch saved_file = django.dispatch.Signal(providing_args=['fieldfile']) """ A signal sent for each ``FileField`` saved when a model is saved. * The ``sender`` argument will be the model class. * The ``fieldfile`` argument will be the instance of the field's file that was saved. """ thumbnail_created = django.dispatch.Signal() """ A signal that gets sent every time a new thumbnail is created. * The ``sender`` argument is the created ``ThumbnailFile`` """ thumbnail_missed = django.dispatch.Signal( providing_args=['options', 'high_resolution']) """ A signal that gets sent whenever a thumbnail is passively requested (i.e. when no render-time generation is wanted, via the ``generate=False`` argument). * The ``sender`` argument is the ``Thumbnailer`` * The ``options`` are the thumbnail options requested. * The ``high_resolution`` boolean argument is set to ``True`` if this is the 2x resolution thumbnail that was missed. """
import django.dispatch saved_file = django.dispatch.Signal() """ A signal sent for each ``FileField`` saved when a model is saved. * The ``sender`` argument will be the model class. * The ``fieldfile`` argument will be the instance of the field's file that was saved. """ thumbnail_created = django.dispatch.Signal() """ A signal that gets sent every time a new thumbnail is created. * The ``sender`` argument is the created ``ThumbnailFile`` """ thumbnail_missed = django.dispatch.Signal() """ A signal that gets sent whenever a thumbnail is passively requested (i.e. when no render-time generation is wanted, via the ``generate=False`` argument). * The ``sender`` argument is the ``Thumbnailer`` * The ``options`` are the thumbnail options requested. * The ``high_resolution`` boolean argument is set to ``True`` if this is the 2x resolution thumbnail that was missed. """
Fix RemovedInDjango40Warning: The providing_args argument is deprecated. As it is purely documentational, it has no replacement
Fix RemovedInDjango40Warning: The providing_args argument is deprecated. As it is purely documentational, it has no replacement
Python
bsd-3-clause
SmileyChris/easy-thumbnails
--- +++ @@ -1,6 +1,6 @@ import django.dispatch -saved_file = django.dispatch.Signal(providing_args=['fieldfile']) +saved_file = django.dispatch.Signal() """ A signal sent for each ``FileField`` saved when a model is saved. @@ -16,8 +16,7 @@ * The ``sender`` argument is the created ``ThumbnailFile`` """ -thumbnail_missed = django.dispatch.Signal( - providing_args=['options', 'high_resolution']) +thumbnail_missed = django.dispatch.Signal() """ A signal that gets sent whenever a thumbnail is passively requested (i.e. when no render-time generation is wanted, via the ``generate=False`` argument).
47e27693788eb84baaabcc4a374e2e8cd6cb1101
image_cropping/thumbnail_processors.py
image_cropping/thumbnail_processors.py
def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping """ if box: values = [int(x) for x in box.split(',')] box = ( int(values[0]), int(values[1]), int(values[2]), int(values[3]), ) image = image.crop(box) return image
def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping """ if box: values = [int(x) for x in box.split(',')] width = abs(values[2] - values[0]) height = abs(values[3] - values[1]) if width != image.size[0] or height != image.size[1]: image = image.crop(*values) return image
Scale image only if necessary to avoid compression artefacts
Scale image only if necessary to avoid compression artefacts
Python
bsd-3-clause
henriquechehad/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping,henriquechehad/django-image-cropping,winzard/django-image-cropping
--- +++ @@ -5,13 +5,10 @@ if box: values = [int(x) for x in box.split(',')] - box = ( - int(values[0]), - int(values[1]), - int(values[2]), - int(values[3]), - ) - image = image.crop(box) + width = abs(values[2] - values[0]) + height = abs(values[3] - values[1]) + if width != image.size[0] or height != image.size[1]: + image = image.crop(*values) return image
e380d669bc09e047282be1d91cc95a7651300141
farms/tests/test_models.py
farms/tests/test_models.py
"""Unit test the farms models.""" from farms.factories import AddressFactory from mock import MagicMock def test_address_factory_generates_valid_addresses_sort_of(mocker): """Same test, but using pytest-mock.""" mocker.patch('farms.models.Address.save', MagicMock(name="save")) address = AddressFactory.create() assert address.street is not '' assert address.postal_code is not '' assert len(address.postal_code) == 5 assert address.city is not ''
"""Unit test the farms models.""" from ..factories import AddressFactory from ..models import Address import pytest def test_address_factory_generates_valid_address(): # GIVEN any state # WHEN building a new address address = AddressFactory.build() # THEN it has all the information we want assert address.street is not '' assert address.postal_code is not '' assert len(address.postal_code) == 5 assert address.city is not '' @pytest.mark.django_db def test_address_can_be_saved_and_retrieved(): # GIVEN a fresh address instance address = AddressFactory.build() street = address.street postal_code = address.postal_code # WHEN saving it to the database address.save() # THEN the db entry is correct saved_address = Address.objects.last() assert saved_address.street == street assert saved_address.postal_code == postal_code
Add integration test for Address model
Add integration test for Address model
Python
mit
FlowFX/sturdy-potato,FlowFX/sturdy-potato,FlowFX/sturdy-potato
--- +++ @@ -1,17 +1,35 @@ """Unit test the farms models.""" -from farms.factories import AddressFactory +from ..factories import AddressFactory +from ..models import Address -from mock import MagicMock +import pytest -def test_address_factory_generates_valid_addresses_sort_of(mocker): - """Same test, but using pytest-mock.""" - mocker.patch('farms.models.Address.save', MagicMock(name="save")) +def test_address_factory_generates_valid_address(): + # GIVEN any state + # WHEN building a new address + address = AddressFactory.build() - address = AddressFactory.create() - + # THEN it has all the information we want assert address.street is not '' assert address.postal_code is not '' assert len(address.postal_code) == 5 assert address.city is not '' + + +@pytest.mark.django_db +def test_address_can_be_saved_and_retrieved(): + # GIVEN a fresh address instance + address = AddressFactory.build() + street = address.street + postal_code = address.postal_code + + # WHEN saving it to the database + address.save() + + # THEN the db entry is correct + saved_address = Address.objects.last() + + assert saved_address.street == street + assert saved_address.postal_code == postal_code
bcaa91b14cd852b88c348aa47ab97b6dc8cde42c
knesset/browser_cases.py
knesset/browser_cases.py
# encoding: utf-8 from knesset.browser_test_case import BrowserTestCase, on_platforms # All browser test cases must inherit from BrowserTestCase which initializes the selenium framework # also, they must use the @on_platforms decorator. This decorator can run the test case several times - for different browser and platforms. @on_platforms() class MyTestCase(BrowserTestCase): """ Simple demo test case - just makes sure the tidbit carousel appears on the homepage """ def testHomepage(self): # inside the tests you can use self.drive which will have a ready selenium driver to use self.driver.get(self.live_server_url+'/') # most functions throw an exception if they don't find what their looking for, so you don't have to assert self.driver.find_element_by_id('tidbitCarousel')
# encoding: utf-8 from knesset.browser_test_case import BrowserTestCase, on_platforms # All browser test cases must inherit from BrowserTestCase which initializes the selenium framework # also, they must use the @on_platforms decorator. This decorator can run the test case several times - for different browser and platforms. @on_platforms() class MainSIteBrowserTestCase(BrowserTestCase): """ Simple demo test case - just makes sure the tidbit carousel appears on the homepage """ def testHomepage(self): # inside the tests you can use self.drive which will have a ready selenium driver to use self.driver.get(self.live_server_url+'/main') # Until we return old page # most functions throw an exception if they don't find what their looking for, so you don't have to assert self.driver.find_element_by_id('tidbitCarousel') def testHelpPageDisplayFacebookUpdates(self): self.driver.get(self.live_server_url + '/help') # Until we return old page self.driver.find_element_by_id('kikar-facebook-updates-ul')
Update test case for current state
Update test case for current state
Python
bsd-3-clause
MeirKriheli/Open-Knesset,OriHoch/Open-Knesset,OriHoch/Open-Knesset,MeirKriheli/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,MeirKriheli/Open-Knesset,OriHoch/Open-Knesset,alonisser/Open-Knesset,MeirKriheli/Open-Knesset,OriHoch/Open-Knesset,daonb/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset
--- +++ @@ -6,13 +6,17 @@ # also, they must use the @on_platforms decorator. This decorator can run the test case several times - for different browser and platforms. @on_platforms() -class MyTestCase(BrowserTestCase): +class MainSIteBrowserTestCase(BrowserTestCase): """ Simple demo test case - just makes sure the tidbit carousel appears on the homepage """ def testHomepage(self): # inside the tests you can use self.drive which will have a ready selenium driver to use - self.driver.get(self.live_server_url+'/') + self.driver.get(self.live_server_url+'/main') # Until we return old page # most functions throw an exception if they don't find what their looking for, so you don't have to assert self.driver.find_element_by_id('tidbitCarousel') + + def testHelpPageDisplayFacebookUpdates(self): + self.driver.get(self.live_server_url + '/help') # Until we return old page + self.driver.find_element_by_id('kikar-facebook-updates-ul')
01347b2725c67ba57aff3b48f69907cb2fcd95d0
pinchangeserver/setup.py
pinchangeserver/setup.py
from setuptools import find_packages, setup setup(name="umaineapi_pinchangeserver", version = "0.1", description = "A service for connecting to myHousing using a Maine ID and ", author = "Noah Howard", platforms = ["any"], license = "BSD", packages = find_packages(), install_requires = ["requests", "flask-mysqldb", "jsonify", "mechanize", "beautifulsoup4", "html5lib" ], )
from setuptools import find_packages, setup setup(name="umaineapi_pinchangeserver", version = "0.1", description = "A service for connecting to myHousing using a Maine ID and ", author = "Noah Howard", platforms = ["any"], license = "BSD", packages = find_packages(), install_requires = ["requests", "flask-mysqldb", "flask-cors", "jsonify", "mechanize", "beautifulsoup4", "html5lib" ], )
Add in dependency for flask cors
Add in dependency for flask cors
Python
mit
nh-99/UMaine-Service-API,nh-99/UMaine-Service-API
--- +++ @@ -7,5 +7,5 @@ platforms = ["any"], license = "BSD", packages = find_packages(), - install_requires = ["requests", "flask-mysqldb", "jsonify", "mechanize", "beautifulsoup4", "html5lib" ], + install_requires = ["requests", "flask-mysqldb", "flask-cors", "jsonify", "mechanize", "beautifulsoup4", "html5lib" ], )
777e567c74ce037fb8de89c64d798d3aa1211da2
courriers/tasks.py
courriers/tasks.py
from celery.task import task @task def subscribe(email, newsletter_list, lang=None, user=None): from courriers.backends import get_backend backend = get_backend()() try: backend.register(email=email, newsletter_list=newsletter_list, lang=lang, user=user) except Exception as e: raise subscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=5) @task def unsubscribe(email, newsletter_list=None, lang=None, user=None): from courriers.backends import get_backend backend = get_backend()() try: backend.unregister(email=email, newsletter_list=newsletter_list, lang=lang, user=user) except Exception as e: raise unsubscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=5)
from celery.task import task @task def subscribe(email, newsletter_list, lang=None, user=None): from courriers.backends import get_backend backend = get_backend()() try: backend.register(email=email, newsletter_list=newsletter_list, lang=lang, user=user) except Exception as e: raise subscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=30) @task def unsubscribe(email, newsletter_list=None, lang=None, user=None): from courriers.backends import get_backend backend = get_backend()() try: backend.unregister(email=email, newsletter_list=newsletter_list, lang=lang, user=user) except Exception as e: raise unsubscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=30)
Fix the delay for subscription and unsubscription retry
Fix the delay for subscription and unsubscription retry
Python
mit
ulule/django-courriers,ulule/django-courriers
--- +++ @@ -13,7 +13,7 @@ lang=lang, user=user) except Exception as e: - raise subscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=5) + raise subscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=30) @task @@ -28,4 +28,4 @@ lang=lang, user=user) except Exception as e: - raise unsubscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=5) + raise unsubscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=30)
ea9dcbed73a2cec0135a54cd093b42bc04364818
test/unit_test/test_cut_number.py
test/unit_test/test_cut_number.py
from lexos.processors.prepare.cutter import split_keep_whitespace, \ count_words, cut_by_number class TestCutByNumbers: def test_split_keep_whitespace(self): assert split_keep_whitespace("Test string") == ["Test", " ", "string"] assert split_keep_whitespace("Test") == ["Test"] assert split_keep_whitespace(" ") == ["", " ", ""] # intended? assert split_keep_whitespace("") == [""] def test_count_words(self): assert count_words(["word", "word", " ", "not", "word"]) == 4 assert count_words(['\n', '\t', ' ', '', '\u3000', "word"]) == 1 assert count_words([""]) == 0 def test_cut_by_number_normal(self): assert cut_by_number("Text", 1) == ["Text"] assert cut_by_number("This text has five words", 5) == \ ["This ", "text ", "has ", "five ", "words"] assert cut_by_number("Hanging space ", 2) == ["Hanging ", "space "]
from lexos.processors.prepare.cutter import split_keep_whitespace, \ count_words, cut_by_number class TestCutByNumbers: def test_split_keep_whitespace(self): assert split_keep_whitespace("Test string") == ["Test", " ", "string"] assert split_keep_whitespace("Test") == ["Test"] assert split_keep_whitespace(" ") == ["", " ", ""] # intended? assert split_keep_whitespace("") == [""] def test_count_words(self): assert count_words(["word", "word", " ", "not", "word"]) == 4 assert count_words(['\n', '\t', ' ', '', '\u3000', "word"]) == 1 assert count_words([""]) == 0 def test_cut_by_number_normal(self): assert cut_by_number("Text", 1) == ["Text"] assert cut_by_number("This text has five words", 5) == \ ["This ", "text ", "has ", "five ", "words"] def test_cut_by_number_spacing(self): assert cut_by_number("Hanging space ", 2) == ["Hanging ", "space "] assert cut_by_number("Other whitespace\n is\tfine!\n\n", 4) == \ ["Other ", "whitespace\n ", "is\t", "fine!\n\n"]
Test how cut_by_number handles whitespace
Test how cut_by_number handles whitespace
Python
mit
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
--- +++ @@ -18,5 +18,9 @@ assert cut_by_number("Text", 1) == ["Text"] assert cut_by_number("This text has five words", 5) == \ ["This ", "text ", "has ", "five ", "words"] + + def test_cut_by_number_spacing(self): assert cut_by_number("Hanging space ", 2) == ["Hanging ", "space "] + assert cut_by_number("Other whitespace\n is\tfine!\n\n", 4) == \ + ["Other ", "whitespace\n ", "is\t", "fine!\n\n"]
075d6f1b8f232c1ae7cb7d288da8f8d1040f49c9
hooks/pre_gen_project.py
hooks/pre_gen_project.py
repo_name = '{{ cookiecutter.repo_name }}' assert_msg = 'Repo name should be valid Python identifier!' if hasattr(repo_name, 'isidentifier'): assert repo_name.isidentifier(), assert_msg else: import re identifier_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") assert bool(identifier_re.match(repo_name)), assert_msg
import sys import cookiecutter # Ensure cookiecutter is recent enough cookiecutter_min_version = '1.3.0' if cookiecutter.__version__ < cookiecutter_min_version: print("--------------------------------------------------------------") print("!! Your cookiecutter is too old, at least %s is required !!" % cookiecutter_min_version) print("--------------------------------------------------------------") sys.exit(1) # Ensure the selected repo name is usable repo_name = '{{ cookiecutter.repo_name }}' assert_msg = 'Repo name should be valid Python identifier!' if hasattr(repo_name, 'isidentifier'): assert repo_name.isidentifier(), assert_msg else: import re identifier_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") assert bool(identifier_re.match(repo_name)), assert_msg
Add check for cookiecutter version - at least 1.3.0 is required now
Add check for cookiecutter version - at least 1.3.0 is required now
Python
isc
thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template
--- +++ @@ -1,3 +1,18 @@ +import sys + +import cookiecutter + + +# Ensure cookiecutter is recent enough +cookiecutter_min_version = '1.3.0' +if cookiecutter.__version__ < cookiecutter_min_version: + print("--------------------------------------------------------------") + print("!! Your cookiecutter is too old, at least %s is required !!" % cookiecutter_min_version) + print("--------------------------------------------------------------") + sys.exit(1) + + +# Ensure the selected repo name is usable repo_name = '{{ cookiecutter.repo_name }}' assert_msg = 'Repo name should be valid Python identifier!'
a41c8b8f9d3901e8d2794981c6cec050bf086e92
conjureup/controllers/clouds/common.py
conjureup/controllers/clouds/common.py
import asyncio from juju.utils import run_with_interrupt from conjureup import events from conjureup.models.provider import LocalhostError, LocalhostJSONError class BaseCloudController: cancel_monitor = asyncio.Event() async def _monitor_localhost(self, provider, cb): """ Checks that localhost/lxd is available and listening, updates widget accordingly """ while not self.cancel_monitor.is_set(): try: compatible = await provider.is_server_compatible() if compatible: events.LXDAvailable.set() self.cancel_monitor.set() cb() return except (LocalhostError, LocalhostJSONError): provider._set_lxd_dir_env() except FileNotFoundError: pass await run_with_interrupt(asyncio.sleep(2), self.cancel_monitor)
import asyncio from juju.utils import run_with_interrupt from conjureup import events from conjureup.models.provider import LocalhostError, LocalhostJSONError class BaseCloudController: cancel_monitor = asyncio.Event() async def _monitor_localhost(self, provider, cb): """ Checks that localhost/lxd is available and listening, updates widget accordingly """ while not self.cancel_monitor.is_set(): try: provider._set_lxd_dir_env() compatible = await provider.is_server_compatible() if compatible: events.LXDAvailable.set() self.cancel_monitor.set() cb() return except (LocalhostError, LocalhostJSONError, FileNotFoundError): pass await run_with_interrupt(asyncio.sleep(2), self.cancel_monitor)
Make sure _set_lxd_dir_env is always called in monitor loop
Make sure _set_lxd_dir_env is always called in monitor loop Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
Python
mit
Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,ubuntu/conjure-up,conjure-up/conjure-up,Ubuntu-Solutions-Engineering/conjure,conjure-up/conjure-up
--- +++ @@ -17,15 +17,14 @@ while not self.cancel_monitor.is_set(): try: + provider._set_lxd_dir_env() compatible = await provider.is_server_compatible() if compatible: events.LXDAvailable.set() self.cancel_monitor.set() cb() return - except (LocalhostError, LocalhostJSONError): - provider._set_lxd_dir_env() - except FileNotFoundError: + except (LocalhostError, LocalhostJSONError, FileNotFoundError): pass await run_with_interrupt(asyncio.sleep(2), self.cancel_monitor)
99d0dc6a77144f39fce80b81247575d7c92ee4ac
footynews/db/models.py
footynews/db/models.py
from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Article(Base): """Model for Articles""" __tablename__ = 'articles' _id = Column(Integer, primary_key=True) source = Column(String) title = Column(String) url = Column(String) author = Column(String) date_published = Column(DateTime) def __init__(self, article): self.source = article.source self.title = article.title self.url = article.url self.author = article.author self.date_published = article.date_published def __repr__(self): return "<Article(source={0})>" engine = create_engine('') Base.metadata.create_all(engine) DBSession = sessionmaker(bind=engine) db_session = DBSession()
from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Article(Base): """Model for Articles""" __tablename__ = 'articles' _id = Column(Integer, primary_key=True) source = Column(String) title = Column(String) url = Column(String) author = Column(String) date_published = Column(DateTime) def __init__(self, article): self.source = article.source self.title = article.title self.url = article.url self.author = article.author self.date_published = article.date_published def __repr__(self): return ("<Article(source={0}, title={1}, url={2}, author={3}, " "date_published={4})>".format(self.source, self.title, self.url, self.author, self.date_published)) engine = create_engine('') Base.metadata.create_all(engine) DBSession = sessionmaker(bind=engine) db_session = DBSession()
Define repr for Article model
Define repr for Article model
Python
apache-2.0
footynews/fn_backend
--- +++ @@ -24,7 +24,9 @@ self.date_published = article.date_published def __repr__(self): - return "<Article(source={0})>" + return ("<Article(source={0}, title={1}, url={2}, author={3}, " + "date_published={4})>".format(self.source, self.title, + self.url, self.author, self.date_published)) engine = create_engine('') Base.metadata.create_all(engine)
48884e305609e7c17eb3906c22ce509191f0d00e
passeplat.py
passeplat.py
from flask import Flask, request import requests app = Flask(__name__) API_ROOT_URL = "https://api.heroku.com/" # uses ~./netrc otherwise which might interfere with your requests requests.defaults.defaults['trust_env'] = False @app.route("/", methods=['GET', 'POST', 'DELETE', 'PUT']) @app.route("/<path:path>", methods=['GET', 'POST', 'DELETE', 'PUT']) def proxy(path=""): clean_headers = {} for k, v in request.headers: clean_headers[k] = v # request.form is a Werkzeug MultiDict # we want to create a string clean_data = "" for k, v in request.form.iteritems(): clean_data += k + "=" + v + "&" # clean_headers['Content-Length'] = str(int(clean_headers['Content-Length']) + 4) print path print request.method print request.headers print clean_headers print request.form print clean_data response = requests.request(request.method, API_ROOT_URL + path, headers=clean_headers, data=clean_data) print response.headers return response.text if __name__ == "__main__": app.debug = True app.run()
from flask import Flask, request, Response import requests app = Flask(__name__) API_ROOT_URL = "https://api.heroku.com/" # uses ~./netrc otherwise which might interfere with your requests requests.defaults.defaults['trust_env'] = False @app.route("/", methods=['GET', 'POST', 'DELETE', 'PUT']) @app.route("/<path:path>", methods=['GET', 'POST', 'DELETE', 'PUT']) def proxy(path=""): clean_headers = {} if 'Authorization' in request.headers: clean_headers['Authorization'] = request.headers['Authorization'] if request.headers['Accept'] == 'application/xml': clean_headers['Accept'] = 'application/xml' else: clean_headers['Accept'] = 'application/json' # request.form is a Werkzeug MultiDict # we want to create a string clean_data = "" for k, v in request.form.iteritems(): clean_data += k + "=" + v + "&" # clean_headers['Content-Length'] = str(int(clean_headers['Content-Length']) + 4) print path print request.method print request.headers print clean_headers print request.form print clean_data response = requests.request(request.method, API_ROOT_URL + path, headers=clean_headers, data=clean_data) print response.headers return Response(response=response.text, status=response.headers['status'], headers=response.headers) if __name__ == "__main__": app.debug = True app.run()
Add more complete flask.Response object as return object
Add more complete flask.Response object as return object Also, selects a couple of specific headers to pass along to Requests. To improve in the future :)
Python
mit
Timothee/Passeplat
--- +++ @@ -1,4 +1,4 @@ -from flask import Flask, request +from flask import Flask, request, Response import requests app = Flask(__name__) API_ROOT_URL = "https://api.heroku.com/" @@ -10,8 +10,12 @@ @app.route("/<path:path>", methods=['GET', 'POST', 'DELETE', 'PUT']) def proxy(path=""): clean_headers = {} - for k, v in request.headers: - clean_headers[k] = v + if 'Authorization' in request.headers: + clean_headers['Authorization'] = request.headers['Authorization'] + if request.headers['Accept'] == 'application/xml': + clean_headers['Accept'] = 'application/xml' + else: + clean_headers['Accept'] = 'application/json' # request.form is a Werkzeug MultiDict # we want to create a string @@ -31,7 +35,8 @@ data=clean_data) print response.headers - return response.text + return Response(response=response.text, status=response.headers['status'], headers=response.headers) + if __name__ == "__main__": app.debug = True
50d0806e2826a5691f1f2ce8fac27c74d98b51c7
environments/default/bin/convertmp3.py
environments/default/bin/convertmp3.py
#!/usr/bin/python import glob import os import subprocess import sys files = sys.argv[1:] if len(sys.argv) > 1 else glob.glob('*') for file in files: if os.path.isfile(file): fileWithoutExtension = os.path.splitext(file)[0] fileWithMp3Extension = fileWithoutExtension + ".mp3"; print "Converting " + file + "..." subprocess.call([ "ffmpeg", "-i", str(file), "-ab", "128k", fileWithoutExtension + ".mp3" ])
#!/usr/bin/python import glob import os import subprocess import sys files = sys.argv[1:] if len(sys.argv) > 1 else glob.glob('*') for file in files: if os.path.isfile(file): fileWithoutExtension = os.path.splitext(file)[0] fileWithMp3Extension = fileWithoutExtension + ".mp3"; print "Converting " + file + "..." subprocess.call([ "ffmpeg", "-i", str(file), "-ab", "128k", fileWithMp3Extension ])
Use variable instead of concatenating string directly
Use variable instead of concatenating string directly
Python
mit
perdian/dotfiles,perdian/dotfiles,perdian/dotfiles
--- +++ @@ -16,5 +16,5 @@ "ffmpeg", "-i", str(file), "-ab", "128k", - fileWithoutExtension + ".mp3" + fileWithMp3Extension ])
54b8d77fed6bc59f7e8926b9f1a8e08f25b26eac
corner_cubes_3d_laser/cut_generator.py
corner_cubes_3d_laser/cut_generator.py
# Program by Ankur Gupta # www.github.com/agupta231 # Jan 2017 # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.
# Program by Ankur Gupta # www.github.com/agupta231 # Jan 2017 # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Set up parameters material_thickness = 0.8 initial_cube_size = 10 iteration_multiplier = 0.5 iterations = 3
Set up the basic parameters
Set up the basic parameters
Python
mit
agupta231/fractal_prints
--- +++ @@ -20,3 +20,9 @@ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. + +# Set up parameters +material_thickness = 0.8 +initial_cube_size = 10 +iteration_multiplier = 0.5 +iterations = 3
4a7b48b29b0a2e476b21e27bda8d7122f9982dae
mica/report/tests/test_write_report.py
mica/report/tests/test_write_report.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='jeanconn', database='axafvv') as db: HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase VV access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
Change sybase skip test to check for more restrictive vv creds
Change sybase skip test to check for more restrictive vv creds This should let the report-writing test that uses the axafvv query run as jeanconn user, but skip for other users.
Python
bsd-3-clause
sot/mica,sot/mica
--- +++ @@ -8,7 +8,7 @@ try: import Ska.DBI - with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: + with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='jeanconn', database='axafvv') as db: HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False @@ -17,7 +17,7 @@ HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) -@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') +@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase VV access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """
ef285377df575e101dd59d11bfec9f5b5d12ab2e
gears/asset_handler.py
gears/asset_handler.py
from functools import wraps class BaseAssetHandler(object): def __call__(self, asset): raise NotImplementedError @classmethod def as_handler(cls, **initkwargs): @wraps(cls, updated=()) def handler(asset): return handler.handler_class(**initkwargs)(asset) handler.handler_class = cls return handler
# -*- coding: utf-8 -*- from functools import wraps class BaseAssetHandler(object): """Base class for all asset handlers (processors, compilers and compressors). A subclass has to implement :meth:`__call__` which is called with asset as argument. """ def __call__(self, asset): """Subclasses have to override this method to implement the actual handler function code. This method is called with asset as argument. Depending on the type of the handler, this method must change asset state (as it does in :class:`~gears.processors.Directivesprocessor`) or return some value (in case of asset compressors). """ raise NotImplementedError @classmethod def as_handler(cls, **initkwargs): """Converts the class into an actual handler function that can be used when registering different types of processors in :class:`~gears.enviroment.Environment` class instance. The arguments passed to :meth:`as_handler` are forwarded to the constructor of the class. """ @wraps(cls, updated=()) def handler(asset): return handler.handler_class(**initkwargs)(asset) handler.handler_class = cls return handler
Add docstrings to AssetHandler class
Add docstrings to AssetHandler class
Python
isc
gears/gears,gears/gears,gears/gears
--- +++ @@ -1,13 +1,32 @@ +# -*- coding: utf-8 -*- + from functools import wraps class BaseAssetHandler(object): + """Base class for all asset handlers (processors, compilers and + compressors). A subclass has to implement :meth:`__call__` which is called + with asset as argument. + """ def __call__(self, asset): + """Subclasses have to override this method to implement the actual + handler function code. This method is called with asset as argument. + Depending on the type of the handler, this method must change asset + state (as it does in :class:`~gears.processors.Directivesprocessor`) + or return some value (in case of asset compressors). + """ raise NotImplementedError @classmethod def as_handler(cls, **initkwargs): + """Converts the class into an actual handler function that can be used + when registering different types of processors in + :class:`~gears.enviroment.Environment` class instance. + + The arguments passed to :meth:`as_handler` are forwarded to the + constructor of the class. + """ @wraps(cls, updated=()) def handler(asset): return handler.handler_class(**initkwargs)(asset)
089bce7ec9df43cc526342ba84e37fe87203ca11
gemini/gemini_amend.py
gemini/gemini_amend.py
import GeminiQuery from gemini_subjects import get_subjects from ped import load_ped_file, get_ped_fields from gemini_utils import quote_string import sqlite3 from database import database_transaction def amend(parser, args): if args.db is None: parser.print_help() exit("ERROR: amend needs a database file.") if args.sample: amend_sample(args) def amend_sample(args): loaded_subjects = get_subjects(args) ped_dict = load_ped_file(args.sample) header = get_ped_fields(args.sample) with database_transaction(args.db) as c: for k, v in loaded_subjects.items(): if k in ped_dict: item_list = map(quote_string, ped_dict[k]) sample = zip(header, item_list) set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample]) sql_query = "update samples set {0} where sample_id={1}" c.execute(sql_query.format(set_str, v.sample_id))
import GeminiQuery from gemini_subjects import get_subjects from ped import load_ped_file, get_ped_fields from gemini_utils import quote_string import sqlite3 from database import database_transaction def amend(parser, args): if args.db is None: parser.print_help() exit("ERROR: amend needs a database file.") if args.sample: amend_sample(args) def amend_sample(args): loaded_subjects = get_subjects(args) ped_dict = load_ped_file(args.sample) header = get_ped_fields(args.sample) with database_transaction(args.db) as c: add_columns(header, c) for k, v in loaded_subjects.items(): if k in ped_dict: item_list = map(quote_string, ped_dict[k]) sample = zip(header, item_list) set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample]) sql_query = "update samples set {0} where sample_id={1}" c.execute(sql_query.format(set_str, v.sample_id)) def add_columns(header, c): """ add any missing columns to the samples table """ for column in header: try: c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column)) except: pass
Extend samples table with new columns when amending.
Extend samples table with new columns when amending. This allows you to add phenotype fields to your samples after you have already created the database.
Python
mit
xuzetan/gemini,brentp/gemini,heuermh/gemini,xuzetan/gemini,udp3f/gemini,bpow/gemini,heuermh/gemini,arq5x/gemini,brentp/gemini,arq5x/gemini,heuermh/gemini,bw2/gemini,bgruening/gemini,brentp/gemini,arq5x/gemini,heuermh/gemini,bw2/gemini,udp3f/gemini,brentp/gemini,bw2/gemini,bgruening/gemini,xuzetan/gemini,udp3f/gemini,arq5x/gemini,bw2/gemini,bpow/gemini,udp3f/gemini,bgruening/gemini,bgruening/gemini,bpow/gemini,bpow/gemini,xuzetan/gemini
--- +++ @@ -17,6 +17,7 @@ ped_dict = load_ped_file(args.sample) header = get_ped_fields(args.sample) with database_transaction(args.db) as c: + add_columns(header, c) for k, v in loaded_subjects.items(): if k in ped_dict: item_list = map(quote_string, ped_dict[k]) @@ -25,3 +26,12 @@ sql_query = "update samples set {0} where sample_id={1}" c.execute(sql_query.format(set_str, v.sample_id)) +def add_columns(header, c): + """ + add any missing columns to the samples table + """ + for column in header: + try: + c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column)) + except: + pass
c33aa32b868a33422f79103474cece38131a93c3
src/oscar/apps/customer/migrations/0005_auto_20170413_1857.py
src/oscar/apps/customer/migrations/0005_auto_20170413_1857.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-04-13 17:57 from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): User = apps.get_model("auth", "User") for user in User.objects.all(): user.emails.update(email=user.email) class Migration(migrations.Migration): dependencies = [ ('customer', '0004_auto_20170413_1853'), ] operations = [ migrations.RunPython(forwards_func) ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-04-13 17:57 from __future__ import unicode_literals from django.db import migrations from oscar.core.compat import get_user_model User = get_user_model() def forwards_func(apps, schema_editor): for user in User.objects.all(): user.emails.update(email=user.email) class Migration(migrations.Migration): dependencies = [ ('customer', '0004_auto_20170413_1853'), ] operations = [ migrations.RunPython(forwards_func) ]
Load current User model for customer email migration.
Load current User model for customer email migration.
Python
bsd-3-clause
solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sasha0/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,solarissmoke/django-oscar
--- +++ @@ -4,10 +4,12 @@ from django.db import migrations +from oscar.core.compat import get_user_model + +User = get_user_model() + def forwards_func(apps, schema_editor): - User = apps.get_model("auth", "User") - for user in User.objects.all(): user.emails.update(email=user.email)
b776a97f6f12f7b424c45d73b1c975748c4c30ae
tasks/check_einstein.py
tasks/check_einstein.py
import json from cumulusci.tasks.salesforce import BaseSalesforceApiTask class CheckPermSetLicenses(BaseSalesforceApiTask): task_options = { "permission_sets": { "description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)", "required": True, } } def _run_task(self): query = self._get_query() print(query) result = self.tooling.query(query) return result["size"] > 0 def _get_query(self): where_targets = [f"'{name}'" for name in self.options["permission_sets"]] return f""" SELECT Name FROM PermissionSet WHERE Name IN ({','.join(where_targets)}) """
import json from cumulusci.tasks.salesforce import BaseSalesforceApiTask class CheckPermSetLicenses(BaseSalesforceApiTask): task_options = { "permission_sets": { "description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)", "required": True, } } def _run_task(self): query = self._get_query() result = self.tooling.query(query) return result["size"] > 0 def _get_query(self): where_targets = [f"'{name}'" for name in self.options["permission_sets"]] return f""" SELECT Name FROM PermissionSet WHERE Name IN ({','.join(where_targets)}) """
Remove debugging statement from CheckPermSetLicenses
Remove debugging statement from CheckPermSetLicenses
Python
bsd-3-clause
SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP
--- +++ @@ -12,7 +12,6 @@ def _run_task(self): query = self._get_query() - print(query) result = self.tooling.query(query) return result["size"] > 0
efe1417ad049e4bb78bf1f111db6b2ea9c603461
rapt/util.py
rapt/util.py
import sys import yaml import click def dump_yaml(obj): return yaml.dump(obj, default_flow_style=False) def edit_yaml(content='', footer=''): MARKER = '# Everything below is ignored\n\n' message = click.edit(content + '\n\n' + MARKER + footer, extension='.yaml') if message is not None: yaml_content = message.split(MARKER, 1)[0].rstrip('\n') return yaml.safe_load(yaml_content) def stdin(): for line in sys.stdin: yield line.strip()
import sys import yaml import click def load_yaml(fh_or_string): return yaml.safe_load(fh_or_string) def dump_yaml(obj): return yaml.dump(obj, default_flow_style=False) def edit_yaml(content='', footer=''): MARKER = '# Everything below is ignored\n\n' message = click.edit(content + '\n\n' + MARKER + footer, extension='.yaml') if message is not None: yaml_content = message.split(MARKER, 1)[0].rstrip('\n') return yaml.safe_load(yaml_content) def stdin(): for line in sys.stdin: yield line.strip()
Add a load yaml helper
Add a load yaml helper
Python
bsd-3-clause
yougov/rapt,yougov/rapt
--- +++ @@ -1,6 +1,10 @@ import sys import yaml import click + + +def load_yaml(fh_or_string): + return yaml.safe_load(fh_or_string) def dump_yaml(obj):
90b2c2b546aa6c4707273be29fe83c2ea36e0ad5
panoptes/state_machine/states/parked.py
panoptes/state_machine/states/parked.py
from . import PanState """ Parked State The Parked state occurs in the following conditions: * Daytime * Bad Weather * System error As such, the state needs to check for a number of conditions. """ class State(PanState): def main(self): return 'exit'
from . import PanState class State(PanState): def main(self): next_state = 'shutdown' # mount = self.panoptes.observatory.mount self.logger.info("I'm parked now.") return next_state
Change Parked state to something silly
Change Parked state to something silly
Python
mit
AstroHuntsman/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,panoptes/POCS,panoptes/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,joshwalawender/POCS,joshwalawender/POCS,joshwalawender/POCS
--- +++ @@ -1,17 +1,14 @@ from . import PanState -""" Parked State - -The Parked state occurs in the following conditions: - * Daytime - * Bad Weather - * System error - -As such, the state needs to check for a number of conditions. -""" class State(PanState): + def main(self): - - return 'exit' + next_state = 'shutdown' + + # mount = self.panoptes.observatory.mount + + self.logger.info("I'm parked now.") + + return next_state
b4e874b752b072565effce1534c58067ee0ac1dc
trader/cli.py
trader/cli.py
import decimal from datetime import datetime import click from .controller import Controller, SimulatedClock from .broker import OandaBacktestBroker from .instruments import InstrumentParamType from .lib import oandapy from .conf import settings @click.command() @click.option('--instrument', '-i', 'instruments', multiple=True, type=InstrumentParamType()) def main(instruments): """ Algortihmic trading tool. """ # XXX: Currently only backtesting is supported api = oandapy.API( environment=settings.ENVIRONMENT, access_token=settings.ACCESS_TOKEN, ) broker = OandaBacktestBroker( api=api, initial_balance=decimal.Decimal(1000)) clock = SimulatedClock( start=datetime(2015, 01, 01, 12, 00), stop=datetime(2015, 01, 01, 13, 00), interval=settings.CLOCK_INTERVAL, ) # XXX: We have to be able to instantiate strategies with custom args strategies = [settings.STRATEGY(instrument) for instrument in set(instruments)] controller = Controller(clock, broker, strategies) controller.run_until_stopped()
import decimal from datetime import datetime import click from .controller import Controller, SimulatedClock from .broker import OandaBacktestBroker from .instruments import InstrumentParamType from .lib import oandapy from .conf import settings @click.command() @click.option('--instrument', '-i', 'instruments', multiple=True, type=InstrumentParamType()) def main(instruments): """ Algortihmic trading tool. """ # XXX: Currently only backtesting is supported api = oandapy.API( environment=settings.ENVIRONMENT, access_token=settings.ACCESS_TOKEN, ) broker = OandaBacktestBroker( api=api, initial_balance=decimal.Decimal(1000)) clock = SimulatedClock( start=datetime(2015, 05, 29, 12, 00), stop=datetime(2015, 05, 29, 15, 00), interval=settings.CLOCK_INTERVAL, ) # XXX: We have to be able to instantiate strategies with custom args strategies = [settings.STRATEGY(instrument) for instrument in set(instruments)] controller = Controller(clock, broker, strategies) controller.run_until_stopped()
Update default value for backtesting clock
Update default value for backtesting clock
Python
mit
jmelett/pyfx,jmelett/pyfx,jmelett/pyFxTrader
--- +++ @@ -26,8 +26,8 @@ api=api, initial_balance=decimal.Decimal(1000)) clock = SimulatedClock( - start=datetime(2015, 01, 01, 12, 00), - stop=datetime(2015, 01, 01, 13, 00), + start=datetime(2015, 05, 29, 12, 00), + stop=datetime(2015, 05, 29, 15, 00), interval=settings.CLOCK_INTERVAL, )