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 = de... | 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
Declara... | 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... |
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 ... | # -*- 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 ... | 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,kj... | ---
+++
@@ -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
... |
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
... | # -*- 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
... | 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_ALIA... | 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_U... | 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].c... |
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 o... | # -*- 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_queryse... | 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.Man... |
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.... | 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.... | 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', 'PYTHONFRAMEWORKPRE... | 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', '... | 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 (... |
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_requirem... | #!/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']
... | 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=... |
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://cose... | 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-acb... | 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.qu... | #!/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.qu... | 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 red... | 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 re... | 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 con... | #!/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 = [... | 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_challen... |
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'
... | """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 no... | 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)
+
... |
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_f... |
"""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_f... | 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_ra... |
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):
... | 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... | 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).upd... |
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_ti... | 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 = []... | 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(... |
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': ['Payme... | 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,
tha... | # 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,
tha... | 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,... |
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_no... | 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 = p... |
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_... | 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'
... | 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_r... |
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... | #!/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)
... | 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 ... | 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 ren... | 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... | ---
+++
@@ -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 .serializ... |
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.Even... | 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 ... | 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), ... |
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.connect... | 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.connec... | 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()... |
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... | 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... |
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()
... | 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()
... | 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.c... |
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 ... | # 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 ... | 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(H5pyDeprecati... |
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(p... | #!/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(p... | 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.CalledP... |
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... | 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... | 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.mac... |
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:
... | #!/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.... | 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_... | 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_... | 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.u... |
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, manag... | 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, ... | 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, cont... |
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'),
... | 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_secre... |
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)
>>> sin... |
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... | 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... | 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)
+ ret... |
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.n... | # -*- 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.n... | 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, p... | # -*- 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, p... | 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,
... | 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': ... | |
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',
... | #!/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',
... | 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... |
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... | #
# 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... | 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... | # 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... | 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 ... |
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
... | #! -*- 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
... | 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... |
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
... | 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
... | 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()... | 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:
+ ... |
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):
... | 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 xr... | 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,kd... | ---
+++
@@ -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 .tr... | # -*- 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 ... | 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 .deleti... |
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... | 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.... | 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 obje... | """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__... | 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 re... |
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)
# -----------------------------------------------------------------------------
"""Spyde... | 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)
+# ------------------------------------------------------... |
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]': 'Foob... | # 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 = {
'use... | 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 ... |
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(fulle... | 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(fulle... | 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""... | #!/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""... | 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 loc... | 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 loc... | 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 SIG... |
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, e... | 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 ... | 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'].configur... |
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... | 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.spli... | 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.AUT... |
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_titl... | 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... | 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... |
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 processin... | #!/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 processin... | 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',
+ '... |
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',
... | 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',
... | 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'... |
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.getLog... | """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_... | 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... |
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', '... | 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 ... | 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... |
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 imp... |
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 imp... | 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):
... |
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"))
... | 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"))
... | 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.rep... |
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_stre... | 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(jso... | 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.startswit... |
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_Q... | 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_Q... | 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 de... |
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']:
... | 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']:
... | 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(Workgr... | 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(Workgr... | 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
e... | # -*- 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'
clea... | 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-datat... | ---
+++
@@ -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_setting... |
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
_recorde... | 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
_recorde... | 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):
- r... |
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,
... | 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/sci... | ---
+++
@@ -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_fil... |
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... | 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... | 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' ... |
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):
... | # 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):
... | 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,kambyse... | ---
+++
@@ -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')]
+ ... |
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):
... | 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.i... |
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'... | 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)
sel... | 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/mopi... | ---
+++
@@ -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_USE... |
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 = pa... | """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, _):
r... | 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 t... | #!/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 app... | 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/e... | ---
+++
@@ -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... |
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... | # 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... | 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... | ---
+++
@@ -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())
@... |
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/'... | 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/'... | 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 ... | import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms ... | 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 re... |
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_... | 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_... | 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]
retur... |
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:
resu... | 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):
""" Whe... | 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(... |
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_lo... | 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_lo... | 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.verbosi... |
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 s... | 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"""
... | 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: 5p... |
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,
**se... | #!/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,
**se... | 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... | '''
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... | 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_r... |
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 = ... | 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.discov... | |
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()
... | 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()
... | 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:
... |
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... | 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
... | #!/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
... | 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 pur... |
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 ... | 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)
... | 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)
- ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.