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
e4193b7082cf3d891c993905443415a613630f8f
mailtemplates/model/sqla/models.py
mailtemplates/model/sqla/models.py
from sqlalchemy import ForeignKey, Column from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) usage = Column(Text(), nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) body = Column(Text())
from sqlalchemy import ForeignKey, Column, UnicodeText from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) usage = Column(UnicodeText, nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) body = Column(UnicodeText())
Change type from text to UnicodeText
Change type from text to UnicodeText
Python
mit
axant/tgapp-mailtemplates,axant/tgapp-mailtemplates
--- +++ @@ -1,4 +1,4 @@ -from sqlalchemy import ForeignKey, Column +from sqlalchemy import ForeignKey, Column, UnicodeText from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base @@ -15,7 +15,7 @@ _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) - usage = Column(Text(), nullable=False) + usage = Column(UnicodeText, nullable=False) class TemplateTranslation(DeclarativeBase): @@ -29,7 +29,7 @@ language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) - body = Column(Text()) + body = Column(UnicodeText())
83966de4421094cf456f0002622f9f409ab4a694
wger/gym/signals.py
wger/gym/signals.py
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from wger.gym.models import Gym from wger.gym.models import GymConfig @receiver(post_save, sender=Gym) def gym_config(sender, instance, created, **kwargs): ''' Creates a configuration entry for newly added gyms ''' if not created or kwargs['raw']: return config = GymConfig() config.gym = instance config.save()
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License from django.conf import settings from django.db.models.signals import post_save from django.db.models.signals import post_delete from django.dispatch import receiver from wger.gym.models import Gym from wger.gym.models import GymConfig from wger.gym.models import UserDocument @receiver(post_save, sender=Gym) def gym_config(sender, instance, created, **kwargs): ''' Creates a configuration entry for newly added gyms ''' if not created or kwargs['raw']: return config = GymConfig() config.gym = instance config.save() @receiver(post_delete, sender=UserDocument) def delete_user_document_on_delete(sender, instance, **kwargs): ''' Deletes the document from the disk as well ''' instance.document.delete(save=False)
Delete the document from the disk on delete
Delete the document from the disk on delete
Python
agpl-3.0
kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,petervanderdoes/wger,DeveloperMal/wger,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,rolandgeider/wger,rolandgeider/wger,kjagoo/wger_stark,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,kjagoo/wger_stark,wger-project/wger,wger-project/wger
--- +++ @@ -17,10 +17,12 @@ from django.conf import settings from django.db.models.signals import post_save +from django.db.models.signals import post_delete from django.dispatch import receiver from wger.gym.models import Gym from wger.gym.models import GymConfig +from wger.gym.models import UserDocument @receiver(post_save, sender=Gym) @@ -34,3 +36,12 @@ config = GymConfig() config.gym = instance config.save() + + +@receiver(post_delete, sender=UserDocument) +def delete_user_document_on_delete(sender, instance, **kwargs): + ''' + Deletes the document from the disk as well + ''' + + instance.document.delete(save=False)
41d795736a7e759cf85cbe366567375eb9703a4a
aldryn_faq/admin.py
aldryn_faq/admin.py
# -*- coding: utf-8 -*- from adminsortable.admin import SortableAdmin from cms.admin.placeholderadmin import PlaceholderAdmin from django.contrib import admin from distutils.version import LooseVersion from hvad.admin import TranslatableAdmin import cms from . import models from aldryn_faq.forms import CategoryForm class CategoryAdmin(TranslatableAdmin): list_display = ['__unicode__', 'all_translations'] form = CategoryForm def get_fieldsets(self, request, obj=None): fieldsets = [ (None, {'fields': ['name', 'slug']}), ] return fieldsets class QuestionAdmin(PlaceholderAdmin, SortableAdmin): render_placeholder_language_tabs = False list_display = ['title', 'language', 'category', 'is_top'] def get_fieldsets(self, request, obj=None): fieldsets = [ (None, { 'fields': ['title', 'language', 'category', 'answer_text', 'is_top'] }) ] # show placeholder field if not CMS 3.0 if LooseVersion(cms.__version__) < LooseVersion('3.0'): fieldsets.append( ('Answer', { 'classes': ['plugin-holder', 'plugin-holder-nopage'], 'fields': ['answer'] })) return fieldsets admin.site.register(models.Question, QuestionAdmin) admin.site.register(models.Category, CategoryAdmin)
# -*- coding: utf-8 -*- from adminsortable.admin import SortableAdmin from cms.admin.placeholderadmin import PlaceholderAdmin from django.contrib import admin from distutils.version import LooseVersion from hvad.admin import TranslatableAdmin import cms from . import models from aldryn_faq.forms import CategoryForm class CategoryAdmin(TranslatableAdmin): list_display = ['__unicode__', 'all_translations'] form = CategoryForm def get_fieldsets(self, request, obj=None): fieldsets = [ (None, {'fields': ['name', 'slug']}), ] return fieldsets class QuestionAdmin(SortableAdmin, PlaceholderAdmin): render_placeholder_language_tabs = False list_display = ['title', 'language', 'category', 'is_top'] def get_fieldsets(self, request, obj=None): fieldsets = [ (None, { 'fields': ['title', 'language', 'category', 'answer_text', 'is_top'] }) ] # show placeholder field if not CMS 3.0 if LooseVersion(cms.__version__) < LooseVersion('3.0'): fieldsets.append( ('Answer', { 'classes': ['plugin-holder', 'plugin-holder-nopage'], 'fields': ['answer'] })) return fieldsets admin.site.register(models.Question, QuestionAdmin) admin.site.register(models.Category, CategoryAdmin)
Use appropriate order of classes
Use appropriate order of classes
Python
bsd-3-clause
czpython/aldryn-faq,czpython/aldryn-faq,mkoistinen/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq
--- +++ @@ -23,7 +23,7 @@ return fieldsets -class QuestionAdmin(PlaceholderAdmin, SortableAdmin): +class QuestionAdmin(SortableAdmin, PlaceholderAdmin): render_placeholder_language_tabs = False list_display = ['title', 'language', 'category', 'is_top']
7427ee344545356070db1300aae83272d5568e89
custom/icds_reports/tasks.py
custom/icds_reports/tasks.py
import os from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db import connections @periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7)) def move_ucr_data_into_aggregation_tables(): with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor: path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql') with open(path, "r") as sql_file: sql_to_execute = sql_file.read() cursor.execute(sql_to_execute) path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql') with open(path, "r") as sql_file: sql_to_execute = sql_file.read() for interval in ["0 months", "1 months", "2 months"]: cursor.execute(sql_to_execute, {"interval": interval})
import os from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db import connections @periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7), acks_late=True) def move_ucr_data_into_aggregation_tables(): with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor: path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql') with open(path, "r") as sql_file: sql_to_execute = sql_file.read() cursor.execute(sql_to_execute) path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql') with open(path, "r") as sql_file: sql_to_execute = sql_file.read() for interval in ["0 months", "1 months", "2 months"]: cursor.execute(sql_to_execute, {"interval": interval})
Add acks late to task
Add acks late to task
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
--- +++ @@ -7,7 +7,7 @@ from django.db import connections -@periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7)) +@periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7), acks_late=True) def move_ucr_data_into_aggregation_tables(): with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:
6d21aa9e6d52701d7beacd4ec519ab1bac488886
machina/models/abstract_models.py
machina/models/abstract_models.py
# -*- coding: utf-8 -*- # Standard library imports from __future__ import unicode_literals # Third party imports from django.db import models from django.utils.translation import ugettext_lazy as _ # Local application / specific library imports class ActiveManager(models.Manager): """ Returns only active objects. """ def get_queryset(self): super_self = super(ActiveManager, self) get_queryset = (super_self.get_query_set if hasattr(super_self, 'get_query_set') else super_self.get_queryset) return get_queryset().filter(is_active__exact=True) class ActiveModel(models.Model): """ An abstract base class model that provides an is_active field and attach an ActiveManager. """ is_active = models.BooleanField(default=True, db_index=True) # Managers objects = models.Manager() active = ActiveManager() class Meta: abstract = True class DatedModel(models.Model): """ An abstract base class model that provides a created and a updated fields to store creation date and last updated date. """ created = models.DateTimeField(auto_now_add=True, verbose_name=_('Creation date')) updated = models.DateTimeField(auto_now=True, verbose_name=_('Update date')) class Meta: abstract = True
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ class ActiveManager(models.Manager): """ Returns only active objects. """ def get_queryset(self): return super(ActiveManager, self).get_queryset().filter(is_active__exact=True) class ActiveModel(models.Model): """ An abstract base class model that provides an is_active field and attach an ActiveManager. """ is_active = models.BooleanField(default=True, db_index=True) # Managers objects = models.Manager() active = ActiveManager() class Meta: abstract = True class DatedModel(models.Model): """ An abstract base class model that provides a created and a updated fields to store creation date and last updated date. """ created = models.DateTimeField(auto_now_add=True, verbose_name=_('Creation date')) updated = models.DateTimeField(auto_now=True, verbose_name=_('Update date')) class Meta: abstract = True
Remove unnecessary compat code from ActiveManager
Remove unnecessary compat code from ActiveManager
Python
bsd-3-clause
franga2000/django-machina,franga2000/django-machina,reinbach/django-machina,reinbach/django-machina,ellmetha/django-machina,franga2000/django-machina,reinbach/django-machina,ellmetha/django-machina,ellmetha/django-machina
--- +++ @@ -1,13 +1,9 @@ # -*- coding: utf-8 -*- -# Standard library imports from __future__ import unicode_literals -# Third party imports from django.db import models from django.utils.translation import ugettext_lazy as _ - -# Local application / specific library imports class ActiveManager(models.Manager): @@ -15,12 +11,7 @@ Returns only active objects. """ def get_queryset(self): - super_self = super(ActiveManager, self) - get_queryset = (super_self.get_query_set - if hasattr(super_self, 'get_query_set') - else super_self.get_queryset) - - return get_queryset().filter(is_active__exact=True) + return super(ActiveManager, self).get_queryset().filter(is_active__exact=True) class ActiveModel(models.Model): @@ -39,7 +30,8 @@ class DatedModel(models.Model): """ - An abstract base class model that provides a created and a updated fields to store creation date and last updated date. + An abstract base class model that provides a created and a updated fields to store creation date + and last updated date. """ created = models.DateTimeField(auto_now_add=True, verbose_name=_('Creation date')) updated = models.DateTimeField(auto_now=True, verbose_name=_('Update date'))
dfe8f453bd28d290016d2d86c3b9502c988d1cdf
app/runserver.py
app/runserver.py
from flask_script import Manager from flask_restful import Api from config import app from api import api manager = Manager(app) def setup_api(app): """ Config resources with flask app """ service = Api(app) service.add_resource(api.MailChimpList,'/api/list/<list_id>',endpoint='list') service.add_resource(api.MailChimpMember,'/api/member/<asu_id>',endpoint='member') service.add_resource(api.GenerateAuthToken,'/api/gen_token',endpoint='token') return app # Deploy for development @manager.command def run_dev(): serviced_app = setup_api(app) serviced_app.run(debug=True) # Deploy for intergation tests @manager.command def run_test(): # To-Do pass # Deploy for production @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
from flask_script import Manager from flask_restful import Api from config import app from api import api manager = Manager(app) def setup_api(app): """ Config resources with flask app """ service = Api(app) service.add_resource(api.MailChimpList,'/api/list/<list_id>',endpoint='list') service.add_resource(api.MailChimpMember,'/api/member/<asu_id>',endpoint='member') service.add_resource(api.GenerateAuthToken,'/api/gen_token',endpoint='token') return app serviced_app = setup_api(app) # Deploy for development @manager.command def run_dev(): serviced_app.run(debug=True) # Deploy for intergation tests @manager.command def run_test(): # To-Do pass # Deploy for production @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
Move api config outside of manager commands
Move api config outside of manager commands
Python
mit
tforrest/soda-automation,tforrest/soda-automation
--- +++ @@ -16,10 +16,11 @@ return app +serviced_app = setup_api(app) + # Deploy for development @manager.command def run_dev(): - serviced_app = setup_api(app) serviced_app.run(debug=True) # Deploy for intergation tests
a146319132a21916747f98fa183fbe29139653ae
lib/pycall/python/investigator.py
lib/pycall/python/investigator.py
from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch)) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None))) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
Fix for python without _multiarch support
Fix for python without _multiarch support
Python
mit
mrkn/pycall.rb,mrkn/pycall,mrkn/pycall.rb,mrkn/pycall,mrkn/pycall.rb,mrkn/pycall,mrkn/pycall,mrkn/pycall.rb
--- +++ @@ -2,6 +2,6 @@ import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) -print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch)) +print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None))) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
101fb8aee3ae9d90502eecd3d4f147b7e9fb437b
python-modules/cis_crypto/setup.py
python-modules/cis_crypto/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() requirements = ['python-jose-cryptodome', 'everett', 'boto3==1.7.67', 'boto==2.49.0', 'botocore==1.10.67', 'requests', 'pyaml'] setup_requirements = ['pytest-runner'] test_requirements = ['pytest', 'pytest-watch', 'pytest-cov', 'pytest-mock', 'moto', 'mock', 'cis_fake_well_known'] setup( name="cis_crypto", version="0.0.1", author="Andrew Krug", author_email="akrug@mozilla.com", description="Per attribute signature system for jwks sign-verify in mozilla-iam.", long_description=long_description, url="https://github.com/mozilla-iam/cis", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Mozilla Public License", "Operating System :: OS Independent", ], install_requires=requirements, license="Mozilla Public License 2.0", include_package_data=True, packages=find_packages(include=['cis_crypto', 'bin']), scripts=['bin/cis_crypto'], setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, zip_safe=False )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() requirements = ['python-jose', 'python-jose-cryptodome', 'everett', 'boto3==1.7.67', 'boto==2.49.0', 'botocore==1.10.67', 'requests', 'pyaml'] setup_requirements = ['pytest-runner'] test_requirements = ['pytest', 'pytest-watch', 'pytest-cov', 'pytest-mock', 'moto', 'mock', 'cis_fake_well_known'] setup( name="cis_crypto", version="0.0.1", author="Andrew Krug", author_email="akrug@mozilla.com", description="Per attribute signature system for jwks sign-verify in mozilla-iam.", long_description=long_description, url="https://github.com/mozilla-iam/cis", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Mozilla Public License", "Operating System :: OS Independent", ], install_requires=requirements, license="Mozilla Public License 2.0", include_package_data=True, packages=find_packages(include=['cis_crypto', 'bin']), scripts=['bin/cis_crypto'], setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, zip_safe=False )
Fix install deps Things will work only in test where cis_fake_well_known is installed otherwise, but "prod" deploys would be missing deps that it would pull (even thus `make install` otherwise works)
Fix install deps Things will work only in test where cis_fake_well_known is installed otherwise, but "prod" deploys would be missing deps that it would pull (even thus `make install` otherwise works)
Python
mpl-2.0
mozilla-iam/cis,mozilla-iam/cis
--- +++ @@ -6,8 +6,8 @@ with open("README.md", "r") as fh: long_description = fh.read() -requirements = ['python-jose-cryptodome', 'everett', 'boto3==1.7.67', 'boto==2.49.0', 'botocore==1.10.67', - 'requests', 'pyaml'] +requirements = ['python-jose', 'python-jose-cryptodome', 'everett', 'boto3==1.7.67', 'boto==2.49.0', + 'botocore==1.10.67', 'requests', 'pyaml'] setup_requirements = ['pytest-runner']
3229340a11a1fcfe9f11ad0c5b558469043deaf4
linkatos/firebase.py
linkatos/firebase.py
import pyrebase def store_url(is_yes, url, FB_API_KEY, FB_USER, FB_PASS): # do nothing if it's unnecessary if is_yes is False: return is_yes # connect to firebase config = { "apiKey": FB_API_KEY, "authDomain": "coses-acbe6.firebaseapp.com", "databaseURL": "https://coses-acbe6.firebaseio.com", "storageBucket": "coses-acbe6.appspot.com"} # otherwise keep url firebase = pyrebase.initialize_app(config) # creates token every time maybe worth doing it once every 30m as they # expire every hour auth = firebase.auth() user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS) db = firebase.database() data = { "url": url } db.child("users").push(data, user['idToken']) is_yes = False return is_yes
import pyrebase def store_url(is_yes, url, FB_API_KEY, FB_USER, FB_PASS): # do nothing if it's unnecessary if not is_yes: return is_yes # connect to firebase config = { "apiKey": FB_API_KEY, "authDomain": "coses-acbe6.firebaseapp.com", "databaseURL": "https://coses-acbe6.firebaseio.com", "storageBucket": "coses-acbe6.appspot.com"} # otherwise keep url firebase = pyrebase.initialize_app(config) # creates token every time maybe worth doing it once every 30m as they # expire every hour auth = firebase.auth() user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS) db = firebase.database() data = { "url": url } db.child("users").push(data, user['idToken']) is_yes = False return is_yes
Change 'is False' to 'not'
refactor: Change 'is False' to 'not'
Python
mit
iwi/linkatos,iwi/linkatos
--- +++ @@ -3,7 +3,7 @@ def store_url(is_yes, url, FB_API_KEY, FB_USER, FB_PASS): # do nothing if it's unnecessary - if is_yes is False: + if not is_yes: return is_yes # connect to firebase
99470c7874a65ccf73693624454db8c4b20d59e1
alerts/cloudtrail_public_bucket.py
alerts/cloudtrail_public_bucket.py
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation from lib.alerttask import AlertTask from mozdef_util.query_models import SearchQuery, TermMatch, ExistsMatch class AlertCloudtrailPublicBucket(AlertTask): def main(self): search_query = SearchQuery(minutes=20) search_query.add_must([ TermMatch('source', 'cloudtrail'), TermMatch('details.eventname', 'CreateBucket'), TermMatch('details.requestparameters.x-amz-acl', 'public-read-write'), ]) self.filtersManual(search_query) self.searchEventsSimple() self.walkEvents() # Set alert properties def onEvent(self, event): request_parameters = event['_source']['details']['requestparameters'] category = 'access' tags = ['cloudtrail'] severity = 'INFO' bucket_name = 'Unknown' if 'bucketname' in request_parameters: bucket_name = request_parameters['bucketname'] summary = "The s3 bucket {0} is listed as public".format(bucket_name) return self.createAlertDict(summary, category, tags, [event], severity)
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation from lib.alerttask import AlertTask from mozdef_util.query_models import SearchQuery, TermMatch class AlertCloudtrailPublicBucket(AlertTask): def main(self): search_query = SearchQuery(minutes=20) search_query.add_must([ TermMatch('source', 'cloudtrail'), TermMatch('details.eventname', 'CreateBucket'), TermMatch('details.requestparameters.x-amz-acl', 'public-read-write'), ]) self.filtersManual(search_query) self.searchEventsSimple() self.walkEvents() # Set alert properties def onEvent(self, event): request_parameters = event['_source']['details']['requestparameters'] category = 'access' tags = ['cloudtrail'] severity = 'INFO' bucket_name = 'Unknown' if 'bucketname' in request_parameters: bucket_name = request_parameters['bucketname'] summary = "The s3 bucket {0} is listed as public".format(bucket_name) return self.createAlertDict(summary, category, tags, [event], severity)
Remove unused import from cloudtrail public bucket alert
Remove unused import from cloudtrail public bucket alert
Python
mpl-2.0
mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mozilla/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,jeffbryner/MozDef
--- +++ @@ -7,7 +7,7 @@ from lib.alerttask import AlertTask -from mozdef_util.query_models import SearchQuery, TermMatch, ExistsMatch +from mozdef_util.query_models import SearchQuery, TermMatch class AlertCloudtrailPublicBucket(AlertTask):
34504f0600dd8f3d7cb2594d51db9fa07e2e139a
package_deb_replace_version.py
package_deb_replace_version.py
import sys fullversion = sys.argv[1] path = f"btsoot_{fullversion}/DEBIAN/control" version = fullversion[1:] control_content = f"""Package: btsoot Version: {version} Section: base Priority: optional Architecture: i386 Depends: build-essential Maintainer: Paul Kramme <pjkramme@gmail.com> Description: BTSOOT Folder redundancy offsite-backup utility. """ print("DEB PACKAGE VERSION REPLACER") # yes, i wrote a tool for this... with open(path, "a") as f: f.write(control_content) print("Done.")
import sys fullversion = sys.argv[1] path = f"btsoot_{fullversion}/DEBIAN/control" version = fullversion[1:] control_content = f"""Package: btsoot Version: {version} Section: base Priority: optional Architecture: amd64 Depends: build-essential Maintainer: Paul Kramme <pjkramme@gmail.com> Description: BTSOOT Folder redundancy offsite-backup utility. """ print("DEB PACKAGE VERSION REPLACER") # yes, i wrote a tool for this... with open(path, "a") as f: f.write(control_content) print("Done.")
Fix architecture for future releases
Fix architecture for future releases
Python
bsd-3-clause
paulkramme/btsoot
--- +++ @@ -7,7 +7,7 @@ Version: {version} Section: base Priority: optional -Architecture: i386 +Architecture: amd64 Depends: build-essential Maintainer: Paul Kramme <pjkramme@gmail.com> Description: BTSOOT
bd0cf3920121ada2c35928130b910667ce16a85a
downstream-farmer/client.py
downstream-farmer/client.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from heartbeat import Challenge import requests from .utils import urlify from .exc import DownstreamError class DownstreamClient(object): def __init__(self, server_url): self.server = server_url.strip('/') self.challenges = [] def connect(self, url): raise NotImplementedError def store_path(self, path): raise NotImplementedError def get_chunk(self, hash): raise NotImplementedError def challenge(self, hash, challenge): raise NotImplementedError def answer(self, hash, hash_answer): raise NotImplementedError def _enc_fname(self, filename): return urlify(os.path.split(filename)[1]) def get_challenges(self, filename): enc_fname = urlify(os.path.split(filename)[1]) url = '%s/api/downstream/challenge/%s' % (self.server, enc_fname) resp = requests.get(url) try: resp.raise_for_status() except Exception as e: raise DownstreamError("Error connecting to downstream-node:", e.message) _json = resp.json() for challenge in _json['challenges']: chal = Challenge(challenge.get('block'), challenge.get('seed')) self.challenges.append(chal) def answer_challenge(self, filename): enc_fname = self._enc_fname(filename) raise NotImplementedError
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import random from heartbeat import Challenge import requests from .utils import urlify from .exc import DownstreamError class DownstreamClient(object): def __init__(self, server_url): self.server = server_url.strip('/') self.challenges = [] def connect(self, url): raise NotImplementedError def store_path(self, path): raise NotImplementedError def get_chunk(self, hash): raise NotImplementedError def challenge(self, hash, challenge): raise NotImplementedError def answer(self, hash, hash_answer): raise NotImplementedError def _enc_fname(self, filename): return urlify(os.path.split(filename)[1]) def get_challenges(self, filename): enc_fname = urlify(os.path.split(filename)[1]) url = '%s/api/downstream/challenge/%s' % (self.server, enc_fname) resp = requests.get(url) try: resp.raise_for_status() except Exception as e: raise DownstreamError("Error connecting to downstream-node:", e.message) _json = resp.json() for challenge in _json['challenges']: chal = Challenge(challenge.get('block'), challenge.get('seed')) self.challenges.append(chal) def answer_challenge(self, filename): enc_fname = self._enc_fname(filename) raise NotImplementedError def random_challenge(self): random.choice(self.challenges)
Add random_challenge method to choose a challenge to answer
Add random_challenge method to choose a challenge to answer
Python
mit
Storj/downstream-farmer
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- import os +import random from heartbeat import Challenge import requests @@ -51,3 +52,6 @@ def answer_challenge(self, filename): enc_fname = self._enc_fname(filename) raise NotImplementedError + + def random_challenge(self): + random.choice(self.challenges)
3ba739dccb1753d15b7e1911d9da1ef021ee1fb4
gitxblob/commands/add.py
gitxblob/commands/add.py
"""usage: git-xblob add <path> [...]""" import os from ..utils import git def bail(code=1): print __doc__.strip() exit(code) def run_add(paths): if not paths: bail() missing_any = False for path in paths: if not os.path.exists(path): print path, 'does not exist' missing_any = True if missing_any: return 3 for path in paths: # Add it to the attributes file. head, tail = os.path.split(path) attributes_path = os.path.join(head, '.gitattributes') with open(attributes_path, 'a') as fh: fh.write('/%s filter=xblob\n' % tail) # Add the file and the attributes. git('add -f %s', attributes_path) git('add -f %s', path)
"""usage: git-xblob add <path> [...]""" import os import re from ..utils import git def bail(code=1): print __doc__.strip() exit(code) def run_add(paths): if not paths: bail() missing_any = False for path in paths: if not os.path.exists(path): print path, 'does not exist' missing_any = True if missing_any: return 3 for path in paths: # Add it to the attributes file. head, tail = os.path.split(path) # Clean up spaces. tail = re.sub(r'\s', '[[:space:]]', tail) attributes_path = os.path.join(head, '.gitattributes') with open(attributes_path, 'a') as fh: fh.write('/%s filter=xblob\n' % tail) # Add the file and the attributes. git('add -f %s', attributes_path) git('add -f %s', path)
Clean up spaces (a little)
Clean up spaces (a little)
Python
bsd-3-clause
mikeboers/git-xblob
--- +++ @@ -1,6 +1,7 @@ """usage: git-xblob add <path> [...]""" import os +import re from ..utils import git @@ -28,6 +29,9 @@ # Add it to the attributes file. head, tail = os.path.split(path) + # Clean up spaces. + tail = re.sub(r'\s', '[[:space:]]', tail) + attributes_path = os.path.join(head, '.gitattributes') with open(attributes_path, 'a') as fh: fh.write('/%s filter=xblob\n' % tail)
b4b87f00f170828accb1974d51fc446694d8334c
examples/rev_rxns.py
examples/rev_rxns.py
"""Example of reversible reaction.""" import os from chemkinlib.utils import Parser from chemkinlib.reactions import ReactionSystems from chemkinlib.config import DATA_DIRECTORY # USER INPUT: reaction (xml) file xml_filename = os.path.join(DATA_DIRECTORY, "rxns_reversible.xml") parser = Parser.ReactionParser(xml_filename) # USER INPUTS (concentrations and temperatures) concentration = ({'H':1, 'H2':1, 'H2O':1, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1}) temperature = 1000 # Set up reaction system rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list, parser.NASA_poly_coefs, temperature, concentration) # Compute and sort reaction rates rxnrates_dict = rxnsys.sort_reaction_rates() # display reaction rates by species for k, v in rxnrates_dict.items(): print("d[{0}]/dt : \t {1:e}".format(k, v))
"""Example of reversible reaction.""" import os from chemkinlib.utils import Parser from chemkinlib.reactions import ReactionSystems from chemkinlib.config import DATA_DIRECTORY # USER INPUT: reaction (xml) file xml_filename = os.path.join(DATA_DIRECTORY, "rxns_reversible.xml") parser = Parser.ReactionParser(xml_filename) # USER INPUTS (concentrations and temperatures) concentration = ({'H':1, 'H2':1, 'H2O':1, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1}) temperature = 1000 # Set up reaction system rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list, parser.NASA_poly_coefs, temperature, concentration) #compute the concentration change with timestep for i in range(10): dt = 0.001 print(rxnsys.step(dt)) # Compute and sort reaction rates rxnrates_dict = rxnsys.sort_reaction_rates() # display reaction rates by species for k, v in rxnrates_dict.items(): print("d[{0}]/dt : \t {1:e}".format(k, v))
Add documentation of the new functions
Add documentation of the new functions
Python
mit
cs207-group11/cs207-FinalProject,hsim13372/cs207-FinalProject,krmotwani/cs207-FinalProject
--- +++ @@ -23,6 +23,11 @@ temperature, concentration) +#compute the concentration change with timestep +for i in range(10): + dt = 0.001 + print(rxnsys.step(dt)) + # Compute and sort reaction rates rxnrates_dict = rxnsys.sort_reaction_rates()
8eea97c45c3e40299db251867eb01a862ca1fdbc
app/dao/__init__.py
app/dao/__init__.py
from app import db from app.dao.decorators import transactional @transactional def dao_create_record(record): db.session.add(record) @transactional def dao_update_record(data_type, id, **kwargs): return data_type.query.filter_by(id=id).update( kwargs ) def dao_get_record_by_id(data_type, id): return data_type.query.filter_by(id=id).one() def dao_get_record_by_old_id(data_type, old_id): return data_type.query.filter_by(old_id=old_id).first()
from app import db from app.dao.decorators import transactional @transactional def dao_create_record(record): db.session.add(record) # @transactional # def dao_update_record(data_type, id, **kwargs): # return data_type.query.filter_by(id=id).update( # kwargs # ) # def dao_get_record_by_id(data_type, id): # return data_type.query.filter_by(id=id).one() # def dao_get_record_by_old_id(data_type, old_id): # return data_type.query.filter_by(old_id=old_id).first()
Comment out generic db functions as not used yet
Comment out generic db functions as not used yet
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
--- +++ @@ -7,16 +7,16 @@ db.session.add(record) -@transactional -def dao_update_record(data_type, id, **kwargs): - return data_type.query.filter_by(id=id).update( - kwargs - ) +# @transactional +# def dao_update_record(data_type, id, **kwargs): +# return data_type.query.filter_by(id=id).update( +# kwargs +# ) -def dao_get_record_by_id(data_type, id): - return data_type.query.filter_by(id=id).one() +# def dao_get_record_by_id(data_type, id): +# return data_type.query.filter_by(id=id).one() -def dao_get_record_by_old_id(data_type, old_id): - return data_type.query.filter_by(old_id=old_id).first() +# def dao_get_record_by_old_id(data_type, old_id): +# return data_type.query.filter_by(old_id=old_id).first()
bd761accdc38b4ed71f94048c3d9ceae05859925
fabfile/tasks/ntp.py
fabfile/tasks/ntp.py
from fabfile.config import * @task @roles('all') def get_all_time(): date = run("DATE=$( sudo date ); DATEMILLISEC=$( sudo date +%s ); echo $DATE; echo $DATEMILLISEC") return tuple(date.split('\r\n')) @task @roles('build') def verify_time_all(): result = execute('get_all_time') print result all_time = [int(date_in_millisec) for date, date_in_millisec in result.values()] all_time.sort() if (all_time[-1] - all_time[0]) > 120: raise RuntimeError("Time not synced in the nodes, Please sync and proceed:\n %s" % result) else: print "Time synced in the nodes, Proceeding to install/provision."
from fabfile.config import * @task @roles('all') def get_all_time(): date = run("DATE=$( sudo date ); DATEMILLISEC=$( sudo date +%s ); echo $DATE; echo $DATEMILLISEC") return tuple(date.split('\r\n')) @task @parallel @roles('build') def verify_time_all(): result = execute('get_all_time') all_time = [] for dates in result.values(): try: (date, date_in_millisec) = dates all_time.append(int(date_in_millisec)) except ValueError: print "ERROR: %s" % dates all_time.sort() if (all_time[-1] - all_time[0]) > 240: raise RuntimeError("Time not synced in the nodes," " Please sync and proceed:\n %s %s %s" % (result, all_time[-1], all_time[0])) else: print "Time synced in the nodes, Proceeding to install/provision."
Increase the time delta from 120 to 240 milli secs to decide the failure.
Increase the time delta from 120 to 240 milli secs to decide the failure. Change-Id: Ic51da36d79d4cd4ccac342d7242e56a23e21c07f
Python
apache-2.0
Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils
--- +++ @@ -7,16 +7,22 @@ return tuple(date.split('\r\n')) @task +@parallel @roles('build') def verify_time_all(): result = execute('get_all_time') - print result - all_time = [int(date_in_millisec) for date, date_in_millisec in result.values()] + all_time = [] + for dates in result.values(): + try: + (date, date_in_millisec) = dates + all_time.append(int(date_in_millisec)) + except ValueError: + print "ERROR: %s" % dates all_time.sort() - - if (all_time[-1] - all_time[0]) > 120: - raise RuntimeError("Time not synced in the nodes, Please sync and proceed:\n %s" % result) + + if (all_time[-1] - all_time[0]) > 240: + raise RuntimeError("Time not synced in the nodes," + " Please sync and proceed:\n %s %s %s" % + (result, all_time[-1], all_time[0])) else: print "Time synced in the nodes, Proceeding to install/provision." - -
93e46310b8ea9e61dbabf02bd3dd4b6b6748dd6e
erpnext/accounts/doctype/bank/bank_dashboard.py
erpnext/accounts/doctype/bank/bank_dashboard.py
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'bank', 'non_standard_fieldnames': { 'Paymnet Order': 'company_bank' }, 'transactions': [ { 'label': _('Bank Deatils'), 'items': ['Bank Account', 'Bank Guarantee'] }, { 'items': ['Payment Order'] } ] }
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'bank', 'transactions': [ { 'label': _('Bank Deatils'), 'items': ['Bank Account', 'Bank Guarantee'] } ] }
Remove payment order from bank dashboard
fix: Remove payment order from bank dashboard
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
--- +++ @@ -6,16 +6,10 @@ def get_data(): return { 'fieldname': 'bank', - 'non_standard_fieldnames': { - 'Paymnet Order': 'company_bank' - }, 'transactions': [ { 'label': _('Bank Deatils'), 'items': ['Bank Account', 'Bank Guarantee'] - }, - { - 'items': ['Payment Order'] } ] }
4b061a25b579c5463b963bcba580284c8dc64903
appengine/isolate/main_frontend.py
appengine/isolate/main_frontend.py
# Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """This modules is imported by AppEngine and defines the 'app' object. It is a separate file so that application bootstrapping code like ereporter2, that shouldn't be done in unit tests, can be done safely. This file must be tested via a smoke test. """ import os import sys import endpoints APP_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(APP_DIR, 'components', 'third_party')) from components import ereporter2 from components import utils import handlers_endpoints import handlers_frontend def create_application(): ereporter2.register_formatter() # App that serves HTML pages and old API. frontend = handlers_frontend.create_application(False) # App that serves new endpoints API. api = endpoints.api_server([handlers_endpoints.isolate_api]) return frontend, api frontend_app, endpoints_app = create_application()
# Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """This modules is imported by AppEngine and defines the 'app' object. It is a separate file so that application bootstrapping code like ereporter2, that shouldn't be done in unit tests, can be done safely. This file must be tested via a smoke test. """ import os import sys import endpoints APP_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(APP_DIR, 'components', 'third_party')) from components import ereporter2 from components import utils import handlers_endpoints import handlers_frontend def create_application(): ereporter2.register_formatter() # App that serves HTML pages and old API. frontend = handlers_frontend.create_application(False) # App that serves new endpoints API. api = endpoints.api_server([handlers_endpoints.IsolateServer]) return frontend, api frontend_app, endpoints_app = create_application()
Fix typo in isolate server.
Fix typo in isolate server. Did I say we need more integration tests? TBR=vadimsh@chromium.org BUG= Review URL: https://codereview.appspot.com/220370043
Python
apache-2.0
luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py
--- +++ @@ -30,7 +30,7 @@ # App that serves HTML pages and old API. frontend = handlers_frontend.create_application(False) # App that serves new endpoints API. - api = endpoints.api_server([handlers_endpoints.isolate_api]) + api = endpoints.api_server([handlers_endpoints.IsolateServer]) return frontend, api
c72decbfaddc6fe697c8afa5330a40afded6ef6f
test/test_pickle.py
test/test_pickle.py
import RMF import cPickle b = RMF.BufferHandle() f = RMF.create_rmf_buffer(b) f.get_root_node().add_child("hi", RMF.ORGANIZATIONAL) del f picklestring = cPickle.dumps(b) bb = cPickle.loads(picklestring) f = RMF.open_rmf_buffer_read_only(bb) print f.get_root_node().get_children()[0]
import RMF try: import cPickle as pickle except ImportError: import pickle b = RMF.BufferHandle() f = RMF.create_rmf_buffer(b) f.get_root_node().add_child("hi", RMF.ORGANIZATIONAL) del f picklestring = pickle.dumps(b) bb = pickle.loads(picklestring) f = RMF.open_rmf_buffer_read_only(bb) print f.get_root_node().get_children()[0]
Fix pickle import in Python 3.
Fix pickle import in Python 3.
Python
apache-2.0
salilab/rmf,salilab/rmf,salilab/rmf,salilab/rmf
--- +++ @@ -1,5 +1,8 @@ import RMF -import cPickle +try: + import cPickle as pickle +except ImportError: + import pickle b = RMF.BufferHandle() f = RMF.create_rmf_buffer(b) @@ -8,8 +11,8 @@ del f -picklestring = cPickle.dumps(b) -bb = cPickle.loads(picklestring) +picklestring = pickle.dumps(b) +bb = pickle.loads(picklestring) f = RMF.open_rmf_buffer_read_only(bb) print f.get_root_node().get_children()[0]
3c8bc9d7c7951e0728951c0e401a1b121e8a39b6
open_municipio/locations/admin.py
open_municipio/locations/admin.py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from open_municipio.locations.models import Location class LocationAdmin(admin.ModelAdmin): pass admin.site.register(Location, LocationAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from open_municipio.locations.models import Location class LocationAdmin(admin.ModelAdmin): list_display = ('name', 'count') admin.site.register(Location, LocationAdmin)
Add a column for count field
Add a column for count field
Python
agpl-3.0
openpolis/open_municipio,openpolis/open_municipio,openpolis/open_municipio,openpolis/open_municipio
--- +++ @@ -4,6 +4,6 @@ class LocationAdmin(admin.ModelAdmin): - pass + list_display = ('name', 'count') admin.site.register(Location, LocationAdmin)
7f4d6c9b1ba69cdb0af8774edb0eeb415aa25d8f
tests/test_model.py
tests/test_model.py
from todoman.model import Database def test_querying(create, tmpdir): for list in 'abc': for i, location in enumerate('abc'): create( 'test{}.ics'.format(i), ('SUMMARY:test_querying\r\n' 'LOCATION:{}\r\n').format(location), list_name=list ) db = Database( [str(tmpdir.ensure_dir(l)) for l in 'abc'], str(tmpdir.join('cache')) ) assert len(set(db.todos())) == 9 assert len(set(db.todos(lists='ab'))) == 6 assert len(set(db.todos(lists='ab', location='a'))) == 2
from datetime import datetime from dateutil.tz.tz import tzoffset from todoman.model import Database def test_querying(create, tmpdir): for list in 'abc': for i, location in enumerate('abc'): create( 'test{}.ics'.format(i), ('SUMMARY:test_querying\r\n' 'LOCATION:{}\r\n').format(location), list_name=list ) db = Database( [str(tmpdir.ensure_dir(l)) for l in 'abc'], str(tmpdir.join('cache')) ) assert len(set(db.todos())) == 9 assert len(set(db.todos(lists='ab'))) == 6 assert len(set(db.todos(lists='ab', location='a'))) == 2 def test_retain_tz(tmpdir, runner, create, default_database): create( 'ar.ics', 'SUMMARY:blah.ar\n' 'DUE;VALUE=DATE-TIME;TZID=HST:20160102T000000\n' ) create( 'de.ics', 'SUMMARY:blah.de\n' 'DUE;VALUE=DATE-TIME;TZID=CET:20160102T000000\n' ) db = Database([tmpdir.join('default')], tmpdir.join('cache.sqlite')) todos = list(db.todos()) assert len(todos) == 2 assert todos[0].due == datetime( 2016, 1, 2, 0, 0, tzinfo=tzoffset(None, -36000) ) assert todos[1].due == datetime( 2016, 1, 2, 0, 0, tzinfo=tzoffset(None, 3600) )
Add tests to verify that we handle TZ properly
Add tests to verify that we handle TZ properly
Python
isc
rimshaakhan/todoman,hobarrera/todoman,Sakshisaraswat/todoman,AnubhaAgrawal/todoman,pimutils/todoman,asalminen/todoman
--- +++ @@ -1,3 +1,7 @@ +from datetime import datetime + +from dateutil.tz.tz import tzoffset + from todoman.model import Database @@ -19,3 +23,27 @@ assert len(set(db.todos())) == 9 assert len(set(db.todos(lists='ab'))) == 6 assert len(set(db.todos(lists='ab', location='a'))) == 2 + + +def test_retain_tz(tmpdir, runner, create, default_database): + create( + 'ar.ics', + 'SUMMARY:blah.ar\n' + 'DUE;VALUE=DATE-TIME;TZID=HST:20160102T000000\n' + ) + create( + 'de.ics', + 'SUMMARY:blah.de\n' + 'DUE;VALUE=DATE-TIME;TZID=CET:20160102T000000\n' + ) + + db = Database([tmpdir.join('default')], tmpdir.join('cache.sqlite')) + todos = list(db.todos()) + + assert len(todos) == 2 + assert todos[0].due == datetime( + 2016, 1, 2, 0, 0, tzinfo=tzoffset(None, -36000) + ) + assert todos[1].due == datetime( + 2016, 1, 2, 0, 0, tzinfo=tzoffset(None, 3600) + )
a01981b818ca97f57da5a75c3342178639c08e3c
tests/test_suite.py
tests/test_suite.py
#!/usr/bin/python from pywidl.pywidl import App import unittest from difflib import context_diff import os.path import sys class TestPyWIdl(unittest.TestCase): def _match(self, fromfile, tofile): diff = context_diff(open(fromfile).readlines(), open(tofile).readlines(), fromfile=fromfile, tofile=tofile) diff_clean = True for line in diff: if diff_clean: print diff_clean = False sys.stdout.write(line) return diff_clean def _buildDom(self, source): src = os.path.join("tests", "data", source) eta = os.path.join("tests", "data", "%s.dom" % source.rsplit('.', 1)[0]) rcv = os.path.join("tests", "received.dom") app = App(src, rcv, os.path.join("tests", "templates", "dom.mako")) app.run() self.assertTrue(self._match(eta, rcv)) def test_basics(self): self._buildDom("sample.idl") if __name__ == "__main__": unittest.main()
#!/usr/bin/python from pywidl.pywidl import App import unittest from difflib import context_diff import os import sys class TestPyWIdl(unittest.TestCase): def _match(self, fromfile, tofile): diff = context_diff(open(fromfile).readlines(), open(tofile).readlines(), fromfile=fromfile, tofile=tofile) diff_clean = True for line in diff: if diff_clean: print diff_clean = False sys.stdout.write(line) if diff_clean: os.remove(tofile) return diff_clean def _buildDom(self, source): src = os.path.join("tests", "data", source) eta = os.path.join("tests", "data", "%s.dom" % source.rsplit('.', 1)[0]) rcv = os.path.join("tests", "received.dom") app = App(src, rcv, os.path.join("tests", "templates", "dom.mako")) app.run() self.assertTrue(self._match(eta, rcv)) def test_basics(self): self._buildDom("sample.idl") if __name__ == "__main__": unittest.main()
Remove received after successful diff.
Remove received after successful diff.
Python
mit
VasilyStepanov/pywidl
--- +++ @@ -5,7 +5,7 @@ import unittest from difflib import context_diff -import os.path +import os import sys @@ -20,6 +20,9 @@ if diff_clean: print diff_clean = False sys.stdout.write(line) + + if diff_clean: + os.remove(tofile) return diff_clean
c89ce9429a85aaf0546c278c2de6fe5061e350e6
django-geojson/djgeojson/views.py
django-geojson/djgeojson/views.py
from http import HttpJSONResponse from serializers import Serializer as GeoJSONSerializer from django.views.generic import ListView class GeoJSONResponseMixin(object): """ A mixin that can be used to render a GeoJSON response. """ response_class = HttpJSONResponse """ Select fields for properties """ fields = [] """ Limit float precision """ precision = None """ Simplify geometries """ simplify = None """ Change projection of geometries """ srid = None def render_to_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ serializer = GeoJSONSerializer() response = self.response_class(**response_kwargs) serializer.serialize(self.get_queryset(), stream=response, fields=self.fields, simplify=self.simplify, srid=self.srid, precision=self.precision, ensure_ascii=False) return response class GeoJSONLayerView(GeoJSONResponseMixin, ListView): """ A generic view to serve a model as a layer. """
from django.views.generic import ListView from django.utils.decorators import method_decorator from django.views.decorators.gzip import gzip_page from .http import HttpJSONResponse from .serializers import Serializer as GeoJSONSerializer class GeoJSONResponseMixin(object): """ A mixin that can be used to render a GeoJSON response. """ response_class = HttpJSONResponse """ Select fields for properties """ fields = [] """ Limit float precision """ precision = None """ Simplify geometries """ simplify = None """ Change projection of geometries """ srid = None def render_to_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ serializer = GeoJSONSerializer() response = self.response_class(**response_kwargs) serializer.serialize(self.get_queryset(), stream=response, fields=self.fields, simplify=self.simplify, srid=self.srid, precision=self.precision, ensure_ascii=False) return response class GeoJSONLayerView(GeoJSONResponseMixin, ListView): """ A generic view to serve a model as a layer. """ @method_decorator(gzip_page) def dispatch(self, *args, **kwargs): return super(GeoJSONLayerView, self).dispatch(*args, **kwargs)
Add Gzip compression to geojson layer view
Add Gzip compression to geojson layer view
Python
bsd-2-clause
johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,camillemonchicourt/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,camillemonchicourt/Geotrek,mabhub/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin
--- +++ @@ -1,6 +1,9 @@ -from http import HttpJSONResponse -from serializers import Serializer as GeoJSONSerializer from django.views.generic import ListView +from django.utils.decorators import method_decorator +from django.views.decorators.gzip import gzip_page + +from .http import HttpJSONResponse +from .serializers import Serializer as GeoJSONSerializer class GeoJSONResponseMixin(object): @@ -34,3 +37,6 @@ """ A generic view to serve a model as a layer. """ + @method_decorator(gzip_page) + def dispatch(self, *args, **kwargs): + return super(GeoJSONLayerView, self).dispatch(*args, **kwargs)
5764b582fde86570fe15c71509c9b7d718d7303a
conference_scheduler/parameters.py
conference_scheduler/parameters.py
from typing import NamedTuple, Callable, List, Dict, Sequence import pulp from .resources import ScheduledItem def variables(events: Sequence, rooms: Sequence, slots: Sequence): """Defines the required instances of pulp.LpVariable Parameters ---------- events : List or Tuple of resources.Event rooms : List or Tuple of resources.Room slots : List or Tuple of resources.Slot Returns ------- dict mapping an instance of resource.ScheduledItem to an instance of pulp.LpVariable """ variables = { (events.index(event), rooms.index(room), slots.index(slot)): pulp.LpVariable( f'{event.name}_{room.name}_slot_{slots.index(slot)}', cat='Binary' ) for event in events for room in rooms for slot in slots } return variables def constraints(variables, events, rooms, slots): constraints = [] # Each event should be scheduled once and once only for event in events: constraints.append( sum( variables[( events.index(event), rooms.index(room), slots.index(slot) )] for room in rooms for slot in slots ) == 1 ) return constraints class Constraint(NamedTuple): function: Callable args: List kwargs: Dict operator: Callable value: int
from typing import Sequence import pulp def variables(events: Sequence, rooms: Sequence, slots: Sequence): """Defines the required instances of pulp.LpVariable Parameters ---------- events : List or Tuple of resources.Event rooms : List or Tuple of resources.Room slots : List or Tuple of resources.Slot Returns ------- dict mapping an instance of resource.ScheduledItem to an instance of pulp.LpVariable """ variables = { (events.index(event), rooms.index(room), slots.index(slot)): pulp.LpVariable( f'{event.name}_{room.name}_slot_{slots.index(slot)}', cat='Binary' ) for event in events for room in rooms for slot in slots } return variables def constraints(variables, events, rooms, slots): constraints = [] # Each event should be scheduled once and once only for event in events: constraints.append( sum( variables[( events.index(event), rooms.index(room), slots.index(slot) )] for room in rooms for slot in slots ) == 1 ) return constraints
Tidy up layout and remove redundant code
Tidy up layout and remove redundant code
Python
mit
PyconUK/ConferenceScheduler
--- +++ @@ -1,6 +1,5 @@ -from typing import NamedTuple, Callable, List, Dict, Sequence +from typing import Sequence import pulp -from .resources import ScheduledItem def variables(events: Sequence, rooms: Sequence, slots: Sequence): @@ -23,10 +22,10 @@ """ variables = { (events.index(event), rooms.index(room), slots.index(slot)): - pulp.LpVariable( - f'{event.name}_{room.name}_slot_{slots.index(slot)}', - cat='Binary' - ) + pulp.LpVariable( + f'{event.name}_{room.name}_slot_{slots.index(slot)}', + cat='Binary' + ) for event in events for room in rooms for slot in slots } return variables @@ -49,11 +48,3 @@ ) return constraints - - -class Constraint(NamedTuple): - function: Callable - args: List - kwargs: Dict - operator: Callable - value: int
1a18bfed90f6423a0c52b3f3fe523b4ed77188af
examples/example_windows.py
examples/example_windows.py
import rumps window = rumps.Window('Nothing...', 'ALERTZ') window.title = 'WINDOWS jk' window.message = 'Something.' window.default_text = 'eh' response = window.run() print response window.add_buttons('One', 'Two', 'Three') print window.run() print response
import rumps window = rumps.Window('Nothing...', 'ALERTZ') window.title = 'WINDOWS jk' window.message = 'Something.' window.default_text = 'eh' response = window.run() print (response) window.add_buttons('One', 'Two', 'Three') print (window.run())
Update example for Python 3
Update example for Python 3
Python
bsd-3-clause
jaredks/rumps,cbenhagen/rumps
--- +++ @@ -6,9 +6,8 @@ window.default_text = 'eh' response = window.run() -print response +print (response) window.add_buttons('One', 'Two', 'Three') -print window.run() -print response +print (window.run())
2d379a3bd04d2b687c719cb9ccca5f289b434d00
plenum/server/i3pc_watchers.py
plenum/server/i3pc_watchers.py
from typing import Callable, Iterable from plenum.server.quorums import Quorums class NetworkI3PCWatcher: def __init__(self, cb: Callable): self.nodes = set() self.connected = set() self.callback = cb self.quorums = Quorums(0) def connect(self, name: str): self.connected.add(name) def disconnect(self, name: str): had_consensus = self._has_consensus() self.connected.discard(name) if had_consensus and not self._has_consensus(): self.callback() def set_nodes(self, nodes: Iterable[str]): self.nodes = set(nodes) self.quorums = Quorums(len(self.nodes)) def _has_consensus(self): return self.quorums.weak.is_reached(len(self.connected))
from typing import Callable, Iterable from plenum.server.quorums import Quorums class NetworkI3PCWatcher: def __init__(self, cb: Callable): self._nodes = set() self.connected = set() self.callback = cb self.quorums = Quorums(0) def connect(self, name: str): self.connected.add(name) def disconnect(self, name: str): had_consensus = self._has_consensus() self.connected.discard(name) if had_consensus and not self._has_consensus(): self.callback() @property def nodes(self): return self._nodes def set_nodes(self, nodes: Iterable[str]): self._nodes = set(nodes) self.quorums = Quorums(len(self._nodes)) def _has_consensus(self): return self.quorums.weak.is_reached(len(self.connected))
Make interface of NetworkI3PCWatcher more clear
INDY-1199: Make interface of NetworkI3PCWatcher more clear Signed-off-by: Sergey Khoroshavin <b770466c7a06c5fe47531d5f0e31684f1131354d@dsr-corporation.com>
Python
apache-2.0
evernym/plenum,evernym/zeno
--- +++ @@ -4,7 +4,7 @@ class NetworkI3PCWatcher: def __init__(self, cb: Callable): - self.nodes = set() + self._nodes = set() self.connected = set() self.callback = cb self.quorums = Quorums(0) @@ -18,9 +18,13 @@ if had_consensus and not self._has_consensus(): self.callback() + @property + def nodes(self): + return self._nodes + def set_nodes(self, nodes: Iterable[str]): - self.nodes = set(nodes) - self.quorums = Quorums(len(self.nodes)) + self._nodes = set(nodes) + self.quorums = Quorums(len(self._nodes)) def _has_consensus(self): return self.quorums.weak.is_reached(len(self.connected))
85cf0af73ddfdce0281a112e4e86d1104e0222e1
appengine_config.py
appengine_config.py
import os import site import sys approot = os.path.dirname(__file__) sys.path.append(os.path.join(approot, 'lib')) site.addsitedir(os.path.join(approot, 'site-packages'))
import os import site import sys approot = os.path.dirname(__file__) sys.path.append(os.path.join(approot, 'lib')) site.addsitedir(os.path.join(approot, 'site-packages')) def webapp_add_wsgi_middleware(app): from google.appengine.ext.appstats import recording app = recording.appstats_wsgi_middleware(app) return app
Add the appstats recording middleware
Add the appstats recording middleware
Python
mit
xchewtoyx/pulldb
--- +++ @@ -5,3 +5,8 @@ approot = os.path.dirname(__file__) sys.path.append(os.path.join(approot, 'lib')) site.addsitedir(os.path.join(approot, 'site-packages')) + +def webapp_add_wsgi_middleware(app): + from google.appengine.ext.appstats import recording + app = recording.appstats_wsgi_middleware(app) + return app
d209020be5369345e04ba5d5cdd30cd8538409a1
tt/utils.py
tt/utils.py
def without_spaces(the_str): return "".join(the_str.split())
def without_spaces(the_str): return "".join(the_str.split()) def listwise_to_str(the_list): return list(map(str, the_list))
Add utility method for converting all elements in list to string.
Add utility method for converting all elements in list to string.
Python
mit
welchbj/tt,welchbj/tt,welchbj/tt
--- +++ @@ -1,2 +1,5 @@ def without_spaces(the_str): return "".join(the_str.split()) + +def listwise_to_str(the_list): + return list(map(str, the_list))
7b758788bdf8ca52d6b75892d8ee97484188d699
bookworm/settings_mobile.py
bookworm/settings_mobile.py
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True SESSION_COOKIE_NAME = 'bookworm_mobile'
Change cookie name for mobile setting
Change cookie name for mobile setting
Python
bsd-3-clause
srilatha44/threepress,srilatha44/threepress,srilatha44/threepress,srilatha44/threepress
--- +++ @@ -12,3 +12,4 @@ TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True +SESSION_COOKIE_NAME = 'bookworm_mobile'
e909759730be51a16fb7656de6a9844fdbf8fb2e
readthedocs/search/serializers.py
readthedocs/search/serializers.py
import logging from pprint import pformat from rest_framework import serializers log = logging.getLogger(__name__) class PageSearchSerializer(serializers.Serializer): project = serializers.CharField() version = serializers.CharField() title = serializers.CharField() path = serializers.CharField() link = serializers.SerializerMethodField() highlight = serializers.SerializerMethodField() def get_link(self, obj): projects_url = self.context.get('projects_url') if projects_url: docs_url = projects_url[obj.project] return docs_url + obj.path def get_highlight(self, obj): highlight = getattr(obj.meta, 'highlight', None) if highlight: for num, result in enumerate(highlight.content): # Change results to turn newlines in highlight into periods # https://github.com/rtfd/readthedocs.org/issues/5168 new_text = result.replace('\n', '. ') highlight.content[num] = new_text ret = highlight.to_dict() log.debug('API Search highlight: %s', pformat(ret)) return ret
import logging from pprint import pformat from rest_framework import serializers log = logging.getLogger(__name__) class PageSearchSerializer(serializers.Serializer): project = serializers.CharField() version = serializers.CharField() title = serializers.CharField() path = serializers.CharField() link = serializers.SerializerMethodField() highlight = serializers.SerializerMethodField() def get_link(self, obj): projects_url = self.context.get('projects_url') if projects_url: docs_url = projects_url[obj.project] return docs_url + obj.path def get_highlight(self, obj): highlight = getattr(obj.meta, 'highlight', None) if highlight: if hasattr(highlight, 'content'): for num, result in enumerate(highlight.content): # Change results to turn newlines in highlight into periods # https://github.com/rtfd/readthedocs.org/issues/5168 new_text = result.replace('\n', '. ') highlight.content[num] = new_text ret = highlight.to_dict() log.debug('API Search highlight: %s', pformat(ret)) return ret
Check for content to highlight
Check for content to highlight
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
--- +++ @@ -23,11 +23,12 @@ def get_highlight(self, obj): highlight = getattr(obj.meta, 'highlight', None) if highlight: - for num, result in enumerate(highlight.content): - # Change results to turn newlines in highlight into periods - # https://github.com/rtfd/readthedocs.org/issues/5168 - new_text = result.replace('\n', '. ') - highlight.content[num] = new_text + if hasattr(highlight, 'content'): + for num, result in enumerate(highlight.content): + # Change results to turn newlines in highlight into periods + # https://github.com/rtfd/readthedocs.org/issues/5168 + new_text = result.replace('\n', '. ') + highlight.content[num] = new_text ret = highlight.to_dict() log.debug('API Search highlight: %s', pformat(ret)) return ret
a67b2c7280ab7e5ae831d372b1fc81f0a2f1f2ce
h5py/tests/hl/test_deprecation.py
h5py/tests/hl/test_deprecation.py
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2018 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Tests that deprecations work correctly """ from __future__ import absolute_import import h5py from ..common import ut, TestCase class TestDeprecations(TestCase): def test_highlevel_access(self): warning_message = ( "The h5py.highlevel module is deprecated, code should import " "directly from h5py, e.g. 'from h5py import File'." ) with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning: hl = h5py.highlevel
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2018 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Tests that deprecations work correctly """ from __future__ import absolute_import import h5py from h5py.h5py_warnings import H5pyDeprecationWarning from ..common import ut, TestCase class TestDeprecations(TestCase): def test_highlevel_access(self): warning_message = ( "The h5py.highlevel module is deprecated, code should import " "directly from h5py, e.g. 'from h5py import File'." ) with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning: File = h5py.highlevel.File
Fix test which appeared to not be run
BUG: Fix test which appeared to not be run
Python
bsd-3-clause
h5py/h5py,h5py/h5py,h5py/h5py
--- +++ @@ -13,6 +13,7 @@ from __future__ import absolute_import import h5py +from h5py.h5py_warnings import H5pyDeprecationWarning from ..common import ut, TestCase @@ -24,4 +25,4 @@ "directly from h5py, e.g. 'from h5py import File'." ) with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning: - hl = h5py.highlevel + File = h5py.highlevel.File
3c7954ea497649a4cd6520842151deb632bc4723
tools/windows/eclipse_make.py
tools/windows/eclipse_make.py
#!/usr/bin/env python # # Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths # to Windows paths, for Eclipse from __future__ import print_function, division import sys import subprocess import os.path import re UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+') paths = {} def check_path(path): try: return paths[path] except KeyError: pass paths[path] = path # cache as failed, replace with success if it works try: winpath = subprocess.check_output(["cygpath", "-w", path]).strip() except subprocess.CalledProcessError: return path # something went wrong running cygpath, assume this is not a path! if not os.path.exists(winpath): return path # not actually a valid path winpath = winpath.replace("\\", "/") # make consistent with forward-slashes used elsewhere paths[path] = winpath return winpath def main(): print("Running make in '%s'" % check_path(os.getcwd())) make = subprocess.Popen(["make"] + sys.argv[1:] + ["BATCH_BUILD=1"], stdout=subprocess.PIPE) for line in iter(make.stdout.readline, ''): line = re.sub(UNIX_PATH_RE, lambda m: check_path(m.group(0)), line) print(line.rstrip()) sys.exit(make.wait()) if __name__ == "__main__": main()
#!/usr/bin/env python # # Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths # to Windows paths, for Eclipse from __future__ import print_function, division import sys import subprocess import os.path import re UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+') paths = {} def check_path(path): try: return paths[path] except KeyError: pass paths[path] = path # cache as failed, replace with success if it works try: winpath = subprocess.check_output(["cygpath", "-w", path]).decode().strip() except subprocess.CalledProcessError: return path # something went wrong running cygpath, assume this is not a path! if not os.path.exists(winpath): return path # not actually a valid path winpath = winpath.replace("\\", "/") # make consistent with forward-slashes used elsewhere paths[path] = winpath return winpath def main(): print("Running make in '%s'" % check_path(os.getcwd())) make = subprocess.Popen(["make"] + sys.argv[1:] + ["BATCH_BUILD=1"], stdout=subprocess.PIPE) for line in iter(make.stdout.readline, ''): line = re.sub(UNIX_PATH_RE, lambda m: check_path(m.group(0)), line) print(line.rstrip()) sys.exit(make.wait()) if __name__ == "__main__": main()
Fix Python 3 incompatibility for building with Eclipse on Windows
tools: Fix Python 3 incompatibility for building with Eclipse on Windows
Python
apache-2.0
espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf
--- +++ @@ -20,7 +20,7 @@ pass paths[path] = path # cache as failed, replace with success if it works try: - winpath = subprocess.check_output(["cygpath", "-w", path]).strip() + winpath = subprocess.check_output(["cygpath", "-w", path]).decode().strip() except subprocess.CalledProcessError: return path # something went wrong running cygpath, assume this is not a path! if not os.path.exists(winpath):
52679561fce3d03c0c2838c209067b070d664e94
postgresql/types/io/pg_network.py
postgresql/types/io/pg_network.py
from .. import INETOID, CIDROID, MACADDROID from . import lib try: import ipaddress except ImportError: import ipaddr as ipaddress oid_to_type = { MACADDROID : str, INETOID: ipaddress._IPAddressBase, CIDROID: ipaddress._BaseNetwork, } def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address): a = Constructor(ob) return pack((a.version, None, a.packed)) def cidr_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_network): a = Constructor(ob) return pack((a.version, a.prefixlen, a.network_address.packed)) def inet_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_address): version, mask, data = unpack(data) return Constructor(data) def cidr_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_network): version, mask, data = unpack(data) r = Constructor(data) r._prefixlen = mask return Constructor(str(r)) oid_to_io = { MACADDROID : (lib.macaddr_pack, lib.macaddr_unpack, str), CIDROID : (cidr_pack, cidr_unpack, str), INETOID : (inet_pack, inet_unpack, str), }
from .. import INETOID, CIDROID, MACADDROID from . import lib try: import ipaddress except ImportError: import ipaddr as ipaddress oid_to_type = { MACADDROID : str, INETOID: ipaddress._IPAddressBase, CIDROID: ipaddress._BaseNetwork, } def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address): a = Constructor(ob) return pack((a.version, None, a.packed)) def cidr_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_network): a = Constructor(ob) return pack((a.version, a.prefixlen, a.network_address.packed)) def inet_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_address): version, mask, data = unpack(data) return Constructor(data) def cidr_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_network): version, mask, data = unpack(data) return Constructor(data).supernet(new_prefix=mask) oid_to_io = { MACADDROID : (lib.macaddr_pack, lib.macaddr_unpack, str), CIDROID : (cidr_pack, cidr_unpack, str), INETOID : (inet_pack, inet_unpack, str), }
Use supernet interface for building the appropriate network.
Use supernet interface for building the appropriate network.
Python
bsd-3-clause
python-postgres/fe,python-postgres/fe
--- +++ @@ -25,9 +25,7 @@ def cidr_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_network): version, mask, data = unpack(data) - r = Constructor(data) - r._prefixlen = mask - return Constructor(str(r)) + return Constructor(data).supernet(new_prefix=mask) oid_to_io = { MACADDROID : (lib.macaddr_pack, lib.macaddr_unpack, str),
d3904489f03aaba94354be548589564d2104082d
ci/generate_pipeline_yml.py
ci/generate_pipeline_yml.py
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2', 'multi-az'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
Remove multi-az env from CI pipeline.
Remove multi-az env from CI pipeline.
Python
apache-2.0
cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator
--- +++ @@ -3,7 +3,7 @@ import os from jinja2 import Template -clusters = ['1-12', '2-0', '2-1', '2-2', 'multi-az'] +clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f:
f367d3122084c85e11efeb20d560a856e9f24d0e
zuice/django.py
zuice/django.py
django = __import__("django.conf.urls.defaults", {}) from zuice import Injector def _view_builder(bindings): def view(request, view_class, **kwargs): view_injector = Injector(bindings) view = view_injector.get_from_type(view_class) bindings_for_response = bindings.copy() bindings_for_response.bind('request').to_instance(request) for item in kwargs.iteritems(): bindings_for_response.bind_name(item[0]).to_instance(item[1]) response_injector = Injector(bindings_for_response) response = response_injector.call(view.respond) return response.render(request) return view def url_to_class_builder(bindings): def url_to_class(regex, view_class, kwargs=None, name=None): if kwargs is None: kwargs = {} kwargs['view_class'] = view_class return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name) return url_to_class
django = __import__("django.conf.urls.defaults", {}) from zuice import Injector def _view_builder(bindings): def view(request, view_class, **kwargs): view_injector = Injector(bindings) view = view_injector.get_from_type(view_class) bindings_for_response = bindings.copy() bindings_for_response.bind('request').to_instance(request) for item in kwargs.iteritems(): bindings_for_response.bind_name(item[0]).to_instance(item[1]) response_injector = Injector(bindings_for_response) response = response_injector.call(view.respond) return response.render(request) return view def url_to_class_builder(bindings): view = _view_builder(bindings.copy()) def url_to_class(regex, view_class, kwargs=None, name=None): if kwargs is None: kwargs = {} kwargs['view_class'] = view_class return django.conf.urls.defaults.url(regex, view, kwargs, name=name) return url_to_class
Refactor url_to_class_builder so that the view is only built once
Refactor url_to_class_builder so that the view is only built once
Python
bsd-2-clause
mwilliamson/zuice
--- +++ @@ -19,11 +19,12 @@ return view def url_to_class_builder(bindings): + view = _view_builder(bindings.copy()) def url_to_class(regex, view_class, kwargs=None, name=None): if kwargs is None: kwargs = {} kwargs['view_class'] = view_class - return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name) + return django.conf.urls.defaults.url(regex, view, kwargs, name=name) return url_to_class
38006f3b68edcdd7707d2b9056fa6564126747d0
infosystem/common/subsystem/__init__.py
infosystem/common/subsystem/__init__.py
import flask from infosystem.common.subsystem.controller import * from infosystem.common.subsystem.driver import * from infosystem.common.subsystem.manager import * from infosystem.common.subsystem.router import * class Subsystem(flask.Blueprint): def __init__(self, resource, router=None, controller=None, manager=None, driver=None, operations=[]): super().__init__(resource.collection(), resource.collection()) driver = driver(resource) if driver else Driver(resource) manager = manager(driver) if manager else Manager(driver) controller = controller(manager, resource.individual(), resource.collection()) if controller else Controller(manager, resource.individual(), resource.collection()) router = router(controller, resource.collection(), routes=operations) if router else Router(controller, resource.collection(), routes=operations) self.name = resource.collection() self.router = router self.manager = manager self.register_routes() def register_routes(self): for route in self.router.routes: self.add_url_rule( route['url'], view_func=route['callback'], methods=[route['method']])
import flask from infosystem.common.subsystem.controller import * from infosystem.common.subsystem.driver import * from infosystem.common.subsystem.manager import * from infosystem.common.subsystem.router import * class Subsystem(flask.Blueprint): def __init__(self, resource=None, router=None, controller=None, manager=None, driver=None, individual_name=None, collection_name=None, operations=[]): individual_name = individual_name or resource.individual() collection_name = collection_name or resource.collection() super().__init__(collection_name, collection_name) driver = driver(resource) if driver else Driver(resource) if resource else None manager = manager(driver) if manager else Manager(driver) controller = controller(manager, individual_name, collection_name) if controller else Controller(manager, individual_name, collection_name) router = router(controller, collection_name, routes=operations) if router else Router(controller, collection_name, routes=operations) self.name = collection_name self.router = router self.manager = manager self.register_routes() def register_routes(self): for route in self.router.routes: self.add_url_rule( route['url'], view_func=route['callback'], methods=[route['method']])
Allow subsystems to not map a sqlachemy entity
Allow subsystems to not map a sqlachemy entity
Python
apache-2.0
samueldmq/infosystem
--- +++ @@ -8,20 +8,22 @@ class Subsystem(flask.Blueprint): - def __init__(self, resource, router=None, controller=None, manager=None, - driver=None, operations=[]): - super().__init__(resource.collection(), resource.collection()) + def __init__(self, resource=None, router=None, controller=None, manager=None, + driver=None, individual_name=None, collection_name=None, operations=[]): + individual_name = individual_name or resource.individual() + collection_name = collection_name or resource.collection() - driver = driver(resource) if driver else Driver(resource) + super().__init__(collection_name, collection_name) + + driver = driver(resource) if driver else Driver(resource) if resource else None manager = manager(driver) if manager else Manager(driver) - controller = controller(manager, resource.individual(), resource.collection()) if controller else Controller(manager, resource.individual(), resource.collection()) - router = router(controller, resource.collection(), routes=operations) if router else Router(controller, resource.collection(), routes=operations) + controller = controller(manager, individual_name, collection_name) if controller else Controller(manager, individual_name, collection_name) + router = router(controller, collection_name, routes=operations) if router else Router(controller, collection_name, routes=operations) - self.name = resource.collection() + self.name = collection_name self.router = router self.manager = manager self.register_routes() - def register_routes(self): for route in self.router.routes:
bfe97d155d968a35492ac6156ed5d6a3decf1dfc
src/config/settings/development.py
src/config/settings/development.py
"""Django configuration for local development environment.""" from .testing import * DEBUG = True
"""Django configuration for local development environment.""" from .testing import * DEBUG = True # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': get_secret('DB_NAME'), 'USER': get_secret('DB_USER'), 'PASSWORD': get_secret('DB_PASSWORD'), 'HOST': get_secret('DB_HOST'), 'PORT': get_secret('DB_PORT'), } }
Configure database for testing environment
Configure database for testing environment
Python
agpl-3.0
FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de
--- +++ @@ -2,3 +2,15 @@ from .testing import * DEBUG = True + +# Database +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': get_secret('DB_NAME'), + 'USER': get_secret('DB_USER'), + 'PASSWORD': get_secret('DB_PASSWORD'), + 'HOST': get_secret('DB_HOST'), + 'PORT': get_secret('DB_PORT'), + } +}
eac05dfe5c4190cc10b00d18aa9f03344eb3a6ea
fastats/core/single_pass.py
fastats/core/single_pass.py
import numpy as np from fastats.core.decorator import fs def value(x): # pragma: no cover return x @fs def single_pass(x): """ Performs a single iteration over the first dimension of `x`. Tests ----- >>> def square(x): ... return x * x >>> data = np.arange(10) >>> single_pass(data, value=square) array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) >>> import math >>> def calc(x): ... return 2 * math.log(x) >>> single_pass(data[1:], value=calc) array([0, 1, 2, 2, 3, 3, 3, 4, 4]) """ result = np.zeros_like(x) for i in range(x.shape[0]): result[i] = value(x[i]) return result if __name__ == '__main__': import pytest pytest.main([__file__])
import numpy as np from fastats.core.decorator import fs def value(x): return x @fs def single_pass(x): """ Performs a single iteration over the first dimension of `x`. Tests ----- >>> def square(x): ... return x * x >>> data = np.arange(10) >>> single_pass(data, value=square) array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) >>> import math >>> def calc(x): ... return 2 * math.log(x) >>> single_pass(data[1:], value=calc) array([0, 1, 2, 2, 3, 3, 3, 4, 4]) """ result = np.zeros_like(x) for i in range(x.shape[0]): result[i] = value(x[i]) return result if __name__ == '__main__': import pytest pytest.main([__file__])
Remove spurious no cover pragma
Remove spurious no cover pragma
Python
mit
dwillmer/fastats,fastats/fastats
--- +++ @@ -4,7 +4,7 @@ from fastats.core.decorator import fs -def value(x): # pragma: no cover +def value(x): return x
1361b5ebb4afd0c3c80df5bf936f3817427cd917
apps/pages/views.py
apps/pages/views.py
from django.views.generic import DetailView from .models import Page class PageView(DetailView): model = Page def get_object(self, queryset=None): slug = self.kwargs.get('slug') if not slug: slug = 'index' return self.get_queryset().get(slug=slug)
from django.views.generic import DetailView from django.shortcuts import get_object_or_404 from .models import Page class PageView(DetailView): model = Page def get_object(self, queryset=None): slug = self.kwargs.get('slug') if not slug: slug = 'index' return get_object_or_404(self.get_queryset(), slug=slug)
Return 404 in case page is not found
Return 404 in case page is not found
Python
mit
MeirKriheli/debian.org.il,MeirKriheli/debian.org.il
--- +++ @@ -1,4 +1,5 @@ from django.views.generic import DetailView +from django.shortcuts import get_object_or_404 from .models import Page @@ -12,4 +13,4 @@ slug = self.kwargs.get('slug') if not slug: slug = 'index' - return self.get_queryset().get(slug=slug) + return get_object_or_404(self.get_queryset(), slug=slug)
0668192acf349e02694daf6480e7858f67dfeba0
pyethapp/__init__.py
pyethapp/__init__.py
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: __version__ = None else: __version__ = _dist.version if not __version__: try: # try to parse from setup.py for l in open(os.path.join(__path__[0], '..', 'setup.py')): if l.startswith("version = '"): __version__ = l.split("'")[1] break finally: if not __version__: __version__ = 'undefined' # add git revision and commit status try: rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']) is_dirty = len(subprocess.check_output(['git', 'diff', '--shortstat']).strip()) __version__ += '-' + rev[:4] + '-dirty' if is_dirty else '' except: pass # ########### endversion ##################
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: __version__ = None else: __version__ = _dist.version if not __version__: try: # try to parse from setup.py for l in open(os.path.join(__path__[0], '..', 'setup.py')): if l.startswith("version = '"): __version__ = l.split("'")[1] break except: pass finally: if not __version__: __version__ = 'undefined' # add git revision and commit status try: rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']) is_dirty = len(subprocess.check_output(['git', 'diff', '--shortstat']).strip()) __version__ += '-' + rev[:4] + '-dirty' if is_dirty else '' except: pass # ########### endversion ##################
Fix versioning from git after `setup.py install`
Fix versioning from git after `setup.py install` When following the `README`, __init__.py raised an "IOError: [Errno 2] No such file or directory:" about `setup.py`.
Python
mit
ethereum/pyethapp,RomanZacharia/pyethapp,gsalgado/pyethapp,ethereum/pyethapp,gsalgado/pyethapp,changwu-tw/pyethapp,d-das/pyethapp,RomanZacharia/pyethapp,changwu-tw/pyethapp,vaporry/pyethapp
--- +++ @@ -22,6 +22,8 @@ if l.startswith("version = '"): __version__ = l.split("'")[1] break + except: + pass finally: if not __version__: __version__ = 'undefined'
58de0a968b4cee5a670ce8e98b494d7a839b0992
functional_tests/fabfile.py
functional_tests/fabfile.py
# -*- coding: utf-8 -*- from fabric.api import env, run def _get_base_folder(host): return '/var/www/sites/{}'.format(host) def _get_manage_py(host): command = 'export $(cat /etc/www/gunicorn-{host}|xargs) && \ {path}/virtualenv/bin/python {path}/source/manage.py'.format( host=host, path=_get_base_folder(host)) return command def reset_database(): run('{manage} flush --noinput'.format(manage=_get_manage_py(env.host))) def create_user(user, password, email): run('{manage} create_user {username} {password} {email}'.format( username=user, password=password, email=email, manage=_get_manage_py(env.host))) def get_sitename(): name = run('{manage} get_sitename'.format(manage=_get_manage_py(env.host))) return name
# -*- coding: utf-8 -*- from fabric.api import env, run def _get_base_folder(host): return '/var/www/sites/{}'.format(host) def _get_manage_py(host): command = 'export $(cat /etc/www/gunicorn-{host}|xargs) && \ {path}/virtualenv/bin/python {path}/source/manage.py'.format( host=host, path=_get_base_folder(host)) return command def reset_database(): run('{manage} flush --noinput'.format(manage=_get_manage_py(env.host))) def create_user(user, password, email): run('{manage} create_user {username} {password} {email}'.format( username=user, password=password, email=email, manage=_get_manage_py(env.host))) def get_sitename(): name = run('{manage} get_sitename'.format(manage=_get_manage_py(env.host))) print name
Fix getting the sitename, we are down to 2 failing FTs
Fix getting the sitename, we are down to 2 failing FTs
Python
mit
XeryusTC/projman,XeryusTC/projman,XeryusTC/projman
--- +++ @@ -21,4 +21,4 @@ def get_sitename(): name = run('{manage} get_sitename'.format(manage=_get_manage_py(env.host))) - return name + print name
6bd6be4219f5fbf6c1d045aff1d0ef09b912fe8c
src/pdns/remotebackend/__init__.py
src/pdns/remotebackend/__init__.py
import json VERSION="0.1" class Handler: def __init__(self): self.log = [] self.result = False self.ttl = 300 self.params = {} def record_prio_ttl(self, qname, qtype, content, prio, ttl, auth=1): return {'qtype': qtype, 'qname': qname, 'content': content, 'ttl': ttl, 'auth': auth} def do_initialize(self, *args): self.params = args self.log.append("PowerDNS python remotebackend version {0} initialized".format(VERSION)) self.result = True def do_lookup(self, args): pass class Connector: def __init__(self, klass, options): self.handler = klass # initialize the handler class self.options = options def mainloop(self, reader, writer): h = self.handler() while(True): line = reader.readline() if line == "": break try: data_in = json.loads(line) method = "do_{0}".format(data_in['method'].lower()) args = {} if ('parameters' in data_in): args = data_in['parameters'] h.result = False h.log = [] if (callable(getattr(h, method, None))): getattr(h,method)(args) writer.write(json.dumps({'result':h.result,'log':h.log}) + "\n") except ValueError: writer.write(json.dumps({'result':False,'log':"Cannot parse input"}) + "\n")
Fix the callable check to not emit exception when method not found
Fix the callable check to not emit exception when method not found
Python
mit
cmouse/pdns-remotebackend-python
--- +++ @@ -0,0 +1,47 @@ +import json + +VERSION="0.1" + +class Handler: + def __init__(self): + self.log = [] + self.result = False + self.ttl = 300 + self.params = {} + + def record_prio_ttl(self, qname, qtype, content, prio, ttl, auth=1): + return {'qtype': qtype, 'qname': qname, 'content': content, + 'ttl': ttl, 'auth': auth} + + def do_initialize(self, *args): + self.params = args + self.log.append("PowerDNS python remotebackend version {0} initialized".format(VERSION)) + self.result = True + + def do_lookup(self, args): + pass + +class Connector: + def __init__(self, klass, options): + self.handler = klass # initialize the handler class + self.options = options + + def mainloop(self, reader, writer): + h = self.handler() + while(True): + line = reader.readline() + if line == "": + break + try: + data_in = json.loads(line) + method = "do_{0}".format(data_in['method'].lower()) + args = {} + if ('parameters' in data_in): + args = data_in['parameters'] + h.result = False + h.log = [] + if (callable(getattr(h, method, None))): + getattr(h,method)(args) + writer.write(json.dumps({'result':h.result,'log':h.log}) + "\n") + except ValueError: + writer.write(json.dumps({'result':False,'log':"Cannot parse input"}) + "\n")
cd996816a49642c766ffd4390a7d1586c4b6765f
annfab/tests/test_lib.py
annfab/tests/test_lib.py
# flake8: noqa import pytest annfab._annfab = pytest.importorskip("annfab._annfab") def test_import(): assert True
# flake8: noqa import pytest _annfab = pytest.importorskip("annfab._annfab") def test_import(): assert True
Use _annfab instead of annfab._annfab in an import test.
Use _annfab instead of annfab._annfab in an import test.
Python
mit
elezar/ann-fab,elezar/ann-fab,elezar/ann-fab
--- +++ @@ -1,6 +1,6 @@ # flake8: noqa import pytest -annfab._annfab = pytest.importorskip("annfab._annfab") +_annfab = pytest.importorskip("annfab._annfab") def test_import():
8ef9618850794dd499617bb28b5044336f155568
python/setup_fsurfer.py
python/setup_fsurfer.py
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License # setup for fsurfer-libs from distutils.core import setup setup(name='fsurfer-libs', version='PKG_VERSION', description='Python module to help create freesurfer workflows', author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/OSGConnect/freesurfer_workflow', packages=['fsurfer'], data_files=[('/usr/share/fsurfer/scripts', ["bash/autorecon1.sh", "bash/autorecon2.sh", "bash/autorecon2-whole.sh", "bash/autorecon3.sh", "bash/autorecon-all.sh", "bash/freesurfer-process.sh"])], license='Apache 2.0')
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License # setup for fsurfer-libs from distutils.core import setup setup(name='fsurfer-libs', version='PKG_VERSION', description='Python module to help create freesurfer workflows', author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/OSGConnect/freesurfer_workflow', packages=['fsurfer'], data_files=[('/usr/share/fsurfer/scripts', ["bash/autorecon1.sh", "bash/autorecon2.sh", "bash/autorecon2-whole.sh", "bash/autorecon3.sh", "bash/autorecon1-options.sh", "bash/autorecon2-options.sh", "bash/autorecon3-options.sh", "bash/autorecon-all.sh", "bash/freesurfer-process.sh"])], license='Apache 2.0')
Update setup to include new scripts
Update setup to include new scripts
Python
apache-2.0
OSGConnect/freesurfer_workflow,OSGConnect/freesurfer_workflow
--- +++ @@ -16,6 +16,9 @@ "bash/autorecon2.sh", "bash/autorecon2-whole.sh", "bash/autorecon3.sh", + "bash/autorecon1-options.sh", + "bash/autorecon2-options.sh", + "bash/autorecon3-options.sh", "bash/autorecon-all.sh", "bash/freesurfer-process.sh"])], license='Apache 2.0')
8f0f1331fc554c2a15722543017da3ce3a3f894b
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the Rubocop plugin class.""" from SublimeLinter.lint import RubyLinter class Rubocop(RubyLinter): """Provides an interface to rubocop.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S rubocop --format emacs' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(:?(?P<warning>[RCW])|(?P<error>[EF])): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', '.rubocop.yml')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the Rubocop plugin class.""" from SublimeLinter.lint import RubyLinter class Rubocop(RubyLinter): """Provides an interface to rubocop.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S rubocop --format emacs' version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(:?(?P<warning>[RCW])|(?P<error>[EF])): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', '.rubocop.yml')
Prepend '-S rubocop' to version args
Prepend '-S rubocop' to version args Fixes #17
Python
mit
SublimeLinter/SublimeLinter-rubocop
--- +++ @@ -19,7 +19,7 @@ syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S rubocop --format emacs' - version_args = '--version' + version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = (
ffaa2b98305c7a1368587cdb30724a7cabbe3237
glitch/apikeys_sample.py
glitch/apikeys_sample.py
# Sample untracked-keys file # If you get errors trying to 'import apikeys', do the following: # 1) Copy this file to apikeys.py (keeping it in the package directory) # 2) Replace all of the example values with real ones # 3) Generate your own cookie key, possibly using urandom as per below # You should then be able to start the server. db_connect_string = "" cookie_monster = "llsfZyohQDa4kRdCCqnoV3gpD8jaHUY0kfkKI3pZlZ4=" # in Python you can generate like this: # import base64 # import uuid # print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)) # Thanks to https://gist.github.com/didip/823887 # Alternative way to generate a similar-length nonce: # import base64, os; print(base64.b64encode(os.urandom(33))) # These settings are used only for the sending of emails. The server will # start with them at the defaults, but all email sending will fail. system_email = 'server@example.com' admin_email = 'username@example.com' # Will use default settings if SMTP_SERVER_PORT == 'localhost' SMTP_SERVER_PORT = "smtp.gmail.com:587" SMTP_USERNAME = "email@gmail.com" SMTP_PASSWORD = "yourpassword"
# Sample untracked-keys file # If you get errors trying to 'import apikeys', do the following: # 1) Copy this file to apikeys.py (keeping it in the package directory) # 2) Replace all of the example values with real ones # 3) Generate your own cookie key, possibly using urandom as per below # You should then be able to start the server. db_connect_string = "" cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa" # Generated like this: # import base64, os; print(base64.b64encode(os.urandom(33))) # These settings are used only for the sending of emails. The server will # start with them at the defaults, but all email sending will fail. system_email = 'server@example.com' admin_email = 'username@example.com' # Will use default settings if SMTP_SERVER_PORT == 'localhost' SMTP_SERVER_PORT = "smtp.gmail.com:587" SMTP_USERNAME = "email@gmail.com" SMTP_PASSWORD = "yourpassword"
Drop the UUID; just use urandom
Drop the UUID; just use urandom
Python
artistic-2.0
Rosuav/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension
--- +++ @@ -6,13 +6,8 @@ # You should then be able to start the server. db_connect_string = "" -cookie_monster = "llsfZyohQDa4kRdCCqnoV3gpD8jaHUY0kfkKI3pZlZ4=" -# in Python you can generate like this: -# import base64 -# import uuid -# print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)) -# Thanks to https://gist.github.com/didip/823887 -# Alternative way to generate a similar-length nonce: +cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa" +# Generated like this: # import base64, os; print(base64.b64encode(os.urandom(33))) # These settings are used only for the sending of emails. The server will
e2735cba808ac4eb33e555fbb3d5d5f774ace032
swf/actors/helpers.py
swf/actors/helpers.py
#! -*- coding:utf-8 -*- import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer """ def __init__(self, heartbeating_closure, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: self.heartbeating_closure() time.sleep(self.heartbeat_interval)
#! -*- coding:utf-8 -*- import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer :param closure_args: feel free to provide arguments to your heartbeating closure """ def __init__(self, heartbeating_closure, closure_args, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure self.closure_args = closure_args self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: self.heartbeating_closure(self.closure_args) time.sleep(self.heartbeat_interval)
Update Heart actors helper class to handle args
Update Heart actors helper class to handle args
Python
mit
botify-labs/python-simple-workflow,botify-labs/python-simple-workflow
--- +++ @@ -16,13 +16,16 @@ :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer + + :param closure_args: feel free to provide arguments to your heartbeating closure """ - def __init__(self, heartbeating_closure, + def __init__(self, heartbeating_closure, closure_args, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure + self.closure_args = closure_args self.heartbeat_interval = heartbeat_interval self.keep_beating = True @@ -35,5 +38,5 @@ def run(self): while self.keep_beating is True: - self.heartbeating_closure() + self.heartbeating_closure(self.closure_args) time.sleep(self.heartbeat_interval)
e94503e25bff0ba986c28ce3f16636b3bb9f2c3d
green_django/__init__.py
green_django/__init__.py
import sys from utils import module_exists from gevent import monkey def make_django_green(): monkey.patch_all() if module_exists('psycogreen'): from psycogreen.gevent.psyco_gevent import make_psycopg_green make_psycopg_green() if module_exists('pymysql'): import pymysql pymysql.install_as_MySQLdb() if module_exists('zmq'): from gevent_zeromq import zmq sys.modules["zmq"] = zmq
import sys from utils import module_exists from gevent import monkey def make_django_green(): monkey.patch_all() if module_exists('psycogreen'): from psycogreen.gevent.psyco_gevent import make_psycopg_green make_psycopg_green() if module_exists('pymysql'): import pymysql pymysql.install_as_MySQLdb() if module_exists('gevent_zeromq'): from gevent_zeromq import zmq sys.modules["zmq"] = zmq
Check for greened package - consistency
Check for greened package - consistency
Python
mit
philipn/green-monkey
--- +++ @@ -16,6 +16,6 @@ import pymysql pymysql.install_as_MySQLdb() - if module_exists('zmq'): + if module_exists('gevent_zeromq'): from gevent_zeromq import zmq sys.modules["zmq"] = zmq
d95d4da272915ad6a581260679df756bf24a6f4c
app/utils/db/__init__.py
app/utils/db/__init__.py
import logging from app import db logger = logging.getLogger(__name__) def save_data(data): try: db.session.add(data) db.session.commit() except Exception as err: logger.error(err)
import logging from app import db logger = logging.getLogger(__name__) def save_record(record): try: db.session.add(record) db.session.commit() except Exception as err: logger.error(err) def delete_record(record): try: db.session.delete(record) db.session.commit() except Exception as err: logger.error(err)
Rename save method for database to a more descriptive name
[FIX] Rename save method for database to a more descriptive name
Python
mit
brayoh/bucket-list-api
--- +++ @@ -4,9 +4,16 @@ logger = logging.getLogger(__name__) -def save_data(data): +def save_record(record): try: - db.session.add(data) + db.session.add(record) db.session.commit() except Exception as err: logger.error(err) + +def delete_record(record): + try: + db.session.delete(record) + db.session.commit() + except Exception as err: + logger.error(err)
331b3987ba09db5d8f774509bedd30c3c6522795
ooni/tests/test_utils.py
ooni/tests/test_utils.py
import os import unittest from ooni.utils import pushFilenameStack class TestUtils(unittest.TestCase): def test_pushFilenameStack(self): basefilename = os.path.join(os.getcwd(), 'dummyfile') f = open(basefilename, "w+") f.write("0\n") f.close() for i in xrange(1, 5): f = open(basefilename+".%s" % i, "w+") f.write("%s\n" % i) f.close() pushFilenameStack(basefilename) for i in xrange(1, 5): f = open(basefilename+".%s" % i) c = f.readlines()[0].strip() self.assertEqual(str(i-1), str(c)) f.close()
import os from twisted.trial import unittest from ooni.utils import pushFilenameStack class TestUtils(unittest.TestCase): def test_pushFilenameStack(self): basefilename = os.path.join(os.getcwd(), 'dummyfile') f = open(basefilename, "w+") f.write("0\n") f.close() for i in xrange(1, 5): f = open(basefilename+".%s" % i, "w+") f.write("%s\n" % i) f.close() pushFilenameStack(basefilename) for i in xrange(1, 5): f = open(basefilename+".%s" % i) c = f.readlines()[0].strip() self.assertEqual(str(i-1), str(c)) f.close()
Use trial unittest instead of python unittest
Use trial unittest instead of python unittest
Python
bsd-2-clause
juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe
--- +++ @@ -1,5 +1,6 @@ import os -import unittest +from twisted.trial import unittest + from ooni.utils import pushFilenameStack class TestUtils(unittest.TestCase): def test_pushFilenameStack(self):
d741b41e814930130a30e99b0fece893786f7190
src/pybel/struct/mutation/__init__.py
src/pybel/struct/mutation/__init__.py
# -*- coding: utf-8 -*- """This module contains functions that mutate or make transformations on a network.""" from . import deletion, expansion, induction, inference, metadata, transfer from .deletion import * from .expansion import * from .induction import * from .inference import * from .metadata import * from .transfer import * __all__ = ( deletion.__all__ + expansion.__all__ + induction.__all__ + inference.__all__ + metadata.__all__ + transfer.__all__ )
# -*- coding: utf-8 -*- """This module contains functions that mutate or make transformations on a network.""" from . import collapse, deletion, expansion, induction, inference, metadata, transfer from .collapse import * from .deletion import * from .expansion import * from .induction import * from .inference import * from .metadata import * from .transfer import * __all__ = ( collapse.__all__ + deletion.__all__ + expansion.__all__ + induction.__all__ + inference.__all__ + metadata.__all__ + transfer.__all__ )
Add collapse to star import
Add collapse to star import
Python
mit
pybel/pybel,pybel/pybel,pybel/pybel
--- +++ @@ -2,7 +2,8 @@ """This module contains functions that mutate or make transformations on a network.""" -from . import deletion, expansion, induction, inference, metadata, transfer +from . import collapse, deletion, expansion, induction, inference, metadata, transfer +from .collapse import * from .deletion import * from .expansion import * from .induction import * @@ -11,6 +12,7 @@ from .transfer import * __all__ = ( + collapse.__all__ + deletion.__all__ + expansion.__all__ + induction.__all__ +
08dede97d1ad9694df18a8262e777769e88f9578
calc.py
calc.py
import sys def add_all(nums): return sum(nums) def multiply_all(nums): return reduce(lambda a, b: a * b, nums) if __name__== '__main__': command = sys.argv[1] nums = map(float, sys.argv[2:]) if command == 'add': print(add_all(nums)) elif command == 'multiply': print(multiply_all(nums))
import sys def add_all(nums): return sum(nums) def multiply_all(nums): return reduce(lambda a, b: a * b, nums) if __name__== '__main__': command = sys.argv[1] nums = map(float, sys.argv[2:]) if command == 'add': print(add_all(nums)) elif command == 'multiply': print(multiply_all(nums))
Fix bug in 'multiply' support
Fix bug in 'multiply' support
Python
bsd-3-clause
tanecious/calc
--- +++ @@ -1,3 +1,4 @@ + import sys def add_all(nums):
5baa4fb91d9b6a80d748b47192b91e2a68b567d0
verleihsystem/categories/views.py
verleihsystem/categories/views.py
from django.shortcuts import render_to_response from categories.models import Category def index(request): category_list = Category.tree.all() return render_to_response("home.html", {'nodes': category_list})
from django.shortcuts import render_to_response from categories.models import Category def index(request): category_list = Category.tree.all() return render_to_response("home.html", {'nodes': category_list, 'request': request})
Add request to return value.
Add request to return value.
Python
isc
westphahl/verleihsystem,westphahl/verleihsystem,westphahl/verleihsystem
--- +++ @@ -4,4 +4,4 @@ def index(request): category_list = Category.tree.all() return render_to_response("home.html", - {'nodes': category_list}) + {'nodes': category_list, 'request': request})
50cf6e64955d1e82ba702b8817b830c23534da11
simple_faq/models.py
simple_faq/models.py
from django.db import models from tinymce import models as tinymce_models photos_path = "/simple-faq/" class Topic(models.Model): text = models.CharField(max_length=200) number = models.IntegerField() class Meta: ordering = ['number'] def __unicode__(self): return u'(%s) %s' % (self.number, self.text, ) class Question(models.Model): text = models.CharField(max_length=200) answer_text = tinymce_models.HTMLField() topic = models.ForeignKey(Topic, related_name="questions") header_picture = models.ImageField(upload_to=photos_path, blank=True) number = models.IntegerField() related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True) class Meta: ordering = ['number'] def __unicode__(self): return u'(%s) %s' % (self.number, self.text, )
from django.db import models from tinymce import models as tinymce_models photos_path = "simple-faq/" class Topic(models.Model): text = models.CharField(max_length=200) number = models.IntegerField() class Meta: ordering = ['number'] def __unicode__(self): return u'(%s) %s' % (self.number, self.text, ) class Question(models.Model): text = models.CharField(max_length=200) answer_text = tinymce_models.HTMLField() topic = models.ForeignKey(Topic, related_name="questions") header_picture = models.ImageField(upload_to=photos_path, blank=True) number = models.IntegerField() related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True) class Meta: ordering = ['number'] def __unicode__(self): return u'(%s) %s' % (self.number, self.text, )
Fix path where the images are saved.
Fix path where the images are saved.
Python
mit
devartis/django-simple-faq,devartis/django-simple-faq
--- +++ @@ -1,7 +1,7 @@ from django.db import models from tinymce import models as tinymce_models -photos_path = "/simple-faq/" +photos_path = "simple-faq/" class Topic(models.Model):
52f510b64e4ded6e159119b2fa544de577b7d949
classyfd/directory/directory.py
classyfd/directory/directory.py
"""Contains a Directory class to represent real directories""" from ..base import _BaseFileAndDirectoryInterface class Directory(_BaseFileAndDirectoryInterface): """A class that groups together the (meta)data and behavior of directories""" def __init__(self, path): """ Construct the object Parameters: path -- (str) where the directory is (or will be) located at. An exception is raised if the path refers to a file, and also if an empty string is given. """ return # Special Methods def __repr__(self): pass def __str__(self): pass # Properties @property def name(self): pass @property def path(self): pass @property def exists(self): pass @property def created_on(self): pass @property def size(self): pass @property def parent(self): pass @property def owner(self): pass @property def group(self): pass # Regular Methods def get_parent(self): pass def create(self): pass def get_permissions(self): pass def change_permissions(self): pass def chmod(self): pass def change_owner(self): pass def change_group(self): pass def copy(self): pass def move(self): pass def rename(self): pass def remove(self): pass
"""Contains a Directory class to represent real directories""" from ..base import _BaseFileAndDirectoryInterface from ..exceptions import InvalidDirectoryValueError class Directory(_BaseFileAndDirectoryInterface): """A class that groups together the (meta)data and behavior of directories""" def __init__(self, path): """ Construct the object Parameters: path -- (str) where the directory is (or will be) located at. An exception is raised if the path refers to a file, and also if an empty string is given. """ if not path: # No point in continuing since the methods of this class assume # that a path will be given upon instantiation. raise InvalidDirectoryValueError("No directory path was given") return # Special Methods def __repr__(self): pass def __str__(self): pass # Properties @property def name(self): pass @property def path(self): pass @property def exists(self): pass @property def created_on(self): pass @property def size(self): pass @property def parent(self): pass @property def owner(self): pass @property def group(self): pass # Regular Methods def get_parent(self): pass def create(self): pass def get_permissions(self): pass def change_permissions(self): pass def chmod(self): pass def change_owner(self): pass def change_group(self): pass def copy(self): pass def move(self): pass def rename(self): pass def remove(self): pass
Add custom exception logic to the Directory class
Add custom exception logic to the Directory class If an empty string was passed to the Directory class, then an exception needs to be raised as all of its methods assume a value for the path.
Python
mit
SizzlingVortex/classyfd
--- +++ @@ -1,6 +1,7 @@ """Contains a Directory class to represent real directories""" from ..base import _BaseFileAndDirectoryInterface +from ..exceptions import InvalidDirectoryValueError class Directory(_BaseFileAndDirectoryInterface): @@ -15,7 +16,11 @@ exception is raised if the path refers to a file, and also if an empty string is given. - """ + """ + if not path: + # No point in continuing since the methods of this class assume + # that a path will be given upon instantiation. + raise InvalidDirectoryValueError("No directory path was given") return
fe50ea0dd1ceb51fdff455484cb5d2d32c94b076
spyder_unittest/__init__.py
spyder_unittest/__init__.py
from .unittest import UnitTestPlugin as PLUGIN_CLASS
# -*- coding:utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Developers # # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) # ----------------------------------------------------------------------------- """Spyder unitest plugin.""" # Local imports from .unittest import UnitTestPlugin as PLUGIN_CLASS VERSION_INFO = (0, 1, 0, 'dev0') __version__ = '.'.join(map(str, VERSION_INFO))
Add version information and header
Add version information and header
Python
mit
jitseniesen/spyder-unittest
--- +++ @@ -1 +1,14 @@ +# -*- coding:utf-8 -*- +# ----------------------------------------------------------------------------- +# Copyright (c) Spyder Project Developers +# +# Licensed under the terms of the MIT License +# (see spyder/__init__.py for details) +# ----------------------------------------------------------------------------- +"""Spyder unitest plugin.""" + +# Local imports from .unittest import UnitTestPlugin as PLUGIN_CLASS + +VERSION_INFO = (0, 1, 0, 'dev0') +__version__ = '.'.join(map(str, VERSION_INFO))
1cc10287a7a9666d7478adc1271250ba49663e24
drf_to_s3/tests/test_parsers.py
drf_to_s3/tests/test_parsers.py
import unittest, urllib from rest_framework.compat import BytesIO class TestParser(unittest.TestCase): def setUp(self): from drf_to_s3.parsers import NestedFormParser self.parser = NestedFormParser() def test_form_parser_unflattens(self): flattened = { 'user[name]': 'Foobar', 'user[email]': 'foo@bar.com', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {}) expected = { 'user': { 'name': 'Foobar', 'email': 'foo@bar.com', } } self.assertEquals(result, expected)
# coding=utf-8 import unittest, urllib from rest_framework.compat import BytesIO class TestParser(unittest.TestCase): def setUp(self): from drf_to_s3.parsers import NestedFormParser self.parser = NestedFormParser() def test_form_parser_unflattens(self): flattened = { 'user[name]': 'Foobar', 'user[email]': 'foo@bar.com', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {}) expected = { 'user': { 'name': 'Foobar', 'email': 'foo@bar.com', } } self.assertEquals(result, expected) @unittest.expectedFailure def test_form_parser_handle_unicode_right(self): unicode_str = u'测试' flattened = { 'user[name]': unicode_str.encode('utf-8'), 'user[email]': 'foo@bar.com', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {'encoding':'utf-8'}) expected = { 'user':{ 'name': unicode_str, 'email': u'foo@bar.com', } } self.assertEquals(result, expected)
Add a failing unit test of unicode parsing
Add a failing unit test of unicode parsing
Python
mit
pombredanne/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,bodylabs/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3
--- +++ @@ -1,3 +1,4 @@ +# coding=utf-8 import unittest, urllib from rest_framework.compat import BytesIO @@ -24,3 +25,27 @@ } } self.assertEquals(result, expected) + + @unittest.expectedFailure + def test_form_parser_handle_unicode_right(self): + + unicode_str = u'测试' + + flattened = { + 'user[name]': unicode_str.encode('utf-8'), + 'user[email]': 'foo@bar.com', + } + stream = BytesIO(urllib.urlencode(flattened)) + + result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {'encoding':'utf-8'}) + + expected = { + 'user':{ + 'name': unicode_str, + 'email': u'foo@bar.com', + } + } + + self.assertEquals(result, expected) + +
6856c469da365c7463017e4c064e1ed25c12dfdc
foyer/tests/test_performance.py
foyer/tests/test_performance.py
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
Allow for some missing silica bond parameters
Allow for some missing silica bond parameters
Python
mit
mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer
--- +++ @@ -17,7 +17,7 @@ def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) - forcefield.apply(surface) + forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45)
e1b177d58be0c41c6e1fa7abf8cef0cb06b272d0
blitz/__init__.py
blitz/__init__.py
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Andre Anjos <andre.anjos@idiap.ch> # Fri 20 Sep 14:45:01 2013 """Blitz++ Array bindings for Python""" from ._library import array, as_blitz, __version__, __api_version__ def get_include(): """Returns the directory containing the C/C++ API include directives""" return __import__('pkg_resources').resource_filename(__name__, 'include') def get_numpy_api(): """Returns the name of the numpy API used for compilation""" from ._array import __numpy_api_name__ return __numpy_api_name__ __all__ = ['array', 'as_blitz']
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Andre Anjos <andre.anjos@idiap.ch> # Fri 20 Sep 14:45:01 2013 """Blitz++ Array bindings for Python""" from ._library import array, as_blitz, __version__, __api_version__ def get_include(): """Returns the directory containing the C/C++ API include directives""" return __import__('pkg_resources').resource_filename(__name__, 'include') def get_numpy_api(): """Returns the name of the numpy API used for compilation""" from ._library import __numpy_api_name__ return __numpy_api_name__ __all__ = ['array', 'as_blitz']
Fix numpy API name retrieval
Fix numpy API name retrieval
Python
bsd-3-clause
tiagofrepereira2012/bob.blitz,tiagofrepereira2012/bob.blitz,tiagofrepereira2012/bob.blitz
--- +++ @@ -15,7 +15,7 @@ def get_numpy_api(): """Returns the name of the numpy API used for compilation""" - from ._array import __numpy_api_name__ + from ._library import __numpy_api_name__ return __numpy_api_name__ __all__ = ['array', 'as_blitz']
85dedf4c02d28f9a4928d46757cbaa1baf8994ed
tingbot/quit.py
tingbot/quit.py
import sys, signal import pygame def fixup_sigterm_behaviour(): ''' SDL registers its own signal handler for SIGTERM, which pushes a SDL_QUIT event to the event loop, instead of killing the process right away. This is a problem for us, because when using the fbcon drivers, the process activates and locks a virtual terminal which survives after the process dies. We need to ensure that the process cleans up this virtual terminal, otherwise the Tingbot needs a reboot. We do this by calling the cleanup and exiting straight away on SIGTERM. ''' # this installs the 'bad' SIGTERM handler pygame.display.init() def quit_handler(sig, frame): pygame.quit() sys.exit(128 + sig) # this overwrites it with our SIGTERM handler signal.signal(signal.SIGTERM, quit_handler)
import sys, signal import pygame def fixup_sigterm_behaviour(): ''' SDL registers its own signal handler for SIGTERM, which pushes a SDL_QUIT event to the event loop, instead of killing the process right away. This is a problem for us, because when using the fbcon drivers, the process activates and locks a virtual terminal which survives after the process dies. We need to ensure that the process cleans up this virtual terminal, otherwise the Tingbot needs a reboot. We do this by calling the cleanup and exiting straight away on SIGTERM. ''' def quit_handler(sig, frame): pygame.quit() sys.exit(128 + sig) signal.signal(signal.SIGTERM, quit_handler)
Remove pygame.display.init() call on import, not needed
Remove pygame.display.init() call on import, not needed
Python
bsd-2-clause
furbrain/tingbot-python
--- +++ @@ -12,12 +12,8 @@ We do this by calling the cleanup and exiting straight away on SIGTERM. ''' - # this installs the 'bad' SIGTERM handler - pygame.display.init() - def quit_handler(sig, frame): pygame.quit() sys.exit(128 + sig) - # this overwrites it with our SIGTERM handler signal.signal(signal.SIGTERM, quit_handler)
4f72617702881bde979648a8ddf240b0d721cf4e
girder/app/app/__init__.py
girder/app/app/__init__.py
from .configuration import Configuration from girder.utility import setting_utilities from .constants import Features from girder.plugin import GirderPlugin @setting_utilities.validator({ Features.NOTEBOOKS }) class AppPlugin(GirderPlugin): DISPLAY_NAME = 'OpenChemistry App' def validateSettings(self, event): pass def load(self, info): info['apiRoot'].configuration = Configuration()
from .configuration import Configuration from girder.utility import setting_utilities from .constants import Features from girder.plugin import GirderPlugin @setting_utilities.validator({ Features.NOTEBOOKS }) def validateSettings(event): pass class AppPlugin(GirderPlugin): DISPLAY_NAME = 'OpenChemistry App' def load(self, info): info['apiRoot'].configuration = Configuration()
Put validateSettings() after girder decorator
Put validateSettings() after girder decorator This was mistakenly put inside the class body. It needs to be after the girder decorator instead. Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
Python
bsd-3-clause
OpenChemistry/mongochemserver
--- +++ @@ -7,12 +7,11 @@ @setting_utilities.validator({ Features.NOTEBOOKS }) +def validateSettings(event): + pass class AppPlugin(GirderPlugin): DISPLAY_NAME = 'OpenChemistry App' - def validateSettings(self, event): - pass - def load(self, info): info['apiRoot'].configuration = Configuration()
04a3f7e0e079f0db23f723c7a08e32841fc7a9fd
hierarchical_auth/admin.py
hierarchical_auth/admin.py
from django.contrib import admin from django.conf import settings from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: User = settings.AUTH_USER_MODEL except: from django.contrib.auth.models import User try: UserAdmin = settings.AUTH_USER_ADMIN_MODEL except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') User = get_model(app_label, model_name) except: from django.contrib.auth.models import User try: app_label, model_name = settings.AUTH_USER_ADMIN_MODEL.split('.') UserAdmin = get_model(app_label, model_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
Work with custom user models in django >= 1.5
Work with custom user models in django >= 1.5 settings only provide module strs, not real implementations
Python
bsd-3-clause
digitalemagine/django-hierarchical-auth,zhangguiyu/django-hierarchical-auth
--- +++ @@ -1,17 +1,20 @@ from django.contrib import admin from django.conf import settings +from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm -try: - User = settings.AUTH_USER_MODEL +try: + app_label, model_name = settings.AUTH_USER_MODEL.split('.') + User = get_model(app_label, model_name) except: from django.contrib.auth.models import User try: - UserAdmin = settings.AUTH_USER_ADMIN_MODEL + app_label, model_name = settings.AUTH_USER_ADMIN_MODEL.split('.') + UserAdmin = get_model(app_label, model_name) except: from django.contrib.auth.admin import UserAdmin
aec62c210bc1746c6fefa12030ada548730faf62
plugins/titlegiver/titlegiver.py
plugins/titlegiver/titlegiver.py
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()) @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
Fix for titles containing cr
Fix for titles containing cr
Python
mit
Tigge/platinumshrimp
--- +++ @@ -6,7 +6,7 @@ from twisted.python import log -title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) +title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): @@ -15,7 +15,7 @@ @staticmethod def find_title_url(url): - return Titlegiver.find_title(urllib2.urlopen(url).read()) + return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text):
70a2196d7748a9b01a0c23e2b2bda6a074ae4c8a
python/setup_fsurfer_backend.py
python/setup_fsurfer_backend.py
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License # setup for fsurf on OSG Connect login from distutils.core import setup import fsurfer setup(name='fsurfer-backend', version=fsurfer.__version__, description='Scripts to handle background freesurfer processing', author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/OSGConnect/freesurfer_workflow', scripts=['process_mri.py', 'update_fsurf_job.py'], license='Apache 2.0')
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License # setup for fsurf on OSG Connect login from distutils.core import setup import fsurfer setup(name='fsurfer-backend', version=fsurfer.__version__, description='Scripts to handle background freesurfer processing', author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/OSGConnect/freesurfer_workflow', scripts=['process_mri.py', 'update_fsurf_job.py', 'purge_inputs.py', 'purge_results.py', 'warn_purge.py'], license='Apache 2.0')
Add purge and warn scripts
Add purge and warn scripts
Python
apache-2.0
OSGConnect/freesurfer_workflow,OSGConnect/freesurfer_workflow
--- +++ @@ -12,6 +12,10 @@ author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/OSGConnect/freesurfer_workflow', - scripts=['process_mri.py', 'update_fsurf_job.py'], + scripts=['process_mri.py', + 'update_fsurf_job.py', + 'purge_inputs.py', + 'purge_results.py', + 'warn_purge.py'], license='Apache 2.0')
16a67da087349e5f661030702c488bd644dac3a8
version.py
version.py
major = 0 minor=0 patch=11 branch="master" timestamp=1376505745.87
major = 0 minor=0 patch=12 branch="master" timestamp=1376505816.36
Tag commit for v0.0.12-master generated by gitmake.py
Tag commit for v0.0.12-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
--- +++ @@ -1,5 +1,5 @@ major = 0 minor=0 -patch=11 +patch=12 branch="master" -timestamp=1376505745.87 +timestamp=1376505816.36
2cd897195c545d36dbde962588e31505bb2bc556
test/cli/test_cmd_piperd.py
test/cli/test_cmd_piperd.py
from piper.cli import cmd_piperd from piper.api import api import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piperd.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piperd.entry(self.mock) clibase.assert_called_once_with( 'piperd', (api.ApiCLI,), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piperd.CLIBase') def test_return_value(self, clibase): ret = cmd_piperd.entry() assert ret is clibase.return_value.entry.return_value
from piper.cli import cmd_piperd from piper.api import api import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piperd.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piperd.entry(self.mock) clibase.assert_called_once_with( 'piperd', (api.ApiCLI,), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piperd.CLIBase') def test_return_value(self, clibase): ret = cmd_piperd.entry() assert ret is clibase.return_value.entry.return_value class TestEntryIntegration(object): @mock.patch('piper.api.api.Flask') def test_api_start(self, flask): cmd_piperd.entry(['api', 'start']) flask.return_value.run.assert_called_once_with(debug=True)
Add integration test for starting the API
Add integration test for starting the API
Python
mit
thiderman/piper
--- +++ @@ -20,3 +20,10 @@ def test_return_value(self, clibase): ret = cmd_piperd.entry() assert ret is clibase.return_value.entry.return_value + + +class TestEntryIntegration(object): + @mock.patch('piper.api.api.Flask') + def test_api_start(self, flask): + cmd_piperd.entry(['api', 'start']) + flask.return_value.run.assert_called_once_with(debug=True)
67149700771c05e735703ed9a12ac2d16e10e886
src/deploy.py
src/deploy.py
"""module concerns itself with tasks involving branch deployments of projects.""" from fabric.api import task from decorators import requires_aws_stack, debugtask from buildercore import bootstrap, cloudformation from buildercore.concurrency import concurrency_for import buildvars import logging LOG = logging.getLogger(__name__) @task @requires_aws_stack def switch_revision_update_instance(stackname, revision=None, concurrency='serial'): buildvars.switch_revision(stackname, revision) bootstrap.update_stack(stackname, service_list=['ec2'], concurrency=concurrency_for(stackname, concurrency)) @debugtask @requires_aws_stack def load_balancer_status(stackname): load_balancer_name = cloudformation.read_output(stackname, 'ElasticLoadBalancer') print(load_balancer_name)
"""module concerns itself with tasks involving branch deployments of projects.""" from fabric.api import task from decorators import requires_aws_stack, debugtask from buildercore import bootstrap, cloudformation, context_handler from buildercore.core import boto_client from buildercore.concurrency import concurrency_for import buildvars import logging LOG = logging.getLogger(__name__) @task @requires_aws_stack def switch_revision_update_instance(stackname, revision=None, concurrency='serial'): buildvars.switch_revision(stackname, revision) bootstrap.update_stack(stackname, service_list=['ec2'], concurrency=concurrency_for(stackname, concurrency)) @debugtask @requires_aws_stack def load_balancer_status(stackname): context = context_handler.load_context(stackname) elb_name = cloudformation.read_output(stackname, 'ElasticLoadBalancer') conn = boto_client('elb', context['aws']['region']) health = conn.describe_instance_health( LoadBalancerName=elb_name, )['InstanceStates'] LOG.info("Load balancer name: %s", elb_name) LOG.info("Health: %s", health)
Complete output of load_balancer_status @debugtask
Complete output of load_balancer_status @debugtask
Python
mit
elifesciences/builder,elifesciences/builder
--- +++ @@ -2,7 +2,8 @@ from fabric.api import task from decorators import requires_aws_stack, debugtask -from buildercore import bootstrap, cloudformation +from buildercore import bootstrap, cloudformation, context_handler +from buildercore.core import boto_client from buildercore.concurrency import concurrency_for import buildvars @@ -19,5 +20,11 @@ @debugtask @requires_aws_stack def load_balancer_status(stackname): - load_balancer_name = cloudformation.read_output(stackname, 'ElasticLoadBalancer') - print(load_balancer_name) + context = context_handler.load_context(stackname) + elb_name = cloudformation.read_output(stackname, 'ElasticLoadBalancer') + conn = boto_client('elb', context['aws']['region']) + health = conn.describe_instance_health( + LoadBalancerName=elb_name, + )['InstanceStates'] + LOG.info("Load balancer name: %s", elb_name) + LOG.info("Health: %s", health)
9c5eb9aa4d8de3d3060c7c6551b1e726d7577f57
setup.py
setup.py
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() setup( name = "django-disposable-email-checker", version = "0.1.1", packages = find_packages(), package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], }, author = "Aaron Bassett", author_email = "me@aaronbassett.com", description = "Python class for use with Django to detect Disposable Emails", long_description=readme, license = "MIT License", keywords = "django email disposable validation", url = "https://github.com/aaronbassett/DisposableEmailChecker", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2 :: Only', 'Framework :: Django' ] )
from setuptools import setup, find_packages setup( name = "django-disposable-email-checker", version = "0.1.1", packages = find_packages(), author = "Aaron Bassett", author_email = "me@aaronbassett.com", description = "Python class for use with Django to detect Disposable Emails", license = "MIT License", keywords = "django email disposable validation", url = "https://github.com/aaronbassett/DisposableEmailChecker", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2 :: Only', 'Framework :: Django' ] )
Remove long description as causing pip error
Remove long description as causing pip error
Python
bsd-3-clause
aaronbassett/DisposableEmailChecker
--- +++ @@ -1,20 +1,13 @@ from setuptools import setup, find_packages -with open('README.rst') as f: - readme = f.read() setup( name = "django-disposable-email-checker", version = "0.1.1", packages = find_packages(), - package_data = { - # If any package contains *.txt or *.rst files, include them: - '': ['*.txt', '*.rst'], - }, author = "Aaron Bassett", author_email = "me@aaronbassett.com", description = "Python class for use with Django to detect Disposable Emails", - long_description=readme, license = "MIT License", keywords = "django email disposable validation", url = "https://github.com/aaronbassett/DisposableEmailChecker",
87d868283d1972330da593fa605bd05e574cf2fd
sslyze/cli/output_generator.py
sslyze/cli/output_generator.py
from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): pass @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None pass @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None pass @abstractmethod def scans_started(self): # type: (None) -> None pass @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None pass @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None pass
from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): """The CLI was just started and successfully parsed the command line. """ @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None """The CLI found a server that it could not connect to; no scans will be performed against this server. """ @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None """The CLI found a server that it was able to connect to; scans will be run against this server. """ @abstractmethod def scans_started(self): # type: (None) -> None """The CLI has finished testing connectivity with the supplied servers and will now start the scans. """ @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None """The CLI has finished scanning one single server. """ @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None """The CLI has finished scanning all the supplied servers and will now exit. """
Document how output generators work
Document how output generators work
Python
agpl-3.0
nabla-c0d3/sslyze
--- +++ @@ -23,29 +23,35 @@ @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): - pass + """The CLI was just started and successfully parsed the command line. + """ @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None - pass + """The CLI found a server that it could not connect to; no scans will be performed against this server. + """ @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None - pass + """The CLI found a server that it was able to connect to; scans will be run against this server. + """ @abstractmethod def scans_started(self): # type: (None) -> None - pass + """The CLI has finished testing connectivity with the supplied servers and will now start the scans. + """ @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None - pass + """The CLI has finished scanning one single server. + """ @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None - pass + """The CLI has finished scanning all the supplied servers and will now exit. + """
29178a5a1e258e0f7c7392233858f36bf67241d0
tmc/exercise_tests/check.py
tmc/exercise_tests/check.py
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text message = message.replace(r"&amp;", "&"))) ret.append(TestResult(success=success, name=name, message=message)) return ret
Fix bug: trying to call .replace on NoneType
Fix bug: trying to call .replace on NoneType
Python
mit
JuhaniImberg/tmc.py,JuhaniImberg/tmc.py
--- +++ @@ -37,8 +37,7 @@ if test.get("result") == "failure": success = False message = test.find(ns + "message").text - ret.append(TestResult(success=success, - name=name, - message=message.replace(r"&amp;", "&"))) + message = message.replace(r"&amp;", "&"))) + ret.append(TestResult(success=success, name=name, message=message)) return ret
339f5c6d7cc5b3a70fa71fd423c0a4226acc77e7
valor/schema.py
valor/schema.py
import json class Schema(dict): """ Lightweight encapsulation of a JSON Schema. """ @classmethod def from_file(cls, path_or_stream): """ Create a schema from a file name or stream. """ if hasattr(path_or_stream, 'read'): return cls(json.load(path_or_stream)) else: with open(path_or_stream) as fp: return cls(json.load(fp)) def resolve_ref(self, ref): return Reference(ref).resolve(self) class Reference(object): def __init__(self, ref): if not ref.startswith('#'): raise ValueError("non-fragment references are not supported (got: %s)" % ref) self.ref = ref def resolve(self, schema): # Very overly simplisitic - doesn't handle array indexes, etc. However, # works with Heroku's schema, so good enough for a prototype. node = schema for bit in self.ref.split('/')[1:]: node = node[bit] return node
import json import jsonpointer class Schema(dict): """ Lightweight encapsulation of a JSON Schema. """ @classmethod def from_file(cls, path_or_stream): """ Create a schema from a file name or stream. """ if hasattr(path_or_stream, 'read'): return cls(json.load(path_or_stream)) else: with open(path_or_stream) as fp: return cls(json.load(fp)) def resolve_ref(self, ref): if not ref.startswith('#'): raise ValueError("non-fragment references are not supported (got: %s)" % ref) return jsonpointer.resolve_pointer(self, ref.lstrip('#'))
Use jsonpointer instead of my own terrible Reference class.
Use jsonpointer instead of my own terrible Reference class.
Python
bsd-3-clause
jacobian/valor
--- +++ @@ -1,4 +1,5 @@ import json +import jsonpointer class Schema(dict): """ @@ -17,18 +18,6 @@ return cls(json.load(fp)) def resolve_ref(self, ref): - return Reference(ref).resolve(self) - -class Reference(object): - def __init__(self, ref): if not ref.startswith('#'): raise ValueError("non-fragment references are not supported (got: %s)" % ref) - self.ref = ref - - def resolve(self, schema): - # Very overly simplisitic - doesn't handle array indexes, etc. However, - # works with Heroku's schema, so good enough for a prototype. - node = schema - for bit in self.ref.split('/')[1:]: - node = node[bit] - return node + return jsonpointer.resolve_pointer(self, ref.lstrip('#'))
bf6ab9532db2e2bc67cb72415674a0fdefe3bc46
corehq/preindex/tasks.py
corehq/preindex/tasks.py
from celery.schedules import crontab from celery.task.base import periodic_task from corehq.preindex.accessors import index_design_doc, get_preindex_designs from corehq.util.decorators import serial_task from django.conf import settings @periodic_task(run_every=crontab(minute='*/5'), queue=settings.CELERY_PERIODIC_QUEUE) def run_continuous_indexing_task(): preindex_couch_views.delay() @serial_task('couch-continuous-indexing', timeout=60 * 60, queue='background_queue', max_retries=0) def preindex_couch_views(): for design in get_preindex_designs(): index_design_doc(design)
from celery.schedules import crontab from celery.task.base import periodic_task from corehq.preindex.accessors import index_design_doc, get_preindex_designs from corehq.util.decorators import serial_task from django.conf import settings @periodic_task(run_every=crontab(minute='*/5'), queue=settings.CELERY_PERIODIC_QUEUE) def run_continuous_indexing_task(): preindex_couch_views.delay() @serial_task('couch-continuous-indexing', timeout=60 * 60, queue=settings.CELERY_PERIODIC_QUEUE, max_retries=0) def preindex_couch_views(): for design in get_preindex_designs(): index_design_doc(design)
Use periodic queue to increase priority
Use periodic queue to increase priority
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -11,7 +11,7 @@ preindex_couch_views.delay() -@serial_task('couch-continuous-indexing', timeout=60 * 60, queue='background_queue', max_retries=0) +@serial_task('couch-continuous-indexing', timeout=60 * 60, queue=settings.CELERY_PERIODIC_QUEUE, max_retries=0) def preindex_couch_views(): for design in get_preindex_designs(): index_design_doc(design)
e679b7d45cd4fd552b1fe54b61b914f23aca2c94
backdrop/__init__.py
backdrop/__init__.py
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX")))
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv( "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
Add a prefix to the statsd key
Add a prefix to the statsd key We have loads of stats at the top leve of our statsd stats in graphite. It makes looking for things that aren't created by backdrop really hard.
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
--- +++ @@ -22,4 +22,5 @@ return getattr(self._statsd, item) statsd = StatsClient( - _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX"))) + _statsd.StatsClient(prefix=os.getenv( + "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
d756406ac78830a2f54308814979e497d43f5ec7
cyder/cydhcp/workgroup/views.py
cyder/cydhcp/workgroup/views.py
import json from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from cyder.base.utils import make_megafilter from cyder.base.views import cy_detail from cyder.cydhcp.workgroup.models import Workgroup def workgroup_detail(request, pk): workgroup = get_object_or_404(Workgroup, pk=pk) return cy_detail(request, Workgroup, 'workgroup/workgroup_detail.html', { 'Attributes': 'workgroupav_set', 'Dynamic Interfaces': workgroup.dynamicinterface_set.all(), 'Static Interfaces': workgroup.staticinterface_set.all(), }, obj=workgroup) def search(request): """Returns a list of workgroups matching 'term'.""" term = request.GET.get('term', '') if not term: raise Http404 workgroups = Workgroup.objects.filter( make_megafilter(Workgroup, term))[:15] workgroups = [{ 'label': str(workgroup), 'pk': workgroup.id} for workgroup in workgroups] return HttpResponse(json.dumps(workgroups))
import json from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from cyder.base.utils import make_megafilter from cyder.base.views import cy_detail from cyder.cydhcp.workgroup.models import Workgroup def workgroup_detail(request, pk): workgroup = get_object_or_404(Workgroup, pk=pk) return cy_detail(request, Workgroup, 'workgroup/workgroup_detail.html', { 'Attributes': 'workgroupav_set', 'Dynamic Interfaces': workgroup.dynamicinterface_set.all(), 'Static Interfaces': workgroup.staticinterface_set.all(), 'Containers': 'ctnr_set', }, obj=workgroup) def search(request): """Returns a list of workgroups matching 'term'.""" term = request.GET.get('term', '') if not term: raise Http404 workgroups = Workgroup.objects.filter( make_megafilter(Workgroup, term))[:15] workgroups = [{ 'label': str(workgroup), 'pk': workgroup.id} for workgroup in workgroups] return HttpResponse(json.dumps(workgroups))
Add containers to workgroup detail view
Add containers to workgroup detail view
Python
bsd-3-clause
OSU-Net/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder
--- +++ @@ -14,6 +14,7 @@ 'Attributes': 'workgroupav_set', 'Dynamic Interfaces': workgroup.dynamicinterface_set.all(), 'Static Interfaces': workgroup.staticinterface_set.all(), + 'Containers': 'ctnr_set', }, obj=workgroup)
12cc6a6bf3e0d6c55a1f2780b76aecd615dfa47a
datatableview/tests/testcase.py
datatableview/tests/testcase.py
# -*- encoding: utf-8 -*- import django from django.test import TestCase from django.core.management import call_command if django.VERSION >= (1, 7): from django.test import override_settings from django.apps import apps initial_data_fixture = 'initial_data_modern' clear_app_cache = apps.clear_cache else: from django.test.utils import override_settings from django.db.models import loading initial_data_fixture = 'initial_data_legacy' def clear_app_cache(): loading.cache.loaded = False @override_settings(INSTALLED_APPS=[ 'datatableview', 'datatableview.tests.test_app', 'datatableview.tests.example_project.example_project.example_app', ]) class DatatableViewTestCase(TestCase): def _pre_setup(self): """ Asks the management script to re-sync the database. Having test-only models is a pain. """ clear_app_cache() call_command('syncdb', interactive=False, verbosity=0) call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
# -*- encoding: utf-8 -*- import django from django.test import TestCase from django.core.management import call_command if django.VERSION >= (1, 7): from django.test import override_settings from django.apps import apps migrate_command = 'migrate' initial_data_fixture = 'initial_data_modern' clear_app_cache = apps.clear_cache else: from django.test.utils import override_settings from django.db.models import loading migrate_command = 'syncdb' initial_data_fixture = 'initial_data_legacy' def clear_app_cache(): loading.cache.loaded = False @override_settings(INSTALLED_APPS=[ 'datatableview', 'datatableview.tests.test_app', 'datatableview.tests.example_project.example_project.example_app', ]) class DatatableViewTestCase(TestCase): def _pre_setup(self): """ Asks the management script to re-sync the database. Having test-only models is a pain. """ clear_app_cache() call_command(migrate_command, interactive=False, verbosity=0) call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
Adjust tests to run migrate when necessary
Adjust tests to run migrate when necessary
Python
apache-2.0
pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view,doganmeh/django-datatable-view,jangeador/django-datatable-view,doganmeh/django-datatable-view,doganmeh/django-datatable-view,jangeador/django-datatable-view,jangeador/django-datatable-view
--- +++ @@ -7,11 +7,13 @@ if django.VERSION >= (1, 7): from django.test import override_settings from django.apps import apps + migrate_command = 'migrate' initial_data_fixture = 'initial_data_modern' clear_app_cache = apps.clear_cache else: from django.test.utils import override_settings from django.db.models import loading + migrate_command = 'syncdb' initial_data_fixture = 'initial_data_legacy' def clear_app_cache(): loading.cache.loaded = False @@ -28,6 +30,6 @@ Asks the management script to re-sync the database. Having test-only models is a pain. """ clear_app_cache() - call_command('syncdb', interactive=False, verbosity=0) + call_command(migrate_command, interactive=False, verbosity=0) call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
88e8968502003f8e08c0f1d4e8bb5a575f5297b4
simple_es/event/domain_event.py
simple_es/event/domain_event.py
from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events TODO: Split logic around saving to a data store into a separate class TODO: Restrict the ability to toggle recorded """ event_type = None _identifier = None _recorded = False def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance of the Identifies class', identifier) self._identifier = identifier @property def attributes(self): """ Filter out private member variables (names prefixed with an underscore) """ return {key: value for key, value in self.__dict__.items() if key.startswith('_') is False}
from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events TODO: Split logic around saving to a data store into a separate class TODO: Restrict the ability to toggle recorded """ event_type = None _identifier = None _recorded = False def __init__(self, identifier=None, event_type=None): # Validate that identifier is an instance of an event Identifier if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance of the Identifies class', identifier, type(identifier)) # Validate that event type was set in a child if event_type is None: raise TypeError('Event type must be a string', event_type, type(event_type)) # Assign the identifier to the event self._identifier = identifier # Assign the type to the event self.event_type = event_type @property def attributes(self): """ Filter out private member variables (names prefixed with an underscore) """ return {key: value for key, value in self.__dict__.items() if key.startswith('_') is False}
Add event_type to the event constructor
Add event_type to the event constructor
Python
apache-2.0
OnShift/simple-es
--- +++ @@ -12,11 +12,22 @@ _identifier = None _recorded = False - def __init__(self, identifier=None): + def __init__(self, identifier=None, event_type=None): + # Validate that identifier is an instance of an event Identifier if not isinstance(identifier, Identifies): - raise TypeError('Event identifier must be an instance of the Identifies class', identifier) + raise TypeError('Event identifier must be an instance of the Identifies class', + identifier, + type(identifier)) + # Validate that event type was set in a child + if event_type is None: + raise TypeError('Event type must be a string', event_type, type(event_type)) + + # Assign the identifier to the event self._identifier = identifier + + # Assign the type to the event + self.event_type = event_type @property def attributes(self):
927d91239e9e374b36fead2f5c2e76b95f27b069
skimage/filter/rank/__init__.py
skimage/filter/rank/__init__.py
from .rank import * from .percentile_rank import * from .bilateral_rank import *
from .rank import (autolevel, bottomhat, equalize, gradient, maximum, mean, meansubstraction, median, minimum, modal, morph_contr_enh, pop, threshold, tophat, noise_filter, entropy, otsu) from .percentile_rank import (percentile_autolevel, percentile_gradient, percentile_mean, percentile_mean_substraction, percentile_morph_contr_enh, percentile, percentile_pop, percentile_threshold) from .bilateral_rank import bilateral_mean, bilateral_pop __all__ = ['autolevel', 'bottomhat', 'equalize', 'gradient', 'maximum', 'mean', 'meansubstraction', 'median', 'minimum', 'modal', 'morph_contr_enh', 'pop', 'threshold', 'tophat', 'noise_filter', 'entropy', 'otsu', 'percentile_autolevel', 'percentile_gradient', 'percentile_mean', 'percentile_mean_substraction', 'percentile_morph_contr_enh', 'percentile', 'percentile_pop', 'percentile_threshold', 'bilateral_mean', 'bilateral_pop']
Add __all__ to rank filter package
Add __all__ to rank filter package
Python
bsd-3-clause
rjeli/scikit-image,chriscrosscutler/scikit-image,Hiyorimi/scikit-image,emon10005/scikit-image,GaZ3ll3/scikit-image,ClinicalGraphics/scikit-image,Britefury/scikit-image,chriscrosscutler/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,dpshelio/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,ofgulban/scikit-image,paalge/scikit-image,michaelaye/scikit-image,ofgulban/scikit-image,youprofit/scikit-image,paalge/scikit-image,almarklein/scikit-image,bennlich/scikit-image,almarklein/scikit-image,Midafi/scikit-image,youprofit/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,jwiggins/scikit-image,chintak/scikit-image,michaelaye/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,jwiggins/scikit-image,Hiyorimi/scikit-image,SamHames/scikit-image,chintak/scikit-image,WarrenWeckesser/scikits-image,juliusbierk/scikit-image,pratapvardhan/scikit-image,WarrenWeckesser/scikits-image,warmspringwinds/scikit-image,ajaybhat/scikit-image,michaelpacer/scikit-image,paalge/scikit-image,bsipocz/scikit-image,chintak/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,SamHames/scikit-image,blink1073/scikit-image,bennlich/scikit-image,dpshelio/scikit-image,SamHames/scikit-image,keflavich/scikit-image,rjeli/scikit-image,Britefury/scikit-image,newville/scikit-image,robintw/scikit-image,bsipocz/scikit-image,robintw/scikit-image,oew1v07/scikit-image,michaelpacer/scikit-image,almarklein/scikit-image,vighneshbirodkar/scikit-image,rjeli/scikit-image,almarklein/scikit-image,keflavich/scikit-image,blink1073/scikit-image,pratapvardhan/scikit-image
--- +++ @@ -1,3 +1,37 @@ -from .rank import * -from .percentile_rank import * -from .bilateral_rank import * +from .rank import (autolevel, bottomhat, equalize, gradient, maximum, mean, + meansubstraction, median, minimum, modal, morph_contr_enh, + pop, threshold, tophat, noise_filter, entropy, otsu) +from .percentile_rank import (percentile_autolevel, percentile_gradient, + percentile_mean, percentile_mean_substraction, + percentile_morph_contr_enh, percentile, + percentile_pop, percentile_threshold) +from .bilateral_rank import bilateral_mean, bilateral_pop + + +__all__ = ['autolevel', + 'bottomhat', + 'equalize', + 'gradient', + 'maximum', + 'mean', + 'meansubstraction', + 'median', + 'minimum', + 'modal', + 'morph_contr_enh', + 'pop', + 'threshold', + 'tophat', + 'noise_filter', + 'entropy', + 'otsu', + 'percentile_autolevel', + 'percentile_gradient', + 'percentile_mean', + 'percentile_mean_substraction', + 'percentile_morph_contr_enh', + 'percentile', + 'percentile_pop', + 'percentile_threshold', + 'bilateral_mean', + 'bilateral_pop']
6cf147986317ed5c7d7fe4fa9785f2d88f7d7e8a
Class_Pattern.py
Class_Pattern.py
class Pattern(object): def __init__(self): self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] self.vowels = ['a','e','i','o','u']
Add vowels and consonants constants
Add vowels and consonants constants
Python
mit
achyutreddy24/WordGen
--- +++ @@ -0,0 +1,5 @@ +class Pattern(object): + + def __init__(self): + self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] + self.vowels = ['a','e','i','o','u']
e3d3c17988fee0a9f616cf4c0f0dc67a5a60fb34
Constants.py
Constants.py
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
Expand IRC numerics to name list
Expand IRC numerics to name list
Python
mit
Didero/DideRobot
--- +++ @@ -3,5 +3,8 @@ CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration -IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", +IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", + "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", + "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", + "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
9b8a39f58b32135e4fecb6ce925c239d198aa2e1
mne/realtime/classifier.py
mne/realtime/classifier.py
# Author: Mainak Jas <mainak@neuro.hut.fi> # # License: BSD (3-clause) from sklearn.base import TransformerMixin from mne.fiff import pick_types class RtClassifier: """ TODO: complete docstring ... Parameters ---------- Attributes ---------- """ def __init__(self, estimator): self.estimator = estimator def fit(self, X, y): self.estimator.fit(X, y) return self def predict(self, X): result = self.estimator.predict(X) return result class Scaler(TransformerMixin): def __init__(self, info): self.info = info def transform(self, epochs_data): picks_list = [pick_types(epochs_data.info, meg='mag', exclude='bads'), pick_types(epochs_data.info, eeg='True', exclude='bads'), pick_types(epochs_data.info, meg='grad', exclude='bads')] for pick_one in picks_list: ch_mean = epochs_data[:, pick_one, :].mean(axis=1)[:, None, :] epochs_data[:, pick_one, :] -= ch_mean return epochs_data
# Author: Mainak Jas <mainak@neuro.hut.fi> # # License: BSD (3-clause) from sklearn.base import TransformerMixin from mne.fiff import pick_types class RtClassifier: """ TODO: complete docstring ... Parameters ---------- Attributes ---------- """ def __init__(self, estimator): self.estimator = estimator def fit(self, X, y): self.estimator.fit(X, y) return self def predict(self, X): result = self.estimator.predict(X) return result class Scaler(TransformerMixin): def __init__(self, info): self.info = info def transform(self, epochs_data): picks_list = [pick_types(self.info, meg='mag', exclude='bads'), pick_types(self.info, eeg='True', exclude='bads'), pick_types(self.info, meg='grad', exclude='bads')] for pick_one in picks_list: ch_mean = epochs_data[:, pick_one, :].mean(axis=1)[:, None, :] epochs_data[:, pick_one, :] -= ch_mean return epochs_data
Fix small bug in Scaler class
Fix small bug in Scaler class
Python
bsd-3-clause
kingjr/mne-python,bloyl/mne-python,rkmaddox/mne-python,kambysese/mne-python,agramfort/mne-python,alexandrebarachant/mne-python,Teekuningas/mne-python,Teekuningas/mne-python,cmoutard/mne-python,dgwakeman/mne-python,andyh616/mne-python,wronk/mne-python,jniediek/mne-python,dgwakeman/mne-python,aestrivex/mne-python,kambysese/mne-python,kingjr/mne-python,yousrabk/mne-python,jmontoyam/mne-python,adykstra/mne-python,jaeilepp/mne-python,wmvanvliet/mne-python,olafhauk/mne-python,lorenzo-desantis/mne-python,alexandrebarachant/mne-python,teonlamont/mne-python,cmoutard/mne-python,jaeilepp/mne-python,leggitta/mne-python,nicproulx/mne-python,wmvanvliet/mne-python,olafhauk/mne-python,dimkal/mne-python,dimkal/mne-python,trachelr/mne-python,cjayb/mne-python,antiface/mne-python,drammock/mne-python,Teekuningas/mne-python,pravsripad/mne-python,larsoner/mne-python,mne-tools/mne-python,ARudiuk/mne-python,trachelr/mne-python,aestrivex/mne-python,Odingod/mne-python,cjayb/mne-python,ARudiuk/mne-python,kingjr/mne-python,lorenzo-desantis/mne-python,effigies/mne-python,nicproulx/mne-python,wronk/mne-python,agramfort/mne-python,Eric89GXL/mne-python,larsoner/mne-python,mne-tools/mne-python,matthew-tucker/mne-python,drammock/mne-python,wmvanvliet/mne-python,yousrabk/mne-python,pravsripad/mne-python,rkmaddox/mne-python,Odingod/mne-python,teonlamont/mne-python,jniediek/mne-python,larsoner/mne-python,matthew-tucker/mne-python,adykstra/mne-python,effigies/mne-python,mne-tools/mne-python,olafhauk/mne-python,antiface/mne-python,andyh616/mne-python,Eric89GXL/mne-python,jmontoyam/mne-python,drammock/mne-python,pravsripad/mne-python,leggitta/mne-python,bloyl/mne-python
--- +++ @@ -42,9 +42,9 @@ def transform(self, epochs_data): - picks_list = [pick_types(epochs_data.info, meg='mag', exclude='bads'), - pick_types(epochs_data.info, eeg='True', exclude='bads'), - pick_types(epochs_data.info, meg='grad', exclude='bads')] + picks_list = [pick_types(self.info, meg='mag', exclude='bads'), + pick_types(self.info, eeg='True', exclude='bads'), + pick_types(self.info, meg='grad', exclude='bads')] for pick_one in picks_list: ch_mean = epochs_data[:, pick_one, :].mean(axis=1)[:, None, :]
f0270de636bb84e89cbbb54896c6ed5037a48323
spiralgalaxygame/precondition.py
spiralgalaxygame/precondition.py
class PreconditionError (TypeError): def __init__(self, callee, *args): TypeError.__init__(self, '{0.__name__}{1!r}'.format(callee, args))
from types import FunctionType, MethodType class PreconditionError (TypeError): def __init__(self, callee, *args): if isinstance(callee, MethodType): name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee) elif isinstance(callee, type) or isinstance(callee, FunctionType): name = callee.__name__ TypeError.__init__(self, '{}{!r}'.format(name, args))
Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
Python
agpl-3.0
nejucomo/sgg,nejucomo/sgg,nejucomo/sgg
--- +++ @@ -1,3 +1,11 @@ +from types import FunctionType, MethodType + + class PreconditionError (TypeError): def __init__(self, callee, *args): - TypeError.__init__(self, '{0.__name__}{1!r}'.format(callee, args)) + if isinstance(callee, MethodType): + name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee) + elif isinstance(callee, type) or isinstance(callee, FunctionType): + name = callee.__name__ + + TypeError.__init__(self, '{}{!r}'.format(name, args))
671ccd8e82e0c106b0ccd9cb61b674f342319725
mopidy/backends/spotify.py
mopidy/backends/spotify.py
import spytify from mopidy import settings from mopidy.backends.base import BaseBackend class SpotifyBackend(BaseBackend): def __init__(self, *args, **kwargs): super(SpotifyBackend, self).__init__(*args, **kwargs) self.spotify = spytify.Spytify( settings.SPOTIFY_USERNAME.encode('utf-8'), settings.SPOTIFY_PASSWORD.encode('utf-8')) self._playlist_load_cache = None def playlist_load(self, name): if not self._playlist_load_cache: for playlist in self.spotify.stored_playlists: if playlist.name == name: tracks = [] for track in playlist.tracks: tracks.append(u'add %s\n' % track.file_id) self._playlist_load_cache = tracks break return self._playlist_load_cache def playlists_list(self): playlists = [] for playlist in self.spotify.stored_playlists: playlists.append(u'playlist: %s' % playlist.name.decode('utf-8')) return playlists def url_handlers(self): return [u'spotify:', u'http://open.spotify.com/']
import sys import spytify from mopidy import settings from mopidy.backends.base import BaseBackend class SpotifyBackend(BaseBackend): def __init__(self, *args, **kwargs): super(SpotifyBackend, self).__init__(*args, **kwargs) self.spotify = spytify.Spytify(self.username, self.password) self._playlist_load_cache = None @property def username(self): username = settings.SPOTIFY_USERNAME.encode('utf-8') if not username: sys.exit('Setting SPOTIFY_USERNAME is not set.') return username @property def password(self): password = settings.SPOTIFY_PASSWORD.encode('utf-8') if not password: sys.exit('Setting SPOTIFY_PASSWORD is not set.') return password def playlist_load(self, name): if not self._playlist_load_cache: for playlist in self.spotify.stored_playlists: if playlist.name == name: tracks = [] for track in playlist.tracks: tracks.append(u'add %s\n' % track.file_id) self._playlist_load_cache = tracks break return self._playlist_load_cache def playlists_list(self): playlists = [] for playlist in self.spotify.stored_playlists: playlists.append(u'playlist: %s' % playlist.name.decode('utf-8')) return playlists def url_handlers(self): return [u'spotify:', u'http://open.spotify.com/']
Exit if SPOTIFY_{USERNAME,PASSWORD} is not set
Exit if SPOTIFY_{USERNAME,PASSWORD} is not set
Python
apache-2.0
hkariti/mopidy,ali/mopidy,jcass77/mopidy,priestd09/mopidy,jmarsik/mopidy,pacificIT/mopidy,mopidy/mopidy,priestd09/mopidy,kingosticks/mopidy,vrs01/mopidy,jcass77/mopidy,bacontext/mopidy,bacontext/mopidy,woutervanwijk/mopidy,tkem/mopidy,mokieyue/mopidy,ZenithDK/mopidy,mopidy/mopidy,jodal/mopidy,swak/mopidy,bencevans/mopidy,swak/mopidy,ZenithDK/mopidy,diandiankan/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,abarisain/mopidy,quartz55/mopidy,mokieyue/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,woutervanwijk/mopidy,liamw9534/mopidy,hkariti/mopidy,quartz55/mopidy,glogiotatidis/mopidy,jmarsik/mopidy,quartz55/mopidy,pacificIT/mopidy,diandiankan/mopidy,ZenithDK/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,tkem/mopidy,dbrgn/mopidy,vrs01/mopidy,bencevans/mopidy,jcass77/mopidy,priestd09/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,dbrgn/mopidy,bacontext/mopidy,adamcik/mopidy,mokieyue/mopidy,rawdlite/mopidy,swak/mopidy,dbrgn/mopidy,hkariti/mopidy,SuperStarPL/mopidy,tkem/mopidy,abarisain/mopidy,diandiankan/mopidy,adamcik/mopidy,ZenithDK/mopidy,jodal/mopidy,mopidy/mopidy,hkariti/mopidy,rawdlite/mopidy,mokieyue/mopidy,diandiankan/mopidy,vrs01/mopidy,bencevans/mopidy,kingosticks/mopidy,liamw9534/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,ali/mopidy,vrs01/mopidy,tkem/mopidy,quartz55/mopidy,jmarsik/mopidy,rawdlite/mopidy,jodal/mopidy,swak/mopidy,glogiotatidis/mopidy,glogiotatidis/mopidy,adamcik/mopidy,rawdlite/mopidy,ali/mopidy,bencevans/mopidy
--- +++ @@ -1,3 +1,5 @@ +import sys + import spytify from mopidy import settings @@ -6,10 +8,22 @@ class SpotifyBackend(BaseBackend): def __init__(self, *args, **kwargs): super(SpotifyBackend, self).__init__(*args, **kwargs) - self.spotify = spytify.Spytify( - settings.SPOTIFY_USERNAME.encode('utf-8'), - settings.SPOTIFY_PASSWORD.encode('utf-8')) + self.spotify = spytify.Spytify(self.username, self.password) self._playlist_load_cache = None + + @property + def username(self): + username = settings.SPOTIFY_USERNAME.encode('utf-8') + if not username: + sys.exit('Setting SPOTIFY_USERNAME is not set.') + return username + + @property + def password(self): + password = settings.SPOTIFY_PASSWORD.encode('utf-8') + if not password: + sys.exit('Setting SPOTIFY_PASSWORD is not set.') + return password def playlist_load(self, name): if not self._playlist_load_cache:
a95f4ea250f4bf85b510791f6eb287e7f01a431f
doc/fake__sounddevice.py
doc/fake__sounddevice.py
"""Mock module for Sphinx autodoc.""" class ffi(object): NULL = NotImplemented I_AM_FAKE = True # This is used for the documentation of "default" def dlopen(self, _): return FakeLibrary() ffi = ffi() class FakeLibrary(object): # from portaudio.h: paFloat32 = paInt32 = paInt24 = paInt16 = paInt8 = paUInt8 = NotImplemented paFramesPerBufferUnspecified = 0 def Pa_Initialize(self): return 0 def Pa_Terminate(self): return 0 # from stdio.h: def fopen(*args, **kwargs): return NotImplemented def fclose(*args): pass
"""Mock module for Sphinx autodoc.""" import ctypes # Monkey-patch ctypes to disable searching for PortAudio ctypes.util.find_library = lambda _: NotImplemented class ffi(object): NULL = NotImplemented I_AM_FAKE = True # This is used for the documentation of "default" def dlopen(self, _): return FakeLibrary() ffi = ffi() class FakeLibrary(object): # from portaudio.h: paFloat32 = paInt32 = paInt24 = paInt16 = paInt8 = paUInt8 = NotImplemented paFramesPerBufferUnspecified = 0 def Pa_Initialize(self): return 0 def Pa_Terminate(self): return 0 # from stdio.h: def fopen(*args, **kwargs): return NotImplemented def fclose(*args): pass
Disable searching for PortAudio when building docs
DOC: Disable searching for PortAudio when building docs
Python
mit
tgarc/python-sounddevice,spatialaudio/python-sounddevice,spatialaudio/python-sounddevice,tgarc/python-sounddevice
--- +++ @@ -1,4 +1,11 @@ """Mock module for Sphinx autodoc.""" + + +import ctypes + + +# Monkey-patch ctypes to disable searching for PortAudio +ctypes.util.find_library = lambda _: NotImplemented class ffi(object):
a41327614c610c5ca4be312b0b3b976d0092fe41
cms/manage.py
cms/manage.py
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. " "It appears you've customized things.\nYou'll have to run django-admin.py, " "passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
Fix string layout for readability
Fix string layout for readability
Python
agpl-3.0
y12uc231/edx-platform,polimediaupv/edx-platform,EduPepperPDTesting/pepper2013-testing,atsolakid/edx-platform,arbrandes/edx-platform,zadgroup/edx-platform,msegado/edx-platform,Kalyzee/edx-platform,xuxiao19910803/edx,UXE/local-edx,RPI-OPENEDX/edx-platform,caesar2164/edx-platform,Lektorium-LLC/edx-platform,rationalAgent/edx-platform-custom,cognitiveclass/edx-platform,MakeHer/edx-platform,arbrandes/edx-platform,morenopc/edx-platform,eduNEXT/edx-platform,vismartltd/edx-platform,pelikanchik/edx-platform,xuxiao19910803/edx,mtlchun/edx,miptliot/edx-platform,mushtaqak/edx-platform,hmcmooc/muddx-platform,yokose-ks/edx-platform,alu042/edx-platform,ferabra/edx-platform,iivic/BoiseStateX,atsolakid/edx-platform,wwj718/edx-platform,JCBarahona/edX,nanolearning/edx-platform,syjeon/new_edx,eestay/edx-platform,marcore/edx-platform,J861449197/edx-platform,syjeon/new_edx,shabab12/edx-platform,jbzdak/edx-platform,DNFcode/edx-platform,iivic/BoiseStateX,cecep-edu/edx-platform,EduPepperPD/pepper2013,carsongee/edx-platform,Shrhawk/edx-platform,xinjiguaike/edx-platform,antoviaque/edx-platform,sameetb-cuelogic/edx-platform-test,alexthered/kienhoc-platform,jazztpt/edx-platform,abdoosh00/edx-rtl-final,TsinghuaX/edx-platform,jbzdak/edx-platform,vismartltd/edx-platform,ubc/edx-platform,atsolakid/edx-platform,gsehub/edx-platform,morpheby/levelup-by,abdoosh00/edraak,tiagochiavericosta/edx-platform,nanolearning/edx-platform,don-github/edx-platform,mcgachey/edx-platform,UOMx/edx-platform,chauhanhardik/populo_2,angelapper/edx-platform,xuxiao19910803/edx-platform,a-parhom/edx-platform,leansoft/edx-platform,morenopc/edx-platform,pomegranited/edx-platform,zhenzhai/edx-platform,yokose-ks/edx-platform,jbassen/edx-platform,simbs/edx-platform,mushtaqak/edx-platform,chudaol/edx-platform,shubhdev/edxOnBaadal,Ayub-Khan/edx-platform,kmoocdev2/edx-platform,dcosentino/edx-platform,shurihell/testasia,louyihua/edx-platform,pabloborrego93/edx-platform,morpheby/levelup-by,morenopc/edx-platform,kamalx/edx-platform,alexthered/kienhoc-platform,J861449197/edx-platform,tiagochiavericosta/edx-platform,prarthitm/edxplatform,zhenzhai/edx-platform,auferack08/edx-platform,halvertoluke/edx-platform,beacloudgenius/edx-platform,alexthered/kienhoc-platform,TeachAtTUM/edx-platform,Kalyzee/edx-platform,xuxiao19910803/edx-platform,shubhdev/edxOnBaadal,arifsetiawan/edx-platform,shubhdev/edx-platform,ahmadio/edx-platform,motion2015/edx-platform,olexiim/edx-platform,peterm-itr/edx-platform,Softmotions/edx-platform,zhenzhai/edx-platform,ahmedaljazzar/edx-platform,sudheerchintala/LearnEraPlatForm,Edraak/edraak-platform,eestay/edx-platform,jswope00/griffinx,waheedahmed/edx-platform,syjeon/new_edx,deepsrijit1105/edx-platform,knehez/edx-platform,nagyistoce/edx-platform,chand3040/cloud_that,appliedx/edx-platform,Kalyzee/edx-platform,pdehaye/theming-edx-platform,iivic/BoiseStateX,Ayub-Khan/edx-platform,bigdatauniversity/edx-platform,mushtaqak/edx-platform,jruiperezv/ANALYSE,zerobatu/edx-platform,antonve/s4-project-mooc,cpennington/edx-platform,zerobatu/edx-platform,ampax/edx-platform-backup,MSOpenTech/edx-platform,dsajkl/reqiop,sameetb-cuelogic/edx-platform-test,shubhdev/edxOnBaadal,analyseuc3m/ANALYSE-v1,OmarIthawi/edx-platform,bitifirefly/edx-platform,shubhdev/edxOnBaadal,shubhdev/edxOnBaadal,MSOpenTech/edx-platform,EduPepperPDTesting/pepper2013-testing,bitifirefly/edx-platform,rue89-tech/edx-platform,jelugbo/tundex,sameetb-cuelogic/edx-platform-test,cselis86/edx-platform,franosincic/edx-platform,iivic/BoiseStateX,nanolearningllc/edx-platform-cypress,solashirai/edx-platform,mitocw/edx-platform,jbassen/edx-platform,eduNEXT/edunext-platform,PepperPD/edx-pepper-platform,martynovp/edx-platform,waheedahmed/edx-platform,shashank971/edx-platform,benpatterson/edx-platform,ahmadiga/min_edx,kamalx/edx-platform,shurihell/testasia,arbrandes/edx-platform,dkarakats/edx-platform,teltek/edx-platform,jruiperezv/ANALYSE,edx-solutions/edx-platform,doismellburning/edx-platform,deepsrijit1105/edx-platform,vasyarv/edx-platform,JCBarahona/edX,ZLLab-Mooc/edx-platform,inares/edx-platform,B-MOOC/edx-platform,hkawasaki/kawasaki-aio8-2,chauhanhardik/populo_2,IONISx/edx-platform,mitocw/edx-platform,mahendra-r/edx-platform,jswope00/griffinx,wwj718/edx-platform,leansoft/edx-platform,hastexo/edx-platform,louyihua/edx-platform,vikas1885/test1,MakeHer/edx-platform,DNFcode/edx-platform,EDUlib/edx-platform,abdoosh00/edraak,amir-qayyum-khan/edx-platform,zadgroup/edx-platform,fintech-circle/edx-platform,jamiefolsom/edx-platform,B-MOOC/edx-platform,unicri/edx-platform,naresh21/synergetics-edx-platform,cognitiveclass/edx-platform,sudheerchintala/LearnEraPlatForm,chudaol/edx-platform,philanthropy-u/edx-platform,ampax/edx-platform,praveen-pal/edx-platform,jonathan-beard/edx-platform,mjg2203/edx-platform-seas,JCBarahona/edX,y12uc231/edx-platform,nikolas/edx-platform,motion2015/edx-platform,longmen21/edx-platform,torchingloom/edx-platform,MakeHer/edx-platform,marcore/edx-platform,torchingloom/edx-platform,beni55/edx-platform,jswope00/griffinx,Edraak/circleci-edx-platform,Edraak/edraak-platform,shubhdev/openedx,motion2015/edx-platform,DefyVentures/edx-platform,J861449197/edx-platform,jazkarta/edx-platform-for-isc,mahendra-r/edx-platform,naresh21/synergetics-edx-platform,inares/edx-platform,shubhdev/openedx,dsajkl/123,franosincic/edx-platform,zofuthan/edx-platform,zofuthan/edx-platform,simbs/edx-platform,ahmedaljazzar/edx-platform,jolyonb/edx-platform,dcosentino/edx-platform,kalebhartje/schoolboost,DNFcode/edx-platform,apigee/edx-platform,jamesblunt/edx-platform,cognitiveclass/edx-platform,playm2mboy/edx-platform,Edraak/edraak-platform,BehavioralInsightsTeam/edx-platform,SravanthiSinha/edx-platform,martynovp/edx-platform,devs1991/test_edx_docmode,nanolearningllc/edx-platform-cypress-2,edx/edx-platform,chrisndodge/edx-platform,EduPepperPDTesting/pepper2013-testing,chauhanhardik/populo,wwj718/ANALYSE,marcore/edx-platform,etzhou/edx-platform,xingyepei/edx-platform,antoviaque/edx-platform,doganov/edx-platform,dsajkl/123,xuxiao19910803/edx,ampax/edx-platform,utecuy/edx-platform,motion2015/a3,eduNEXT/edunext-platform,a-parhom/edx-platform,CourseTalk/edx-platform,torchingloom/edx-platform,alu042/edx-platform,stvstnfrd/edx-platform,edry/edx-platform,shubhdev/edx-platform,J861449197/edx-platform,edx/edx-platform,romain-li/edx-platform,ampax/edx-platform-backup,procangroup/edx-platform,edry/edx-platform,abdoosh00/edraak,eduNEXT/edx-platform,apigee/edx-platform,vismartltd/edx-platform,abdoosh00/edx-rtl-final,don-github/edx-platform,bigdatauniversity/edx-platform,chand3040/cloud_that,EduPepperPDTesting/pepper2013-testing,knehez/edx-platform,kalebhartje/schoolboost,IndonesiaX/edx-platform,Edraak/circleci-edx-platform,andyzsf/edx,antonve/s4-project-mooc,raccoongang/edx-platform,jzoldak/edx-platform,etzhou/edx-platform,jbassen/edx-platform,jelugbo/tundex,xinjiguaike/edx-platform,vasyarv/edx-platform,andyzsf/edx,appsembler/edx-platform,nanolearningllc/edx-platform-cypress-2,openfun/edx-platform,eemirtekin/edx-platform,antoviaque/edx-platform,AkA84/edx-platform,wwj718/ANALYSE,chauhanhardik/populo_2,rhndg/openedx,procangroup/edx-platform,unicri/edx-platform,JioEducation/edx-platform,chauhanhardik/populo,defance/edx-platform,DNFcode/edx-platform,eestay/edx-platform,TeachAtTUM/edx-platform,ovnicraft/edx-platform,adoosii/edx-platform,jazkarta/edx-platform-for-isc,jswope00/griffinx,RPI-OPENEDX/edx-platform,jbzdak/edx-platform,IITBinterns13/edx-platform-dev,PepperPD/edx-pepper-platform,ZLLab-Mooc/edx-platform,TsinghuaX/edx-platform,jamiefolsom/edx-platform,sudheerchintala/LearnEraPlatForm,chand3040/cloud_that,polimediaupv/edx-platform,SravanthiSinha/edx-platform,gymnasium/edx-platform,kmoocdev2/edx-platform,pku9104038/edx-platform,arifsetiawan/edx-platform,msegado/edx-platform,yokose-ks/edx-platform,nttks/jenkins-test,nikolas/edx-platform,kxliugang/edx-platform,alu042/edx-platform,nagyistoce/edx-platform,mushtaqak/edx-platform,longmen21/edx-platform,JioEducation/edx-platform,10clouds/edx-platform,dcosentino/edx-platform,doganov/edx-platform,doismellburning/edx-platform,cyanna/edx-platform,mbareta/edx-platform-ft,zofuthan/edx-platform,appsembler/edx-platform,halvertoluke/edx-platform,andyzsf/edx,hamzehd/edx-platform,xinjiguaike/edx-platform,zubair-arbi/edx-platform,praveen-pal/edx-platform,defance/edx-platform,franosincic/edx-platform,shubhdev/openedx,dkarakats/edx-platform,arifsetiawan/edx-platform,nttks/jenkins-test,iivic/BoiseStateX,chauhanhardik/populo,CredoReference/edx-platform,peterm-itr/edx-platform,peterm-itr/edx-platform,leansoft/edx-platform,RPI-OPENEDX/edx-platform,UOMx/edx-platform,BehavioralInsightsTeam/edx-platform,nttks/edx-platform,jolyonb/edx-platform,halvertoluke/edx-platform,arifsetiawan/edx-platform,10clouds/edx-platform,philanthropy-u/edx-platform,SivilTaram/edx-platform,marcore/edx-platform,jazkarta/edx-platform-for-isc,don-github/edx-platform,ferabra/edx-platform,Edraak/edx-platform,Lektorium-LLC/edx-platform,jolyonb/edx-platform,zubair-arbi/edx-platform,auferack08/edx-platform,kxliugang/edx-platform,DefyVentures/edx-platform,martynovp/edx-platform,alexthered/kienhoc-platform,Shrhawk/edx-platform,pepeportela/edx-platform,Semi-global/edx-platform,nikolas/edx-platform,eduNEXT/edx-platform,ahmedaljazzar/edx-platform,rationalAgent/edx-platform-custom,amir-qayyum-khan/edx-platform,msegado/edx-platform,unicri/edx-platform,antoviaque/edx-platform,nagyistoce/edx-platform,jbassen/edx-platform,Lektorium-LLC/edx-platform,IITBinterns13/edx-platform-dev,Stanford-Online/edx-platform,zhenzhai/edx-platform,chauhanhardik/populo_2,utecuy/edx-platform,tiagochiavericosta/edx-platform,IONISx/edx-platform,abdoosh00/edx-rtl-final,WatanabeYasumasa/edx-platform,playm2mboy/edx-platform,jswope00/griffinx,ubc/edx-platform,pdehaye/theming-edx-platform,gymnasium/edx-platform,philanthropy-u/edx-platform,EduPepperPD/pepper2013,bigdatauniversity/edx-platform,morpheby/levelup-by,zhenzhai/edx-platform,ahmadio/edx-platform,romain-li/edx-platform,nanolearningllc/edx-platform-cypress-2,mtlchun/edx,playm2mboy/edx-platform,Edraak/circleci-edx-platform,solashirai/edx-platform,gymnasium/edx-platform,cyanna/edx-platform,nanolearningllc/edx-platform-cypress,B-MOOC/edx-platform,prarthitm/edxplatform,nanolearningllc/edx-platform-cypress,hamzehd/edx-platform,jazztpt/edx-platform,B-MOOC/edx-platform,fintech-circle/edx-platform,xingyepei/edx-platform,morenopc/edx-platform,xingyepei/edx-platform,rhndg/openedx,caesar2164/edx-platform,CredoReference/edx-platform,jazkarta/edx-platform,appliedx/edx-platform,kamalx/edx-platform,dsajkl/reqiop,synergeticsedx/deployment-wipro,itsjeyd/edx-platform,pdehaye/theming-edx-platform,jamiefolsom/edx-platform,louyihua/edx-platform,jswope00/GAI,motion2015/edx-platform,ferabra/edx-platform,edx/edx-platform,benpatterson/edx-platform,jazkarta/edx-platform,kmoocdev2/edx-platform,zerobatu/edx-platform,fly19890211/edx-platform,utecuy/edx-platform,IITBinterns13/edx-platform-dev,miptliot/edx-platform,lduarte1991/edx-platform,valtech-mooc/edx-platform,tiagochiavericosta/edx-platform,JCBarahona/edX,analyseuc3m/ANALYSE-v1,msegado/edx-platform,ahmadio/edx-platform,TeachAtTUM/edx-platform,dsajkl/reqiop,hastexo/edx-platform,10clouds/edx-platform,valtech-mooc/edx-platform,tanmaykm/edx-platform,philanthropy-u/edx-platform,analyseuc3m/ANALYSE-v1,shurihell/testasia,bdero/edx-platform,mjg2203/edx-platform-seas,ahmadiga/min_edx,zerobatu/edx-platform,hkawasaki/kawasaki-aio8-2,MSOpenTech/edx-platform,chauhanhardik/populo_2,LICEF/edx-platform,mjirayu/sit_academy,angelapper/edx-platform,rhndg/openedx,mtlchun/edx,stvstnfrd/edx-platform,UOMx/edx-platform,procangroup/edx-platform,morpheby/levelup-by,rue89-tech/edx-platform,miptliot/edx-platform,chrisndodge/edx-platform,jazztpt/edx-platform,chauhanhardik/populo,kmoocdev/edx-platform,openfun/edx-platform,dkarakats/edx-platform,deepsrijit1105/edx-platform,pdehaye/theming-edx-platform,mbareta/edx-platform-ft,PepperPD/edx-pepper-platform,appliedx/edx-platform,doismellburning/edx-platform,mtlchun/edx,4eek/edx-platform,Softmotions/edx-platform,jazkarta/edx-platform-for-isc,gsehub/edx-platform,gsehub/edx-platform,kursitet/edx-platform,Edraak/edx-platform,Lektorium-LLC/edx-platform,kamalx/edx-platform,nttks/edx-platform,4eek/edx-platform,wwj718/edx-platform,hkawasaki/kawasaki-aio8-1,SravanthiSinha/edx-platform,zofuthan/edx-platform,valtech-mooc/edx-platform,Softmotions/edx-platform,xuxiao19910803/edx-platform,shabab12/edx-platform,SravanthiSinha/edx-platform,ubc/edx-platform,mcgachey/edx-platform,doganov/edx-platform,apigee/edx-platform,fintech-circle/edx-platform,mahendra-r/edx-platform,caesar2164/edx-platform,sameetb-cuelogic/edx-platform-test,SivilTaram/edx-platform,unicri/edx-platform,xinjiguaike/edx-platform,LICEF/edx-platform,waheedahmed/edx-platform,devs1991/test_edx_docmode,kmoocdev/edx-platform,vikas1885/test1,4eek/edx-platform,devs1991/test_edx_docmode,shubhdev/edx-platform,cognitiveclass/edx-platform,cyanna/edx-platform,etzhou/edx-platform,benpatterson/edx-platform,kursitet/edx-platform,romain-li/edx-platform,jamesblunt/edx-platform,chudaol/edx-platform,mjg2203/edx-platform-seas,beni55/edx-platform,arifsetiawan/edx-platform,cpennington/edx-platform,nanolearning/edx-platform,raccoongang/edx-platform,hkawasaki/kawasaki-aio8-1,stvstnfrd/edx-platform,kxliugang/edx-platform,sudheerchintala/LearnEraPlatForm,appliedx/edx-platform,alexthered/kienhoc-platform,Endika/edx-platform,solashirai/edx-platform,xuxiao19910803/edx,ESOedX/edx-platform,cpennington/edx-platform,jjmiranda/edx-platform,LearnEra/LearnEraPlaftform,dsajkl/123,franosincic/edx-platform,OmarIthawi/edx-platform,synergeticsedx/deployment-wipro,shubhdev/openedx,angelapper/edx-platform,RPI-OPENEDX/edx-platform,UXE/local-edx,mjg2203/edx-platform-seas,rismalrv/edx-platform,dsajkl/123,IONISx/edx-platform,rue89-tech/edx-platform,caesar2164/edx-platform,morenopc/edx-platform,leansoft/edx-platform,pabloborrego93/edx-platform,Shrhawk/edx-platform,ahmadio/edx-platform,fly19890211/edx-platform,jamesblunt/edx-platform,CourseTalk/edx-platform,pepeportela/edx-platform,deepsrijit1105/edx-platform,ubc/edx-platform,lduarte1991/edx-platform,IndonesiaX/edx-platform,hamzehd/edx-platform,Unow/edx-platform,xingyepei/edx-platform,jelugbo/tundex,hamzehd/edx-platform,playm2mboy/edx-platform,J861449197/edx-platform,solashirai/edx-platform,devs1991/test_edx_docmode,doganov/edx-platform,lduarte1991/edx-platform,dkarakats/edx-platform,mitocw/edx-platform,LearnEra/LearnEraPlaftform,rhndg/openedx,shashank971/edx-platform,jjmiranda/edx-platform,Ayub-Khan/edx-platform,wwj718/ANALYSE,arbrandes/edx-platform,MakeHer/edx-platform,10clouds/edx-platform,polimediaupv/edx-platform,xuxiao19910803/edx-platform,hamzehd/edx-platform,Semi-global/edx-platform,doganov/edx-platform,beni55/edx-platform,nanolearningllc/edx-platform-cypress-2,DefyVentures/edx-platform,PepperPD/edx-pepper-platform,hkawasaki/kawasaki-aio8-0,sameetb-cuelogic/edx-platform-test,edry/edx-platform,EduPepperPDTesting/pepper2013-testing,Softmotions/edx-platform,edry/edx-platform,edx-solutions/edx-platform,Ayub-Khan/edx-platform,atsolakid/edx-platform,cselis86/edx-platform,edx-solutions/edx-platform,itsjeyd/edx-platform,ahmadiga/min_edx,rhndg/openedx,halvertoluke/edx-platform,cecep-edu/edx-platform,eemirtekin/edx-platform,4eek/edx-platform,ferabra/edx-platform,simbs/edx-platform,jruiperezv/ANALYSE,Stanford-Online/edx-platform,nanolearningllc/edx-platform-cypress-2,motion2015/a3,etzhou/edx-platform,jjmiranda/edx-platform,mushtaqak/edx-platform,SivilTaram/edx-platform,beacloudgenius/edx-platform,jzoldak/edx-platform,raccoongang/edx-platform,nagyistoce/edx-platform,motion2015/edx-platform,mbareta/edx-platform-ft,syjeon/new_edx,adoosii/edx-platform,auferack08/edx-platform,jruiperezv/ANALYSE,kalebhartje/schoolboost,JioEducation/edx-platform,SivilTaram/edx-platform,olexiim/edx-platform,LearnEra/LearnEraPlaftform,hkawasaki/kawasaki-aio8-2,ak2703/edx-platform,CourseTalk/edx-platform,abdoosh00/edx-rtl-final,nanolearningllc/edx-platform-cypress,jamesblunt/edx-platform,vasyarv/edx-platform,itsjeyd/edx-platform,romain-li/edx-platform,devs1991/test_edx_docmode,pku9104038/edx-platform,hkawasaki/kawasaki-aio8-2,MSOpenTech/edx-platform,naresh21/synergetics-edx-platform,hastexo/edx-platform,bdero/edx-platform,motion2015/a3,torchingloom/edx-platform,tanmaykm/edx-platform,Stanford-Online/edx-platform,don-github/edx-platform,jzoldak/edx-platform,longmen21/edx-platform,cselis86/edx-platform,knehez/edx-platform,Shrhawk/edx-platform,auferack08/edx-platform,kmoocdev2/edx-platform,jruiperezv/ANALYSE,AkA84/edx-platform,apigee/edx-platform,eemirtekin/edx-platform,Softmotions/edx-platform,cpennington/edx-platform,dsajkl/reqiop,shubhdev/edx-platform,nikolas/edx-platform,ak2703/edx-platform,antonve/s4-project-mooc,martynovp/edx-platform,doismellburning/edx-platform,ampax/edx-platform-backup,shurihell/testasia,mjirayu/sit_academy,a-parhom/edx-platform,hmcmooc/muddx-platform,jswope00/GAI,ak2703/edx-platform,ahmadio/edx-platform,peterm-itr/edx-platform,yokose-ks/edx-platform,amir-qayyum-khan/edx-platform,chrisndodge/edx-platform,UXE/local-edx,UOMx/edx-platform,pelikanchik/edx-platform,B-MOOC/edx-platform,naresh21/synergetics-edx-platform,bdero/edx-platform,abdoosh00/edraak,LearnEra/LearnEraPlaftform,unicri/edx-platform,devs1991/test_edx_docmode,EduPepperPD/pepper2013,kursitet/edx-platform,zadgroup/edx-platform,EduPepperPD/pepper2013,ESOedX/edx-platform,tiagochiavericosta/edx-platform,rue89-tech/edx-platform,angelapper/edx-platform,zerobatu/edx-platform,zadgroup/edx-platform,beni55/edx-platform,chand3040/cloud_that,motion2015/a3,shashank971/edx-platform,DNFcode/edx-platform,ampax/edx-platform-backup,WatanabeYasumasa/edx-platform,bitifirefly/edx-platform,mbareta/edx-platform-ft,teltek/edx-platform,jbzdak/edx-platform,shubhdev/openedx,jonathan-beard/edx-platform,eemirtekin/edx-platform,carsongee/edx-platform,andyzsf/edx,knehez/edx-platform,kmoocdev/edx-platform,jamesblunt/edx-platform,shurihell/testasia,zofuthan/edx-platform,vasyarv/edx-platform,lduarte1991/edx-platform,itsjeyd/edx-platform,jazkarta/edx-platform-for-isc,analyseuc3m/ANALYSE-v1,chudaol/edx-platform,Endika/edx-platform,beacloudgenius/edx-platform,eduNEXT/edunext-platform,bitifirefly/edx-platform,defance/edx-platform,msegado/edx-platform,jonathan-beard/edx-platform,leansoft/edx-platform,kalebhartje/schoolboost,tanmaykm/edx-platform,bigdatauniversity/edx-platform,mahendra-r/edx-platform,carsongee/edx-platform,pepeportela/edx-platform,prarthitm/edxplatform,doismellburning/edx-platform,shabab12/edx-platform,MakeHer/edx-platform,stvstnfrd/edx-platform,bitifirefly/edx-platform,kursitet/edx-platform,olexiim/edx-platform,solashirai/edx-platform,kalebhartje/schoolboost,jjmiranda/edx-platform,dsajkl/123,shashank971/edx-platform,amir-qayyum-khan/edx-platform,cecep-edu/edx-platform,benpatterson/edx-platform,miptliot/edx-platform,vikas1885/test1,vismartltd/edx-platform,ovnicraft/edx-platform,jazkarta/edx-platform,dcosentino/edx-platform,rismalrv/edx-platform,Shrhawk/edx-platform,Edraak/circleci-edx-platform,jazztpt/edx-platform,Livit/Livit.Learn.EdX,longmen21/edx-platform,EduPepperPDTesting/pepper2013-testing,waheedahmed/edx-platform,a-parhom/edx-platform,jonathan-beard/edx-platform,pku9104038/edx-platform,gsehub/edx-platform,y12uc231/edx-platform,kmoocdev/edx-platform,praveen-pal/edx-platform,hmcmooc/muddx-platform,utecuy/edx-platform,jazztpt/edx-platform,EduPepperPD/pepper2013,nanolearning/edx-platform,ovnicraft/edx-platform,hkawasaki/kawasaki-aio8-1,rismalrv/edx-platform,jelugbo/tundex,edx-solutions/edx-platform,kxliugang/edx-platform,kamalx/edx-platform,franosincic/edx-platform,nanolearning/edx-platform,procangroup/edx-platform,ahmadiga/min_edx,vikas1885/test1,nttks/edx-platform,rue89-tech/edx-platform,mcgachey/edx-platform,openfun/edx-platform,bdero/edx-platform,ferabra/edx-platform,jswope00/GAI,pelikanchik/edx-platform,pabloborrego93/edx-platform,prarthitm/edxplatform,devs1991/test_edx_docmode,WatanabeYasumasa/edx-platform,Stanford-Online/edx-platform,AkA84/edx-platform,polimediaupv/edx-platform,wwj718/ANALYSE,Semi-global/edx-platform,EDUlib/edx-platform,pelikanchik/edx-platform,Edraak/edx-platform,Edraak/edraak-platform,LICEF/edx-platform,ZLLab-Mooc/edx-platform,jelugbo/tundex,DefyVentures/edx-platform,WatanabeYasumasa/edx-platform,Kalyzee/edx-platform,pomegranited/edx-platform,LICEF/edx-platform,jzoldak/edx-platform,IndonesiaX/edx-platform,IITBinterns13/edx-platform-dev,wwj718/edx-platform,y12uc231/edx-platform,pomegranited/edx-platform,hmcmooc/muddx-platform,vikas1885/test1,zubair-arbi/edx-platform,appsembler/edx-platform,teltek/edx-platform,cselis86/edx-platform,knehez/edx-platform,appsembler/edx-platform,chudaol/edx-platform,4eek/edx-platform,proversity-org/edx-platform,Unow/edx-platform,nikolas/edx-platform,don-github/edx-platform,ZLLab-Mooc/edx-platform,nttks/edx-platform,jazkarta/edx-platform,tanmaykm/edx-platform,pepeportela/edx-platform,beacloudgenius/edx-platform,zubair-arbi/edx-platform,ovnicraft/edx-platform,TsinghuaX/edx-platform,eestay/edx-platform,inares/edx-platform,fly19890211/edx-platform,kxliugang/edx-platform,chand3040/cloud_that,carsongee/edx-platform,yokose-ks/edx-platform,hkawasaki/kawasaki-aio8-0,adoosii/edx-platform,ampax/edx-platform,kursitet/edx-platform,synergeticsedx/deployment-wipro,olexiim/edx-platform,IONISx/edx-platform,halvertoluke/edx-platform,Livit/Livit.Learn.EdX,ahmedaljazzar/edx-platform,vismartltd/edx-platform,ESOedX/edx-platform,synergeticsedx/deployment-wipro,cecep-edu/edx-platform,MSOpenTech/edx-platform,nanolearningllc/edx-platform-cypress,teltek/edx-platform,edry/edx-platform,OmarIthawi/edx-platform,longmen21/edx-platform,hastexo/edx-platform,cyanna/edx-platform,AkA84/edx-platform,valtech-mooc/edx-platform,mjirayu/sit_academy,olexiim/edx-platform,simbs/edx-platform,cognitiveclass/edx-platform,adoosii/edx-platform,proversity-org/edx-platform,hkawasaki/kawasaki-aio8-0,beni55/edx-platform,ovnicraft/edx-platform,proversity-org/edx-platform,shabab12/edx-platform,chauhanhardik/populo,kmoocdev/edx-platform,ahmadiga/min_edx,JCBarahona/edX,adoosii/edx-platform,proversity-org/edx-platform,jbzdak/edx-platform,rationalAgent/edx-platform-custom,appliedx/edx-platform,hkawasaki/kawasaki-aio8-0,mjirayu/sit_academy,devs1991/test_edx_docmode,ubc/edx-platform,ampax/edx-platform,vasyarv/edx-platform,cecep-edu/edx-platform,beacloudgenius/edx-platform,ZLLab-Mooc/edx-platform,jbassen/edx-platform,Semi-global/edx-platform,raccoongang/edx-platform,eduNEXT/edunext-platform,xuxiao19910803/edx-platform,Semi-global/edx-platform,torchingloom/edx-platform,wwj718/edx-platform,Edraak/circleci-edx-platform,OmarIthawi/edx-platform,Edraak/edx-platform,romain-li/edx-platform,zadgroup/edx-platform,edx/edx-platform,CredoReference/edx-platform,xinjiguaike/edx-platform,TsinghuaX/edx-platform,inares/edx-platform,Livit/Livit.Learn.EdX,mitocw/edx-platform,nttks/jenkins-test,inares/edx-platform,EDUlib/edx-platform,jamiefolsom/edx-platform,louyihua/edx-platform,cyanna/edx-platform,kmoocdev2/edx-platform,EDUlib/edx-platform,nttks/jenkins-test,SravanthiSinha/edx-platform,simbs/edx-platform,hkawasaki/kawasaki-aio8-1,mcgachey/edx-platform,praveen-pal/edx-platform,atsolakid/edx-platform,Endika/edx-platform,nttks/jenkins-test,pku9104038/edx-platform,defance/edx-platform,dkarakats/edx-platform,wwj718/ANALYSE,Unow/edx-platform,mtlchun/edx,Livit/Livit.Learn.EdX,y12uc231/edx-platform,jazkarta/edx-platform,rationalAgent/edx-platform-custom,fly19890211/edx-platform,Kalyzee/edx-platform,chrisndodge/edx-platform,fly19890211/edx-platform,polimediaupv/edx-platform,jonathan-beard/edx-platform,shubhdev/edx-platform,jamiefolsom/edx-platform,eestay/edx-platform,rismalrv/edx-platform,SivilTaram/edx-platform,openfun/edx-platform,BehavioralInsightsTeam/edx-platform,Edraak/edx-platform,shashank971/edx-platform,rationalAgent/edx-platform-custom,motion2015/a3,antonve/s4-project-mooc,openfun/edx-platform,playm2mboy/edx-platform,gymnasium/edx-platform,pomegranited/edx-platform,eduNEXT/edx-platform,CredoReference/edx-platform,utecuy/edx-platform,ak2703/edx-platform,cselis86/edx-platform,jswope00/GAI,Endika/edx-platform,jolyonb/edx-platform,mahendra-r/edx-platform,DefyVentures/edx-platform,AkA84/edx-platform,xingyepei/edx-platform,pabloborrego93/edx-platform,xuxiao19910803/edx,ak2703/edx-platform,dcosentino/edx-platform,Unow/edx-platform,martynovp/edx-platform,CourseTalk/edx-platform,waheedahmed/edx-platform,etzhou/edx-platform,PepperPD/edx-pepper-platform,bigdatauniversity/edx-platform,RPI-OPENEDX/edx-platform,IndonesiaX/edx-platform,Ayub-Khan/edx-platform,eemirtekin/edx-platform,benpatterson/edx-platform,pomegranited/edx-platform,IONISx/edx-platform,mjirayu/sit_academy,valtech-mooc/edx-platform,JioEducation/edx-platform,nttks/edx-platform,UXE/local-edx,antonve/s4-project-mooc,fintech-circle/edx-platform,alu042/edx-platform,ESOedX/edx-platform,BehavioralInsightsTeam/edx-platform,ampax/edx-platform-backup,nagyistoce/edx-platform,zubair-arbi/edx-platform,mcgachey/edx-platform,rismalrv/edx-platform,LICEF/edx-platform,TeachAtTUM/edx-platform,IndonesiaX/edx-platform
--- +++ @@ -5,7 +5,9 @@ imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys - sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. " + "It appears you've customized things.\nYou'll have to run django-admin.py, " + "passing it your settings module.\n" % __file__) sys.exit(1) import settings
34ba8742d576414a65a4f19b8bdc89e5e3c759b3
astropy/io/ascii/tests/test_compressed.py
astropy/io/ascii/tests/test_compressed.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import numpy as np from ....tests.helper import pytest from .. import read ROOT = os.path.abspath(os.path.dirname(__file__)) @pytest.mark.parametrize('filename', ['t/daophot.dat.gz', 't/latex1.tex.gz', 't/short.rdb.gz']) def test_gzip(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.gz', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp._data == t_uncomp._data) @pytest.mark.parametrize('filename', ['t/short.rdb.bz2', 't/ipac.dat.bz2']) def test_bzip2(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.bz2', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp._data == t_uncomp._data)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import numpy as np from ....tests.helper import pytest from .. import read ROOT = os.path.abspath(os.path.dirname(__file__)) @pytest.mark.parametrize('filename', ['t/daophot.dat.gz', 't/latex1.tex.gz', 't/short.rdb.gz']) def test_gzip(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.gz', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp.as_array() == t_uncomp.as_array()) @pytest.mark.parametrize('filename', ['t/short.rdb.bz2', 't/ipac.dat.bz2']) def test_bzip2(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.bz2', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp.as_array() == t_uncomp.as_array())
Use as_array() instead of _data in io.ascii compressed tests
Use as_array() instead of _data in io.ascii compressed tests
Python
bsd-3-clause
dhomeier/astropy,StuartLittlefair/astropy,mhvk/astropy,saimn/astropy,saimn/astropy,astropy/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,DougBurke/astropy,dhomeier/astropy,stargaser/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,MSeifert04/astropy,astropy/astropy,lpsinger/astropy,saimn/astropy,tbabej/astropy,joergdietrich/astropy,bsipocz/astropy,pllim/astropy,stargaser/astropy,stargaser/astropy,tbabej/astropy,bsipocz/astropy,MSeifert04/astropy,kelle/astropy,saimn/astropy,AustereCuriosity/astropy,astropy/astropy,mhvk/astropy,MSeifert04/astropy,kelle/astropy,AustereCuriosity/astropy,MSeifert04/astropy,tbabej/astropy,StuartLittlefair/astropy,stargaser/astropy,mhvk/astropy,kelle/astropy,kelle/astropy,lpsinger/astropy,lpsinger/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,funbaker/astropy,mhvk/astropy,pllim/astropy,pllim/astropy,joergdietrich/astropy,pllim/astropy,larrybradley/astropy,larrybradley/astropy,funbaker/astropy,lpsinger/astropy,tbabej/astropy,AustereCuriosity/astropy,bsipocz/astropy,larrybradley/astropy,mhvk/astropy,DougBurke/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,dhomeier/astropy,astropy/astropy,lpsinger/astropy,pllim/astropy,dhomeier/astropy,larrybradley/astropy,joergdietrich/astropy,funbaker/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,DougBurke/astropy,kelle/astropy,DougBurke/astropy,astropy/astropy,saimn/astropy,funbaker/astropy,tbabej/astropy,bsipocz/astropy
--- +++ @@ -14,7 +14,7 @@ t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.gz', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names - assert np.all(t_comp._data == t_uncomp._data) + assert np.all(t_comp.as_array() == t_uncomp.as_array()) @pytest.mark.parametrize('filename', ['t/short.rdb.bz2', 't/ipac.dat.bz2']) @@ -22,4 +22,4 @@ t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.bz2', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names - assert np.all(t_comp._data == t_uncomp._data) + assert np.all(t_comp.as_array() == t_uncomp.as_array())
7ca0291b5ef0c9505d36abdc15fa9622aa433788
police_api/service.py
police_api/service.py
import logging import requests logger = logging.getLogger(__name__) class APIError(Exception): pass class BaseService(object): def __init__(self, api, **config): self.api = api self.requester = requests.session() self.config = { 'base_url': 'http://data.police.uk/api/', } self.config.update(config) self.set_credentials(self.config.get('username'), self.config.get('password')) def set_credentials(self, username, password): if username and password: self.requester.auth = (username, password) def raise_for_status(self, request): try: request.raise_for_status() except requests.models.HTTPError as e: raise APIError(e) def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs url = self.config['base_url'] + method logger.debug('%s %s' % (verb, url)) r = self.requester.request(verb, url, **request_kwargs) self.raise_for_status(r) return r.json()
import logging import requests logger = logging.getLogger(__name__) class APIError(Exception): pass class BaseService(object): def __init__(self, api, **config): self.api = api self.requester = requests.session() self.config = { 'base_url': 'http://data.police.uk/api/', } self.config.update(config) self.set_credentials(self.config.get('username'), self.config.get('password')) def set_credentials(self, username, password): if username and password: self.requester.auth = (username, password) def raise_for_status(self, request): try: request.raise_for_status() except requests.models.HTTPError as e: raise APIError(e) def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = { 'timeout': self.config.get('timeout', 20), } if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs url = self.config['base_url'] + method logger.debug('%s %s' % (verb, url)) r = self.requester.request(verb, url, **request_kwargs) self.raise_for_status(r) return r.json()
Add timeout config parameter with a default of 20 seconds
Add timeout config parameter with a default of 20 seconds
Python
mit
rkhleics/police-api-client-python
--- +++ @@ -33,7 +33,9 @@ def request(self, verb, method, **kwargs): verb = verb.upper() - request_kwargs = {} + request_kwargs = { + 'timeout': self.config.get('timeout', 20), + } if verb == 'GET': request_kwargs['params'] = kwargs else:
bac9b62c40d0c69dcb346adfe82309e10a480276
inonemonth/challenges/tests/test_forms.py
inonemonth/challenges/tests/test_forms.py
import unittest import django.test from django.core.exceptions import ValidationError from core.tests.setups import RobrechtSocialUserFactory from ..validators import RepoExistanceValidator ############################################################################### # Forms # ############################################################################### ''' from ..forms import InvestmentModelForm class InvestmentModelFormTestCase(TestCase): """ Tests for InvestmentModelForm """ def test_initial_value_of_investor_type(self): """ Verify initial value of investor_type field of InvestmentModelForm. """ investor_type_initial = InvestmentModelForm().fields["investor_type"].initial self.assertEqual(investor_type_initial, "PERSON") ''' ############################################################################### # Validators # ############################################################################### # Test takes longer than average test because of requests call #@unittest.skip("") class RepoExistanceValidatorTestCase(django.test.TestCase): def test_repo_existance_validator(self): user_rob = RobrechtSocialUserFactory() self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
import unittest import django.test from django.core.exceptions import ValidationError from core.tests.setups import RobrechtSocialUserFactory from ..validators import RepoExistanceValidator ############################################################################### # Forms # ############################################################################### ''' from ..forms import InvestmentModelForm class InvestmentModelFormTestCase(TestCase): """ Tests for InvestmentModelForm """ def test_initial_value_of_investor_type(self): """ Verify initial value of investor_type field of InvestmentModelForm. """ investor_type_initial = InvestmentModelForm().fields["investor_type"].initial self.assertEqual(investor_type_initial, "PERSON") ''' ############################################################################### # Validators # ############################################################################### # Test takes about ~0.7 secs because of requests call @unittest.skip("") class RepoExistanceValidatorTestCase(django.test.TestCase): def test_repo_existance_validator(self): user_rob = RobrechtSocialUserFactory() self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
Write note for test that triggers get request
Write note for test that triggers get request
Python
mit
robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth
--- +++ @@ -30,8 +30,8 @@ # Validators # ############################################################################### -# Test takes longer than average test because of requests call -#@unittest.skip("") +# Test takes about ~0.7 secs because of requests call +@unittest.skip("") class RepoExistanceValidatorTestCase(django.test.TestCase): def test_repo_existance_validator(self): user_rob = RobrechtSocialUserFactory()
8033ce16b11ff7317ecc3c9ef7db448c44b72b1b
providers/popularity/torrentz.py
providers/popularity/torrentz.py
from providers.popularity.provider import PopularityProvider from utils.torrent_util import torrent_to_search_string, remove_bad_torrent_matches IDENTIFIER = "Torrentz" class Provider(PopularityProvider): PAGES_TO_FETCH = 1 def get_popular(self): results = [] for page in range(Provider.PAGES_TO_FETCH): terms = ["movies", "hd", "-xxx", "-porn"] url = "https://torrentz.eu/search?q=%s&p=%s" % ( "+".join(terms), page ) results += self.parse_html(url, ".results dt a") results = remove_bad_torrent_matches(results) results = [torrent_to_search_string(name) for name in results] return results
from providers.popularity.provider import PopularityProvider from utils.torrent_util import torrent_to_search_string, remove_bad_torrent_matches IDENTIFIER = "Torrentz" class Provider(PopularityProvider): PAGES_TO_FETCH = 1 def get_popular(self): results = [] for page in range(Provider.PAGES_TO_FETCH): terms = ["movies", "hd", "-xxx", "-porn"] url = "https://torrentz.eu/search?q=%s&p=%s" % ( "+".join(terms), page ) results += self.parse_html(url, ".results dt a") results = [torrent_to_search_string(name) for name in results] results = remove_bad_torrent_matches(results) return results
Remove bad torrents assumes torrent_to_search_string already ran.
Remove bad torrents assumes torrent_to_search_string already ran.
Python
mit
EmilStenstrom/nephele
--- +++ @@ -15,6 +15,6 @@ ) results += self.parse_html(url, ".results dt a") + results = [torrent_to_search_string(name) for name in results] results = remove_bad_torrent_matches(results) - results = [torrent_to_search_string(name) for name in results] return results
ddc44c6673cff4121eaaa47d8d075d63b82a85fe
runreport.py
runreport.py
import os import json import saulify.sitespec as sitespec SPEC_DIRECTORY = "sitespecs" if __name__ == "__main__": for fname in os.listdir(SPEC_DIRECTORY): fpath = os.path.join(SPEC_DIRECTORY, fname) test_cases = sitespec.load_testcases(fpath) for test_case in test_cases: result = test_case.run() print(json.dumps(result))
import os import json import argparse import saulify.sitespec as sitespec SPEC_DIRECTORY = "sitespecs" parser = argparse.ArgumentParser() parser.add_argument("-p", "--pretty", help="Pretty print test results", action="store_true") args = parser.parse_args() def test_passed(report): """ Whether all components of a scraper test succeeded """ if report["status"] != "OK": return False for result in report["result"].values(): if result["missing"]: return False return True def print_report(report): """ Converts test report dictionary to a human-readable format """ if report["status"] == "OK": result = "PASS" if test_passed(report) else "FAIL" else: result = "EXCEPTION" print("{0} : {1}".format(result, report["url"])) if report["status"] == "EXCEPTION": print(report["message"]) elif test_passed(report): r = report["result"] stats = ", ".join(["{0} {1}".format(len(r[c]["found"]), c) for c in r]) print("Found " + stats) else: for category, result in report["result"].items(): if result["missing"]: count = len(result["missing"]) print("Missing {0} {1}:".format(count, category)) for item in result["missing"]: print(item) if __name__ == "__main__": for fname in os.listdir(SPEC_DIRECTORY): fpath = os.path.join(SPEC_DIRECTORY, fname) test_cases = sitespec.load_testcases(fpath) for test_case in test_cases: report = test_case.run() if args.pretty: print_report(report) print("\n") else: print(json.dumps(report))
Add optional pretty printing to test runner
Add optional pretty printing to test runner
Python
agpl-3.0
asm-products/saulify-web,asm-products/saulify-web,asm-products/saulify-web
--- +++ @@ -1,9 +1,56 @@ import os import json +import argparse import saulify.sitespec as sitespec SPEC_DIRECTORY = "sitespecs" + + +parser = argparse.ArgumentParser() +parser.add_argument("-p", "--pretty", help="Pretty print test results", + action="store_true") +args = parser.parse_args() + + +def test_passed(report): + """ Whether all components of a scraper test succeeded """ + + if report["status"] != "OK": + return False + + for result in report["result"].values(): + if result["missing"]: + return False + + return True + + +def print_report(report): + """ Converts test report dictionary to a human-readable format """ + + if report["status"] == "OK": + result = "PASS" if test_passed(report) else "FAIL" + else: + result = "EXCEPTION" + + print("{0} : {1}".format(result, report["url"])) + + if report["status"] == "EXCEPTION": + print(report["message"]) + + elif test_passed(report): + r = report["result"] + stats = ", ".join(["{0} {1}".format(len(r[c]["found"]), c) for c in r]) + print("Found " + stats) + + else: + for category, result in report["result"].items(): + if result["missing"]: + count = len(result["missing"]) + print("Missing {0} {1}:".format(count, category)) + for item in result["missing"]: + print(item) if __name__ == "__main__": @@ -11,5 +58,9 @@ fpath = os.path.join(SPEC_DIRECTORY, fname) test_cases = sitespec.load_testcases(fpath) for test_case in test_cases: - result = test_case.run() - print(json.dumps(result)) + report = test_case.run() + if args.pretty: + print_report(report) + print("\n") + else: + print(json.dumps(report))
bd2c459b14103786f25aacf1daf3a7f23638df00
base/app/main.py
base/app/main.py
# test.py def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) #return [b"Hello World"] # python3 return ["Hello World from uwsgi-nginx:base"] # python2
# test.py def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) #return [b"Hello World"] # python3 return ["Hello World from default uWSGI app (default)"] # python2
Add '(default)' to sample app
Add '(default)' to sample app
Python
apache-2.0
tiangolo/uwsgi-nginx-docker,tiangolo/uwsgi-nginx-docker
--- +++ @@ -2,4 +2,4 @@ def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) #return [b"Hello World"] # python3 - return ["Hello World from uwsgi-nginx:base"] # python2 + return ["Hello World from default uWSGI app (default)"] # python2
afcb007c7c8b68bc4cace5ff6d634330f70603ec
channels/management/commands/runworker.py
channels/management/commands/runworker.py
from django.core.management import BaseCommand, CommandError from channels import DEFAULT_CHANNEL_LAYER from channels.layers import get_channel_layer from channels.log import setup_logger from channels.routing import get_default_application from channels.worker import Worker class Command(BaseCommand): leave_locale_alone = True def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( "--layer", action="store", dest="layer", default=DEFAULT_CHANNEL_LAYER, help="Channel layer alias to use, if not the default.", ) parser.add_argument( "channels", nargs="+", help="Channels to listen on." ) def handle(self, *args, **options): # Get the backend to use self.verbosity = options.get("verbosity", 1) # Get the channel layer they asked for (or see if one isn't configured) if "layer" in options: self.channel_layer = get_channel_layer(options["layer"]) else: self.channel_layer = get_channel_layer() if self.channel_layer is None: raise CommandError("You do not have any CHANNEL_LAYERS configured.") # Run the worker self.logger = setup_logger("django.channels", self.verbosity) self.logger.info("Running worker for channels %s", options["channels"]) worker = Worker( application=get_default_application(), channels=options["channels"], channel_layer=self.channel_layer, ) worker.run()
from django.core.management import BaseCommand, CommandError from channels import DEFAULT_CHANNEL_LAYER from channels.layers import get_channel_layer from channels.log import setup_logger from channels.routing import get_default_application from channels.worker import Worker class Command(BaseCommand): leave_locale_alone = True worker_class = Worker def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( "--layer", action="store", dest="layer", default=DEFAULT_CHANNEL_LAYER, help="Channel layer alias to use, if not the default.", ) parser.add_argument( "channels", nargs="+", help="Channels to listen on." ) def handle(self, *args, **options): # Get the backend to use self.verbosity = options.get("verbosity", 1) # Get the channel layer they asked for (or see if one isn't configured) if "layer" in options: self.channel_layer = get_channel_layer(options["layer"]) else: self.channel_layer = get_channel_layer() if self.channel_layer is None: raise CommandError("You do not have any CHANNEL_LAYERS configured.") # Run the worker self.logger = setup_logger("django.channels", self.verbosity) self.logger.info("Running worker for channels %s", options["channels"]) worker = self.worker_class( application=get_default_application(), channels=options["channels"], channel_layer=self.channel_layer, ) worker.run()
Allow subclasses to customise the worker class
Allow subclasses to customise the worker class
Python
bsd-3-clause
django/channels,andrewgodwin/django-channels,andrewgodwin/channels
--- +++ @@ -10,6 +10,7 @@ class Command(BaseCommand): leave_locale_alone = True + worker_class = Worker def add_arguments(self, parser): super(Command, self).add_arguments(parser) @@ -36,7 +37,7 @@ # Run the worker self.logger = setup_logger("django.channels", self.verbosity) self.logger.info("Running worker for channels %s", options["channels"]) - worker = Worker( + worker = self.worker_class( application=get_default_application(), channels=options["channels"], channel_layer=self.channel_layer,
d220f56a72a6481b33e7c75acf2f92bb89c17561
app/utils/html.py
app/utils/html.py
from typing import Iterable, Tuple def gallery(samples: Iterable[Tuple[str, str]], *, refresh: bool = False) -> str: lines = [] for url, template in samples: if refresh: url += "?time=0" lines.append( f""" <a href="{template or url}"> <img src="{url}" width="500" style="padding: 5px;"> </a> """ ) if refresh: lines.append( r""" <script> setInterval(function() { var images = document.images; for (var i=0; i<images.length; i++) { images[i].src = images[i].src.replace( /\btime=[^&]*/, 'time=' + new Date().getTime() ); } }, 2000); </script> """ ) return "\n".join(lines).replace("\n" + " " * 12, "\n")
from typing import Iterable, Tuple def gallery(samples: Iterable[Tuple[str, str]], *, refresh: bool = False) -> str: lines = [] for url, template in samples: if refresh: url += "?time=0" else: url += "?width=300&height=300" lines.append( f""" <a href="{template or url}"> <img src="{url}" style="padding: 5px;"> </a> """ ) if refresh: lines.append( r""" <script> setInterval(function() { var images = document.images; for (var i=0; i<images.length; i++) { images[i].src = images[i].src.replace( /\btime=[^&]*/, 'time=' + new Date().getTime() ); } }, 2000); </script> """ ) return "\n".join(lines).replace("\n" + " " * 12, "\n")
Use padding on the index
Use padding on the index
Python
mit
jacebrowning/memegen,jacebrowning/memegen
--- +++ @@ -7,10 +7,12 @@ for url, template in samples: if refresh: url += "?time=0" + else: + url += "?width=300&height=300" lines.append( f""" <a href="{template or url}"> - <img src="{url}" width="500" style="padding: 5px;"> + <img src="{url}" style="padding: 5px;"> </a> """ )
deb70e977ad59a84fbafe2251f60f2da1d4abf20
astral/api/app.py
astral/api/app.py
#!/usr/bin/env python import threading import tornado.httpserver import tornado.ioloop import tornado.web from astral.conf import settings from urls import url_patterns class NodeWebAPI(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns, **settings.TORNADO_SETTINGS) def run(): from astral.api.handlers.events import queue_listener event_thread = threading.Thread(target=queue_listener) event_thread.daemon = True event_thread.start() app = NodeWebAPI() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(settings.TORNADO_SETTINGS['port']) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
#!/usr/bin/env python import threading import tornado.httpserver import tornado.ioloop import tornado.web from astral.conf import settings from urls import url_patterns class NodeWebAPI(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns, **settings.TORNADO_SETTINGS) def run(): from astral.api.handlers.events import queue_listener event_thread = threading.Thread(target=queue_listener) event_thread.daemon = True event_thread.start() app = NodeWebAPI() app.listen(settings.TORNADO_SETTINGS['port']) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
Use shortcut listen() for starting the HTTPServer.
Use shortcut listen() for starting the HTTPServer.
Python
mit
peplin/astral
--- +++ @@ -21,8 +21,7 @@ event_thread.start() app = NodeWebAPI() - http_server = tornado.httpserver.HTTPServer(app) - http_server.listen(settings.TORNADO_SETTINGS['port']) + app.listen(settings.TORNADO_SETTINGS['port']) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__":
06ae3ea593d4af5379307c2383e113000883db45
gooey/gui/application.py
gooey/gui/application.py
''' Main runner entry point for Gooey. ''' import wx # wx.html and wx.xml imports required here to make packaging with # pyinstaller on OSX possible without manually specifying `hidden_imports` # in the build.spec import wx.html import wx.xml import wx.richtext # Need to be imported before the wx.App object is created. import wx.lib.inspection from gooey.gui.lang import i18n from gooey.gui import image_repository from gooey.gui.containers.application import GooeyApplication from gooey.util.functional import merge def run(build_spec): app, _ = build_app(build_spec) app.MainLoop() def build_app(build_spec): app = wx.App(False) i18n.load(build_spec['language_dir'], build_spec['language'], build_spec['encoding']) imagesPaths = image_repository.loadImages(build_spec['image_dir']) gapp = GooeyApplication(merge(build_spec, imagesPaths)) gapp.Show() return (app, gapp)
''' Main runner entry point for Gooey. ''' import wx # wx.html and wx.xml imports required here to make packaging with # pyinstaller on OSX possible without manually specifying `hidden_imports` # in the build.spec import wx.html import wx.xml import wx.richtext # Need to be imported before the wx.App object is created. import wx.lib.inspection from gooey.gui.lang import i18n from gooey.gui import image_repository from gooey.gui.containers.application import GooeyApplication from gooey.util.functional import merge def run(build_spec): app, _ = build_app(build_spec) app.MainLoop() def build_app(build_spec): app = wx.App(False) # use actual program name instead of script file name in macOS menu app.SetAppDisplayName(build_spec['program_name']) i18n.load(build_spec['language_dir'], build_spec['language'], build_spec['encoding']) imagesPaths = image_repository.loadImages(build_spec['image_dir']) gapp = GooeyApplication(merge(build_spec, imagesPaths)) gapp.Show() return (app, gapp)
Use program_name instead of script file name in macOS menu
Use program_name instead of script file name in macOS menu
Python
mit
chriskiehl/Gooey
--- +++ @@ -24,6 +24,8 @@ def build_app(build_spec): app = wx.App(False) + # use actual program name instead of script file name in macOS menu + app.SetAppDisplayName(build_spec['program_name']) i18n.load(build_spec['language_dir'], build_spec['language'], build_spec['encoding']) imagesPaths = image_repository.loadImages(build_spec['image_dir'])
2e730cee505f70f0d0dad5deea417a8b9ed892d9
run_all_tests.py
run_all_tests.py
#!/usr/bin/env python """Gathers all tests in the /tests/ subdirectory and runs them.""" import os import unittest def main(): test_loader = unittest.TestLoader() tests_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tests') test_suite = test_loader.discover(tests_dir, '*.py') test_runner = unittest.TextTestRunner() test_runner.run(test_suite) if __name__ == '__main__': main()
Add a test runner that will execute all the tests in /tests/
Add a test runner that will execute all the tests in /tests/
Python
mit
mrhappyasthma/HappyDebugging,mrhappyasthma/happydebugging
--- +++ @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +"""Gathers all tests in the /tests/ subdirectory and runs them.""" +import os +import unittest + + +def main(): + test_loader = unittest.TestLoader() + tests_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tests') + test_suite = test_loader.discover(tests_dir, '*.py') + test_runner = unittest.TextTestRunner() + test_runner.run(test_suite) + + +if __name__ == '__main__': + main()
ce41f12aebfec5412c0bb9a4fb9a550b8be951a8
hoomd/update/__init__.py
hoomd/update/__init__.py
from hoomd.update.box_resize import BoxResize # TODO remove when no longer necessary class _updater: pass
from hoomd.update.box_resize import BoxResize # TODO remove when no longer necessary class _updater: pass __all__ = [BoxResize]
Add an __all__ variable to hoomd.upate module
Add an __all__ variable to hoomd.upate module
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
--- +++ @@ -4,3 +4,6 @@ # TODO remove when no longer necessary class _updater: pass + + +__all__ = [BoxResize]
93725280614984955cc8ac4fac74b90e6b5b4076
radio/__init__.py
radio/__init__.py
import logging from django.utils.version import get_version from subprocess import check_output, CalledProcessError logger = logging.getLogger(__name__) VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) logger.error('Trunk-Player Version ' + __fullversion__)
import logging from django.utils.version import get_version from subprocess import check_output, CalledProcessError logger = logging.getLogger(__name__) VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) logger.info('Trunk-Player Version ' + __fullversion__)
Change version from error to info
Change version from error to info
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
--- +++ @@ -17,4 +17,4 @@ __fullversion__ = '{} #{}'.format(__version__,__git_hash__) -logger.error('Trunk-Player Version ' + __fullversion__) +logger.info('Trunk-Player Version ' + __fullversion__)
ad888e5c5423fcb2419c497597990868216edfe3
pubrunner/__init__.py
pubrunner/__init__.py
from pubrunner.command_line import * from pubrunner.upload import * from pubrunner.FTPClient import * from pubrunner.getresource import * from pubrunner.pubrun import pubrun,cleanWorkingDirectory from pubrunner.convert import * def loadYAML(yamlFilename): yamlData = None with open(yamlFilename,'r') as f: try: yamlData = yaml.load(f) except yaml.YAMLError as exc: print(exc) raise return yamlData def findSettingsFile(): possibilities = [ os.getcwd(), os.path.expanduser("~") ] for directory in possibilities: settingsPath = os.path.join(directory,'.pubrunner.settings.yml') if os.path.isfile(settingsPath): return settingsPath raise RuntimeError("Unable to find .pubrunner.settings.yml file. Tried current directory first, then home directory") globalSettings = None def getGlobalSettings(): global globalSettings if globalSettings is None: settingsYamlFile = findSettingsFile() globalSettings = loadYAML(settingsYamlFile) return globalSettings
from pubrunner.command_line import * from pubrunner.upload import * from pubrunner.FTPClient import * from pubrunner.getresource import * from pubrunner.pubrun import pubrun,cleanWorkingDirectory from pubrunner.convert import * from pubrunner.pubmed_hash import pubmed_hash def loadYAML(yamlFilename): yamlData = None with open(yamlFilename,'r') as f: try: yamlData = yaml.load(f) except yaml.YAMLError as exc: print(exc) raise return yamlData def findSettingsFile(): possibilities = [ os.getcwd(), os.path.expanduser("~") ] for directory in possibilities: settingsPath = os.path.join(directory,'.pubrunner.settings.yml') if os.path.isfile(settingsPath): return settingsPath raise RuntimeError("Unable to find .pubrunner.settings.yml file. Tried current directory first, then home directory") globalSettings = None def getGlobalSettings(): global globalSettings if globalSettings is None: settingsYamlFile = findSettingsFile() globalSettings = loadYAML(settingsYamlFile) return globalSettings
Make pubmed hash accessible to API
Make pubmed hash accessible to API
Python
mit
jakelever/pubrunner,jakelever/pubrunner
--- +++ @@ -5,6 +5,7 @@ from pubrunner.getresource import * from pubrunner.pubrun import pubrun,cleanWorkingDirectory from pubrunner.convert import * +from pubrunner.pubmed_hash import pubmed_hash def loadYAML(yamlFilename): yamlData = None
74d0e710711f1b499ab32784b751adc55e8b7f00
python/bonetrousle.py
python/bonetrousle.py
#!/bin/python3 import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased def minimumValue(k, b): return 0 # The maximum number of sticks that may be purchased def maximumValue(k, b): return 100 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
#!/bin/python3 import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased # Equivalant to: 1 + 2 + 3 ... b # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def minimumValue(k, b): return b * (1 + b) / 2 # The maximum number of sticks that may be purchased # Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def maximumValue(k, b): return b * ((k - b + 1) + k) / 2 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
Implement minimum and maximum values
Implement minimum and maximum values
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
--- +++ @@ -13,12 +13,16 @@ return -1 # The minimum number of sticks that may be purchased +# Equivalant to: 1 + 2 + 3 ... b +# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def minimumValue(k, b): - return 0 + return b * (1 + b) / 2 # The maximum number of sticks that may be purchased +# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k +# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def maximumValue(k, b): - return 100 + return b * ((k - b + 1) + k) / 2 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b):
7aa89902f8af2ca1f4b3c9e356a62062cc74696b
bot/anime_searcher.py
bot/anime_searcher.py
from itertools import chain from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) cached_data, cached_id = await self.__get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: res, id_ = await self.__get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: return_val[site] = res for title in get_synonyms(res, site): names.append(title) if id_: to_be_cached[site] = id_ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): """ Cache search results into the db. :param to_be_cached: items to be cached. :param names: all names for the item. :param medium: the medium type. """ itere = set(chain(*names)) for site, id_ in to_be_cached.items(): await self.cache_one(site, id_, medium, itere) async def cache_one(self, site, id_, medium, iterator): """ Cache one id. :param site: the site. :param id_: the id. :param medium: the medium type. :param iterator: an iterator for all names. """ for name in iterator: if name: await self.db_controller.set_identifier( name, medium, site, id_ )
from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) cached_data, cached_id = await self._get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: res, id_ = await self._get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: return_val[site] = res for title in get_synonyms(res, site): names.append(title) if id_: to_be_cached[site] = id_ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): await super()._cache(to_be_cached, names, medium)
Update anime searcher implementation to use super class methods
Update anime searcher implementation to use super class methods
Python
apache-2.0
MaT1g3R/YasenBaka
--- +++ @@ -1,4 +1,3 @@ -from itertools import chain from typing import Iterable from minoshiro import Medium, Minoshiro, Site @@ -9,12 +8,12 @@ async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) - cached_data, cached_id = await self.__get_cached(query, medium) + cached_data, cached_id = await self._get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: - res, id_ = await self.__get_result( + res, id_ = await self._get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: @@ -26,26 +25,4 @@ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): - """ - Cache search results into the db. - :param to_be_cached: items to be cached. - :param names: all names for the item. - :param medium: the medium type. - """ - itere = set(chain(*names)) - for site, id_ in to_be_cached.items(): - await self.cache_one(site, id_, medium, itere) - - async def cache_one(self, site, id_, medium, iterator): - """ - Cache one id. - :param site: the site. - :param id_: the id. - :param medium: the medium type. - :param iterator: an iterator for all names. - """ - for name in iterator: - if name: - await self.db_controller.set_identifier( - name, medium, site, id_ - ) + await super()._cache(to_be_cached, names, medium)