commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
f114e5ecf62a5a08c22e1db23e891abe066b61f8
oneflow/core/forms.py
oneflow/core/forms.py
# -*- coding: utf-8 -*- import logging #from django import forms #from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model LOGGER = logging.getLogger(__name__) User = get_user_model() class FullUserCreationForm(Use...
# -*- coding: utf-8 -*- import logging from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model LOGGER = logging.getLogger(__name__) User = get_user_model() class FullUserCreationForm(forms.ModelForm): """ Like the django UserCreationForm, ...
Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.
Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.
Python
agpl-3.0
1flow/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow
c684dbb999ac622d5bba266d39e2dd7e69265393
yunity/api/utils.py
yunity/api/utils.py
from django.http import JsonResponse class ApiBase(object): STATUS_ERROR = 0 STATUS_SUCCESS = 1 STATUS_WARNING = 2 def json_response(self, data=None, status=STATUS_SUCCESS, message=None): status_code = 400 if status == ApiBase.STATUS_ERROR else 200 return JsonResponse({ ...
from django.http import JsonResponse class ApiBase(object): @classmethod def success(cls, data, status=200): """ :type data: dict :type status: int :rtype JsonResponse """ return JsonResponse(data, status=status) @classmethod def error(cls, error, stat...
Refactor json_response to more BDD methods
Refactor json_response to more BDD methods
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend
dbb223d64d1058e34c35867dcca2665766d0edbf
synapse/tests/test_config.py
synapse/tests/test_config.py
from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) ...
from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) ...
Update test to ensure that default configuration values are available via getConfOpt
Update test to ensure that default configuration values are available via getConfOpt
Python
apache-2.0
vertexproject/synapse,vertexproject/synapse,vertexproject/synapse,vivisect/synapse
876cfd11bf57101ca7774e0f003855ab7603bfba
dh/thirdparty/__init__.py
dh/thirdparty/__init__.py
""" Third-party modules which are essential and must always available. For maximum compatibility, these modules should be pure Python without non-standard dependencies. List of current modules: * atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites) * colorama-0.3.9 (https://github.com/tartley/co...
""" Third-party modules which are essential and must always available. For maximum compatibility, these modules should be pure Python without non-standard dependencies. List of current modules: * atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites) * colorama-0.3.9 (https://github.com/tartley/co...
Remove package transitions in documentation
Remove package transitions in documentation
Python
mit
dhaase-de/dh-python-dh,dhaase-de/dh-python-dh
62b177e0a0fd7adbabe72d04befff566f05e9a74
scudcloud/notifier.py
scudcloud/notifier.py
from dbus.exceptions import DBusException try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify except (ImportError, AttributeError): from scudcloud import notify2 Notify = None class Notifier(object): def __init__(self, app_name, icon): self.icon = icon ...
from dbus.exceptions import DBusException try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify except (ImportError, AttributeError, ValueError): from scudcloud import notify2 Notify = None class Notifier(object): def __init__(self, app_name, icon): self.i...
Allow ValueError as a notify exception
Allow ValueError as a notify exception
Python
mit
raelgc/scudcloud,raelgc/scudcloud,raelgc/scudcloud
c8429ec00772455c981ebb799f0c87de55bda64e
django_fixmystreet/backoffice/forms.py
django_fixmystreet/backoffice/forms.py
from django import forms from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy from django.contrib.sessions.models import Session class ManagersChoiceField (forms.field...
from django import forms from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy from django.contrib.sessions.models import Session from django.contrib.auth.decorators imp...
Fix user not defined error for not logged in users
Fix user not defined error for not logged in users
Python
agpl-3.0
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
87b6f69fe53e0425dd5321fcecb613f31887c746
recipyCommon/libraryversions.py
recipyCommon/libraryversions.py
import sys import warnings def get_version(modulename): "Return a string containing the module name and the library version." version = '?' # Get the root module name (in case we have something like `recipy.open` # or `matplotlib.pyplot`) modulename = modulename.split('.')[0] if modulename i...
import sys import warnings def get_version(modulename): "Return a string containing the module name and the library version." version = '?' # Get the root module name (in case we have something like `recipy.open` # or `matplotlib.pyplot`) modulename = modulename.split('.')[0] if modulename i...
Add explicit (rather than broad/general) exceptions in get_version
Add explicit (rather than broad/general) exceptions in get_version
Python
apache-2.0
recipy/recipy,recipy/recipy
f9f9f385e4f425da0537680ba6afd2ce81bfb774
rembed/test/integration_test.py
rembed/test/integration_test.py
from hamcrest import * import pytest @pytest.mark.xfail def test_should_get_correct_embedding(): consumer = REmbedConsumer() embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744') assert_that(embedding, contains_string('Four more years.'))
from rembed import consumer from hamcrest import * import pytest @pytest.mark.xfail def test_should_get_correct_embedding(): embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744') assert_that(embedding, contains_string('Four more years.'))
Fix import in integration test
Fix import in integration test
Python
mit
tino/pyembed,pyembed/pyembed,pyembed/pyembed
7278be28410c111280d4ccb566842419979843d3
mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py
mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py
import random from django.core.management.base import BaseCommand from django.contrib.auth.models import User from mla_game.apps.accounts.models import Profile from ...models import ( Transcript, TranscriptPhraseDownvote ) class Command(BaseCommand): help = 'Creates random votes for 5 phrases in a random t...
import random from django.core.management.base import BaseCommand from django.contrib.auth.models import User from mla_game.apps.accounts.models import Profile from ...models import ( Transcript, TranscriptPhraseDownvote ) from ...tasks import update_transcript_stats class Command(BaseCommand): help = 'Cre...
Use an actually random transcript; update stats immediately
Use an actually random transcript; update stats immediately
Python
mit
WGBH/FixIt,WGBH/FixIt,WGBH/FixIt
80b05e0cd3d73529d37843d398857289d5717e44
wagtail/tests/migrations/0005_auto_20141113_0642.py
wagtail/tests/migrations/0005_auto_20141113_0642.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tests', '0004_auto_20141008_0420'), ] operations = [ migrations.AlterField( model_name='formfield', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0002_initial_data'), ('tests', '0004_auto_20141008_0420'), ] operations = [ migrations.AlterField( ...
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)
Python
bsd-3-clause
rsalmaso/wagtail,mikedingjan/wagtail,Toshakins/wagtail,dresiu/wagtail,nilnvoid/wagtail,iansprice/wagtail,kurtw/wagtail,takeflight/wagtail,thenewguy/wagtail,dresiu/wagtail,nutztherookie/wagtail,thenewguy/wagtail,mikedingjan/wagtail,mixxorz/wagtail,takeflight/wagtail,torchbox/wagtail,JoshBarr/wagtail,nealtodd/wagtail,jor...
79928051b481f9e19b45c8eebcf8ae2ff229b342
opps/boxes/models.py
opps/boxes/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #from django.conf import settings #from django.utils.importlib import import_module from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable, BaseBox """ from django.db.models import get_model model = g...
#!/usr/bin/env python # -*- coding: utf-8 -*- #from django.conf import settings #from django.utils.importlib import import_module from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable, BaseBox try: OPPS_APPS = tuple([(u"{0}.{1}".format( ...
Fix OPPS_APPS, get object_name in dropdawn
Fix OPPS_APPS, get object_name in dropdawn
Python
mit
YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps
8f36430e6fc17485b422ed5e620de4b156101623
polyaxon_client/stores/stores/local_store.py
polyaxon_client/stores/stores/local_store.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import Store class LocalStore(Store): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pylint:disa...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import BaseStore class LocalStore(BaseStore): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pyl...
Update local store base class
Update local store base class
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
7048366af948773b6badfb1f3611f9e4c694e810
code/dataplot.py
code/dataplot.py
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def loadCudaStream(name): """ reads the file specified by name into a numpy array (and removes the superfluous fourth bit from cuda's float4) np.shape(data)=(N,3) where N is the length of a streamline...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def loadCudaStream(name): """ reads the file specified by name into a numpy array (and removes the superfluous fourth bit from cuda's float4) np.shape(data)=(N,3) where N is the length of a streamline...
Create commandline options for the clampval
Create commandline options for the clampval
Python
mit
TAdeJong/plasma-analysis,TAdeJong/plasma-analysis
a3a34026369391837d31d7424e78de207b98340d
preferences/views.py
preferences/views.py
from django.shortcuts import render from django.db import transaction # from django.views.generic import TemplateView from registration.forms import RegistrationFormUniqueEmail from registration.backends.default.views import RegistrationView from preferences.models import PersonFollow from opencivicdata.models.peopl...
from django.shortcuts import render from django.db import transaction # from django.views.generic import TemplateView from tot.utils import get_current_people from registration.forms import RegistrationFormUniqueEmail from registration.backends.default.views import RegistrationView from preferences.models import Per...
Use new util function for getting current people
Use new util function for getting current people
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
21858e2137d3b15089c5d036cd99d4a3be4e3dbe
python/sanitytest.py
python/sanitytest.py
#!/usr/bin/python import libvirt globals = dir(libvirt) # Sanity test that the generator hasn't gone wrong # Look for core classes assert("virConnect" in globals) assert("virDomain" in globals) assert("virDomainSnapshot" in globals) assert("virInterface" in globals) assert("virNWFilter" in globals) assert("virNodeD...
#!/usr/bin/python import libvirt globals = dir(libvirt) # Sanity test that the generator hasn't gone wrong # Look for core classes for clsname in ["virConnect", "virDomain", "virDomainSnapshot", "virInterface", "virNWFilter", "virNodeDe...
Check if classes are derived from object
Check if classes are derived from object This makes sure we don't regress to old style classes
Python
lgpl-2.1
trainstack/libvirt,siboulet/libvirt-openvz,elmarco/libvirt,crobinso/libvirt,eskultety/libvirt,crobinso/libvirt,shugaoye/libvirt,libvirt/libvirt,fabianfreyer/libvirt,iam-TJ/libvirt,eskultety/libvirt,olafhering/libvirt,shugaoye/libvirt,shugaoye/libvirt,rlaager/libvirt,cbosdo/libvirt,rlaager/libvirt,nertpinx/libvirt,andre...
d4cb09e9ffa645c97976c524a3d084172f091a16
p560m/subarray_sum.py
p560m/subarray_sum.py
from typing import List from collections import defaultdict class Solution: def subarraySum(self, nums: List[int], k: int) -> int: sum_count = defaultdict(int) sum_count[0] = 1 s, ans = 0, 0 for n in nums: s += n if s - k in sum_count: ans +=...
from typing import List from collections import defaultdict class Solution: def subarraySum(self, nums: List[int], k: int) -> int: sum_count = defaultdict(int) sum_count[0] = 1 s, ans = 0, 0 for n in nums: s += n ans += sum_count[s - k] sum_count...
Update p560m subarray sum in Python
Update p560m subarray sum in Python
Python
mit
l33tdaima/l33tdaima,l33tdaima/l33tdaima,l33tdaima/l33tdaima,l33tdaima/l33tdaima,l33tdaima/l33tdaima
ffd39111a7b76e2cdec4e27501d0f5bfaba269d9
actor/app_logging.py
actor/app_logging.py
import errno import os import logging def _mkdir_p(path): try: os.mkdir(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def log_file_handler(app_name, log_level, log_dir): app_log_dir = os.path.join(log_d...
import errno import os import logging def _mkdir_p(path): ab_path = path if not os.path.isabs(ab_path): curr_dir = os.getcwd() ab_path = os.path.join(curr_dir, path) try: os.makedirs(ab_path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(ab_path)...
Fix logging bug: mkdir -> makedirs.
Fix logging bug: mkdir -> makedirs.
Python
mit
cqumirrors/actor
9877bf47e3cd11070bac6377ea734ca20ff364ba
testing/python/setup_plan.py
testing/python/setup_plan.py
def test_show_fixtures_and_test(testdir): p = testdir.makepyfile(''' import pytest @pytest.fixture def arg(): assert False def test_arg(arg): assert False ''') result = testdir.runpytest("--setup-plan", p) assert result.ret == 0 result.stdout...
def test_show_fixtures_and_test(testdir): """ Verifies that fixtures are not executed. """ p = testdir.makepyfile(''' import pytest @pytest.fixture def arg(): assert False def test_arg(arg): assert False ''') result = testdir.runpytest("--setup-pl...
Improve commenting for setupplan unittest.
Improve commenting for setupplan unittest.
Python
mit
etataurov/pytest,pytest-dev/pytest,hpk42/pytest,skylarjhdownes/pytest,rmfitzpatrick/pytest,jaraco/pytest,MichaelAquilina/pytest,tomviner/pytest,ddboline/pytest,Akasurde/pytest,nicoddemus/pytest,The-Compiler/pytest,tgoodlet/pytest,hackebrot/pytest,nicoddemus/pytest,tareqalayan/pytest,txomon/pytest,eli-b/pytest,markshao/...
87f44bb68af64f2654c68fb60bf93a34ac6095a6
pylearn2/scripts/dbm/dbm_metrics.py
pylearn2/scripts/dbm/dbm_metrics.py
#!/usr/bin/env python import argparse if __name__ == '__main__': # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=["ais"]) parser.add_argument("model_path", help="path to the pickled DBM model") args = par...
#!/usr/bin/env python import argparse from pylearn2.utils import serial def compute_ais(model): pass if __name__ == '__main__': # Possible metrics metrics = {'ais': compute_ais} # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", ...
Make the script recuperate the correct method
Make the script recuperate the correct method
Python
bsd-3-clause
fyffyt/pylearn2,daemonmaker/pylearn2,se4u/pylearn2,hyqneuron/pylearn2-maxsom,abergeron/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,w1kke/pylearn2,matrogers/pylearn2,TNick/pylearn2,msingh172/pylearn2,shiquanwang/pylearn2,pkainz/pylearn2,fishcorn/pylearn2,chrish42/pylearn,kose-y/pylearn2,Refefer/pylearn2,lunyang/pylearn2,...
31073969ed99dd6f57ff1959c050fd0f8f59f58c
tests/scipy_argrelextrema.py
tests/scipy_argrelextrema.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) # To get number of...
Add eg to get number of peaks
Add eg to get number of peaks
Python
mit
MonsieurV/py-findpeaks,MonsieurV/py-findpeaks
84062292b62d68a14981bcebf18c01feda26fb01
src/plotter/comparison_plotter.py
src/plotter/comparison_plotter.py
#!/usr/bin/env python import matplotlib.pyplot as plt from .constants import PLOT class ComparisonPlotter: def __init__(self, data_list): self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) self.position_fig, self.position_plot = plt.subplots(2, 1, sharex=True) self.position_er...
#!/usr/bin/env python import matplotlib.pyplot as plt from .plotter import Plotter from .constants import PLOT class ComparisonPlotter(Plotter): def __init__(self, data_list): temp_data = data_list[0] Plotter.__init__(self, temp_data['t'], temp_data['zeros']) self.trajectory_fig, self.tr...
Make class ComparisonPlotter inherit from Plotter
feat: Make class ComparisonPlotter inherit from Plotter
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
4c0d88fe4d3fb935c5040fa39c5db10f74e6908f
pinax/stripe/utils.py
pinax/stripe/utils.py
import datetime import decimal from django.utils import timezone def convert_tstamp(response, field_name=None): try: if field_name and response[field_name]: return datetime.datetime.fromtimestamp( response[field_name], timezone.utc ) if not ...
import datetime import decimal from django.utils import timezone def convert_tstamp(response, field_name=None): try: if field_name and response[field_name]: return datetime.datetime.fromtimestamp( response[field_name], timezone.utc ) if resp...
Handle case when response is None
Handle case when response is None
Python
mit
pinax/django-stripe-payments
a7ba6ece76e768e642a6ed264791e3987f7c7629
apps/user_app/forms.py
apps/user_app/forms.py
from django import forms from django.core import validators from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): username = forms.CharField(label='username', max_length=30, required=True,) #validators=[self.isValidU...
from django import forms from django.core.exceptions import ValidationError from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm def isValidUserName(username): try: User.objects.get(username=username) except User.DoesNotExist: return raise ValidationError('The usern...
Implement validation to the username field.
Implement validation to the username field.
Python
mit
pedrolinhares/po-po-modoro,pedrolinhares/po-po-modoro
5553481f8cc8537febbf24fbfea4315a3b61548f
corehq/apps/commtrack/management/commands/check_multiple_parentage.py
corehq/apps/commtrack/management/commands/check_multiple_parentage.py
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write("Populating site codes...\n") domains = Domain.get_all() for d in domains: if d.commtrack_enabled...
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from corehq.apps.locations.models import Location import csv class Command(BaseCommand): def handle(self, *args, **options): with open('parentage_results.csv', 'wb+') as csvfile: csv_writer = csv.w...
Switch to CSV and add important info
Switch to CSV and add important info
Python
bsd-3-clause
puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/com...
adb0bffd6586fa380a077f1ec0b950c6ae5d8b4f
bin/reporting-api.py
bin/reporting-api.py
#!/usr/bin/python """ Start the Reporting API application using Paste Deploy. """ import sys import os from paste.deploy import loadapp, loadserver import logging import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-c', '--confdir', action='store', required=True, help="S...
#!/usr/bin/python """ Start the Reporting API application using Paste Deploy. """ import sys import os from paste.deploy import loadapp, loadserver import logging import argparse def parse_args(): REALFILE = os.path.realpath(__file__) REALDIR = os.path.dirname(REALFILE) PARDIR = os.path.realpath(os.path....
Make the confdir option optional, with default value the conf subdir in the source tree. Wrap long lines. Add a -l alias for option --logfile.
Make the confdir option optional, with default value the conf subdir in the source tree. Wrap long lines. Add a -l alias for option --logfile.
Python
apache-2.0
NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api,NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api
e3db38f0de04ab3e1126f3417fcdd99ab7d2e81c
flask_ldap_login/check.py
flask_ldap_login/check.py
""" Check that application ldap creds are set up correctly. """ from argparse import ArgumentParser from pprint import pprint from werkzeug.utils import import_string def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('app_module', metavar='APP_MODULE', ...
""" Check that application ldap creds are set up correctly. """ from argparse import ArgumentParser from pprint import pprint import getpass from werkzeug.utils import import_string def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('app_module', metavar='APP...
Use getpass to get password
Use getpass to get password
Python
bsd-2-clause
ContinuumIO/flask-ldap-login,ContinuumIO/flask-ldap-login
1d74ba63dda5193a5287a45c9570a7c2ece6fb42
moksha/apps/metrics/moksha/apps/metrics/consumers/metrics_consumer.py
moksha/apps/metrics/moksha/apps/metrics/consumers/metrics_consumer.py
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ...
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ...
Fix the data format of our metrics consumer
Fix the data format of our metrics consumer
Python
apache-2.0
mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha,lmacken/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha
c5d0595acb080bdc33efdc95a5781ed6b87b0a2e
warehouse/packages/models.py
warehouse/packages/models.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from sqlalchemy import event from sqlalchemy.schema import FetchedValue from sqlalchemy.dialects import postgresql as pg from warehouse import db from warehouse.databases.mixins import UUIDPrimaryKeyMixin fr...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from sqlalchemy.schema import FetchedValue from sqlalchemy.dialects import postgresql as pg from sqlalchemy.ext.declarative import declared_attr from warehouse import db from warehouse.database.mixins import...
Refactor Project to use new mixins and methods
Refactor Project to use new mixins and methods
Python
bsd-2-clause
davidfischer/warehouse
f44bd61809d2d965359ad4795b3839aa9a56bfec
src/sentry/monkey.py
src/sentry/monkey.py
from __future__ import absolute_import def register_scheme(name): from six.moves.urllib import parse as urlparse uses = urlparse.uses_netloc, urlparse.uses_query, urlparse.uses_relative, urlparse.uses_fragment for use in uses: if name not in use: use.append(name) register_scheme('app...
from __future__ import absolute_import def register_scheme(name): try: import urlparse # NOQA except ImportError: from urllib import parse as urlparse # NOQA uses = urlparse.uses_netloc, urlparse.uses_query, urlparse.uses_relative, urlparse.uses_fragment for use in uses: if n...
Remove six.moves and disable linter
Remove six.moves and disable linter
Python
bsd-3-clause
gencer/sentry,ifduyue/sentry,jean/sentry,looker/sentry,jean/sentry,gencer/sentry,mvaled/sentry,JamesMura/sentry,JamesMura/sentry,JamesMura/sentry,jean/sentry,BuildingLink/sentry,looker/sentry,looker/sentry,beeftornado/sentry,JackDanger/sentry,BuildingLink/sentry,JackDanger/sentry,jean/sentry,mvaled/sentry,beeftornado/s...
87a4c494c18039a296775dab8acf910f83fb59b8
djangoappengine/utils.py
djangoappengine/utils.py
from google.appengine.api import apiproxy_stub_map import os have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if have_appserver: appid = os.environ.get('APPLICATION_ID') else: try: from google.appengine.tools import dev_appserver from .boot import PROJECT_DIR a...
from google.appengine.api import apiproxy_stub_map import os have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if have_appserver: appid = os.environ.get('APPLICATION_ID') else: try: from google.appengine.tools import dev_appserver from .boot import PROJECT_DIR t...
Make prosthetic-runner work with GAE SDK 1.6
Make prosthetic-runner work with GAE SDK 1.6
Python
mit
philterphactory/prosthetic-runner,philterphactory/prosthetic-runner,philterphactory/prosthetic-runner
0e1c9c09bdf60fce3e9dbb8051db079687709fe0
blah/commands.py
blah/commands.py
import os import blah.repositories import blah.fetcher class WhatIsThisCommand(object): def create_parser(self, subparser): subparser.add_argument("directory", nargs="?") def execute(self, args): directory = args.directory if args.directory is not None else os.getcwd() repository ...
import os import argparse import blah.repositories import blah.fetcher class WhatIsThisCommand(object): def create_parser(self, subparser): subparser.add_argument("directory", nargs="?") def execute(self, args): directory = args.directory if args.directory is not None else os.getcwd() ...
Fix and hide --use-cache option
Fix and hide --use-cache option
Python
bsd-2-clause
mwilliamson/mayo
59e454f0272725c46d06f3d5f32edafa866f578b
registration/admin.py
registration/admin.py
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfil...
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Python
bsd-3-clause
remarkablerocket/django-mailinglist-registration,remarkablerocket/django-mailinglist-registration
03b180bf1dad2f7f82dec177b1fece369bdcf5e6
build/oggm/run_test.py
build/oggm/run_test.py
#!/usr/bin/env python import os os.environ["MPLBACKEND"] = 'agg' import matplotlib matplotlib.use('agg') import pytest import pytest_mpl.plugin import oggm import sys import ssl ssl._create_default_https_context = ssl._create_unverified_context initial_dir = os.getcwd() oggm_file = os.path.abspath(oggm.__file__) o...
#!/usr/bin/env python import os os.environ["MPLBACKEND"] = 'agg' import matplotlib matplotlib.use('agg') import pytest import oggm import sys import ssl ssl._create_default_https_context = ssl._create_unverified_context initial_dir = os.getcwd() oggm_file = os.path.abspath(oggm.__file__) oggm_dir = os.path.dirname...
Revert "Try to fix mpl invocation"
Revert "Try to fix mpl invocation" This reverts commit c5f0e32eb12ae7809b9fde0371bfb73ec86d47a3.
Python
mit
OGGM/OGGM-Anaconda
695b7cabdc46f3f90b116fa63380bff2ecbfab0c
json_settings/__init__.py
json_settings/__init__.py
import json import logging import os import sys def json_patch(path): logging.warn("Attempting to load local settings from %r" % (path,)) try: d = json.load(open(path)) except IOError: logging.exception("Unable to open json settings in %r" % (path,)) raise SystemExit(-1) except...
import json import logging import os import sys def json_patch(path): logging.warn("Attempting to load local settings from %r" % (path,)) try: d = json.load(open(path)) except IOError: logging.exception("Unable to open json settings in %r" % (path,)) raise SystemExit(-1) except...
Patch to make work like we expect
Patch to make work like we expect
Python
apache-2.0
coolshop-com/django-json-settings
d6be1dfbd9124ed1c35c32a0819bbfa3d9e6759a
scripts/linux/cura.py
scripts/linux/cura.py
#!/usr/bin/python import os, sys try: import OpenGL import wx import serial import numpy import power except ImportError as e: module = e.message.lstrip('No module named ') print 'Requires ' + module if module == 'power': print "Install from: https://github.com/GreatFruitOmsk/...
#!/usr/bin/python import os, sys try: import OpenGL import wx import serial import numpy import power except ImportError as e: module = e.message.lstrip('No module named ') if module == 'OpenGL': module = 'PyOpenGL' elif module == 'serial': module = 'pyserial' ...
Add py prefix to OpenGL and serial. Exit when error.
Add py prefix to OpenGL and serial. Exit when error.
Python
agpl-3.0
alephobjects/Cura,alephobjects/Cura,alephobjects/Cura
56aba3ab7a23dd8bf322a9d577fa64e686dfc9ef
serrano/middleware.py
serrano/middleware.py
class SessionMiddleware(object): def process_request(self, request): if getattr(request, 'user', None) and request.user.is_authenticated(): return session = request.session # Ensure the session is created view processing, but only if a cookie # had been previously set. Th...
from .tokens import get_request_token class SessionMiddleware(object): def process_request(self, request): if getattr(request, 'user', None) and request.user.is_authenticated(): return # Token-based authentication is attempting to be used, bypass CSRF # check if get_re...
Update SessionMiddleware to bypass CSRF if request token is present
Update SessionMiddleware to bypass CSRF if request token is present For non-session-based authentication, Serrano resources handle authenticating using a token based approach. If it is present, CSRF must be turned off to exempt the resources from the check.
Python
bsd-2-clause
rv816/serrano_night,chop-dbhi/serrano,chop-dbhi/serrano,rv816/serrano_night
7e373bd4b3c111b38d983e809aa443ff242860db
tests/test_pipelines/test_python.py
tests/test_pipelines/test_python.py
# -*- coding: utf-8 -*- """ .. module:: tests.test_pipeline.test_python :synopsis: Tests for bundled python pipelines """ from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.pipeli...
# -*- coding: utf-8 -*- """ .. module:: tests.test_pipeline.test_python :synopsis: Tests for bundled python pipelines """ from facio.pipeline.python.virtualenv import Virtualenv from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): ...
Test for getting virtualenv name, prompting the user
Test for getting virtualenv name, prompting the user
Python
bsd-3-clause
krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio
2f6e53a12975dc4e15ba8b85e4df409868ec4df9
tests/test_utils.py
tests/test_utils.py
# Copyright 2013 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
# Copyright 2013 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
Remove unused test code in test_util.py
Remove unused test code in test_util.py This doesn't seem to do anything Change-Id: Ieba6b5f7229680146f9b3f2ae2f3f2d2b1354376
Python
apache-2.0
citrix-openstack-build/python-ceilometerclient,citrix-openstack-build/python-ceilometerclient
b4b7185a054d07097e743664abda44e121674b8b
talks_keeper/forms.py
talks_keeper/forms.py
from django import forms from .models import Label, Talk class TalkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TalkForm, self).__init__(*args, **kwargs) labels = Label.objects.all() for label_ in labels: self.fields.update({ 'label_{}'.fo...
from django import forms from .models import Label, Talk class TalkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TalkForm, self).__init__(*args, **kwargs) instance = kwargs['instance'] labels = Label.objects.all() for label_ in labels: if instance ...
Update TalkForm to use checked labels
Update TalkForm to use checked labels
Python
mit
samitnuk/talks_keeper,samitnuk/talks_keeper,samitnuk/talks_keeper
6df1e7a7f0987efc8e34c521e8c4de9a75f9dfde
troposphere/auth.py
troposphere/auth.py
import logging from troposphere.query import only_current_tokens logger = logging.getLogger(__name__) def has_valid_token(user): """ Returns boolean indicating if there are non-expired authentication tokens associated with the user. """ logger.info(hasattr(user, "auth_tokens")) non_expired_...
import logging from troposphere.query import only_current_tokens logger = logging.getLogger(__name__) def has_valid_token(user): """ Returns boolean indicating if there are non-expired authentication tokens associated with the user. """ logger.info("user has auth_tokens attributes? %s" % ...
Use exists() check from QuerySet; give logger-info context
Use exists() check from QuerySet; give logger-info context
Python
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
8dcf6c373316d21399fa1edd276cea357fea75fb
groundstation/sockets/stream_socket.py
groundstation/sockets/stream_socket.py
import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # XXX Implement the...
import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # XXX Implement the...
Support being given protobuf Messages
Support being given protobuf Messages
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
90a933fcfa52c6ebc41e810b3c851cca696f1e71
project/apps/api/management/commands/denormalize.py
project/apps/api/management/commands/denormalize.py
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v...
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v...
Remove ranking from denormalization command
Remove ranking from denormalization command
Python
bsd-2-clause
barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api
68bc2d2b50e754d50f1a2f85fa7dbde0ca8a6a12
qual/tests/test_iso.py
qual/tests/test_iso.py
import unittest from hypothesis import given from hypothesis.strategies import integers from hypothesis.extra.datetime import datetimes import qual from datetime import date, MINYEAR, MAXYEAR class TestIsoUtils(unittest.TestCase): @given(datetimes(timezones=[])) def test_round_trip_date(self, dt): d ...
import unittest from hypothesis import given from hypothesis.strategies import integers from hypothesis.extra.datetime import datetimes import qual from datetime import date, MINYEAR, MAXYEAR class TestIsoUtils(unittest.TestCase): @given(datetimes(timezones=[])) def test_round_trip_date(self, dt): d ...
Add a new passing test for invalid week numbers.
Add a new passing test for invalid week numbers.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
c1a1c976642fa1d8f17f89732f6c4fe5bd76d0de
devito/dimension.py
devito/dimension.py
import cgen from sympy import Symbol __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: Optional, boolean flag...
import cgen import numpy as np from sympy import Symbol __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: O...
Add dtype of iteration variable
Dimension: Add dtype of iteration variable
Python
mit
opesci/devito,opesci/devito
7072389221f7e287328cecc695b93a77d04c69ba
tests/basecli_test.py
tests/basecli_test.py
from unittest import TestCase from ass2m.cli import CLI from tempfile import mkdtemp import shutil class BaseCLITest(TestCase): def setUp(self): self.root = mkdtemp(prefix='ass2m_test_root') self.app = CLI(self.root) def tearDown(self): if self.root: shutil.rmtree(self.root...
from unittest import TestCase from ass2m.cli import CLI from tempfile import mkdtemp import shutil import sys import re from StringIO import StringIO class BaseCLITest(TestCase): def setUp(self): self.root = mkdtemp(prefix='ass2m_test_root') self.app = CLI(self.root) def tearDown(self): ...
Test and capture the CLI output
Test and capture the CLI output
Python
agpl-3.0
laurentb/assnet,laurentb/assnet
926d5333c1556850a3eda6025ac8cf471b67c0a3
condor/probes/setup.py
condor/probes/setup.py
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License from distutils.core import setup setup(name='htcondor-es-probes', version='0.6.3', description='HTCondor probes for Elasticsearch analytics', author='Suchandra Thapa', author_email='sthapa@ci.uch...
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License from distutils.core import setup setup(name='htcondor-es-probes', version='0.6.3', description='HTCondor probes for Elasticsearch analytics', author='Suchandra Thapa', author_email='sthapa@ci.uch...
Add directory for state files
Add directory for state files
Python
apache-2.0
DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs
2d102e049ceb4ac6d9892313e78b82fc91f9e84c
tests/test_filters.py
tests/test_filters.py
from unittest import TestCase import numpy as np from hrv.filters import moving_average class Filter(TestCase): def test_moving_average_order_3(self): fake_rri = np.array([810, 830, 860, 790, 804]) rri_filt = moving_average(fake_rri, order=3) expected = [810, 833.33, 826.66, 818, 804] ...
from unittest import TestCase import numpy as np from hrv.filters import moving_average class Filter(TestCase): def test_moving_average_order_3(self): fake_rri = np.array([810, 830, 860, 790, 804]) rri_filt = moving_average(fake_rri, order=3) expected = [810, 833.33, 826.66, 818, 804] ...
Test moving average filter for 5th order
Test moving average filter for 5th order
Python
bsd-3-clause
rhenanbartels/hrv
e1c57cb41c59c118648602ff9837418e5d4baad4
saleor/dashboard/category/forms.py
saleor/dashboard/category/forms.py
from django import forms from ...product.models import Category class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = []
from django import forms from django.utils.translation import ugettext_lazy as _ from ...product.models import Category class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = [] def clean_parent(self): parent = self.cleaned_data['parent'] if parent == sel...
Add validation on category parent field
Add validation on category parent field
Python
bsd-3-clause
itbabu/saleor,rchav/vinerack,avorio/saleor,HyperManTT/ECommerceSaleor,laosunhust/saleor,itbabu/saleor,josesanch/saleor,Drekscott/Motlaesaleor,maferelo/saleor,taedori81/saleor,rchav/vinerack,avorio/saleor,rodrigozn/CW-Shop,avorio/saleor,maferelo/saleor,arth-co/saleor,paweltin/saleor,jreigel/saleor,paweltin/saleor,Dreksc...
7b9206d7c3fcf91c6ac16b54b9e1d13b92f7802a
tests/test_testing.py
tests/test_testing.py
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test MetPy's testing utilities.""" import numpy as np import pytest from metpy.testing import assert_array_almost_equal # Test #1183: numpy.testing.assert_array* ignores an...
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test MetPy's testing utilities.""" import warnings import numpy as np import pytest from metpy.deprecation import MetpyDeprecationWarning from metpy.testing import assert_arr...
Add explicit test for deprecation decorator
MNT: Add explicit test for deprecation decorator
Python
bsd-3-clause
dopplershift/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy,Unidata/MetPy,Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy
fd39c97cd1cab3e55ba6aa067127af93e41af506
tests/travis-setup.py
tests/travis-setup.py
import bcrypt import sys import os sys.path.insert(0, "..") from timpani import database connection = database.DatabaseConnection() hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8") user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpan...
import bcrypt import sys import os sys.path.insert(0, "..") from timpani import database connection = database.DatabaseConnection() hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8") user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpan...
Create index on session_id in order to speed tests
Create index on session_id in order to speed tests It seems that session querying has been the longest component of all my tests, and adding one test raised my test time signifigantly. Hopefully this smooths somet of that out.
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
25133d90fe267dba522c9b87eb0bd614ae8556dd
web_433Mhz/views.py
web_433Mhz/views.py
from web_433Mhz import app from flask import render_template @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html')
from web_433Mhz import app from flask import render_template, jsonify import subprocess import os @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html') @app.route('/api/get_code', methods=['GET']) def get_code(): proc = subprocess.Popen(os.path.abspath('../433Mhz'),\ ...
Add api call to open binary and grab stdout
Add api call to open binary and grab stdout
Python
agpl-3.0
tuxxy/433Mhz_web,tuxxy/433Mhz_web,tuxxy/433Mhz_web,tuxxy/433Mhz_web
5c30173731d058b51d7a94238a3ccf5984e2e790
echo_server.py
echo_server.py
#!/usr/bin/env python import socket def main(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) server_socket.bind(('127.0.0.1', 50000)) server_socket.listen(1) conn, addr = server_socket.accept() msg = conn.recv(1024) conn...
#!/usr/bin/env python import socket def main(): server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) server_socket.bind(('127.0.0.1', 50000)) server_socket.listen(1) conn, addr = server_socket.accept() msg = conn.recv(1024) conn.sendall(...
Change format to satify pedantic linter
Change format to satify pedantic linter
Python
mit
charlieRode/network_tools
76ecb6a4b71d1a248b21cf1671360514dc6c3be2
mobile/backends/twilio.py
mobile/backends/twilio.py
# encoding: utf-8 from twilio.rest import TwilioRestClient from mobile.backends.base import BaseBackend class Backend(BaseBackend): """Twilio Gate Backend.""" class SMS: @classmethod def send(self, recipient, sender, message): """ Send an SMS and return its initial de...
# encoding: utf-8 import twilio.twiml from django.http import QueryDict from twilio.rest import TwilioRestClient from mobile.backends.base import BaseBackend import mobile.models class Backend(BaseBackend): """Twilio Gate Backend.""" class SMS: @classmethod def send(self, recipient, sender...
Add receive support to Twilio backend
Add receive support to Twilio backend
Python
mit
hyperoslo/django-mobile
a6e868803e1336d83ee8863d15896880603fc777
tornwamp/customize.py
tornwamp/customize.py
""" TornWAMP user-configurable structures. """ from tornwamp.processors import GoodbyeProcessor, HelloProcessor, pubsub, rpc from tornwamp.messages import Code processors = { Code.HELLO: HelloProcessor, Code.GOODBYE: GoodbyeProcessor, Code.SUBSCRIBE: pubsub.SubscribeProcessor, Code.CALL: rpc.CallProces...
""" TornWAMP user-configurable structures. """ from tornwamp.processors import GoodbyeProcessor, HelloProcessor, pubsub, rpc from tornwamp.messages import Code processors = { Code.HELLO: HelloProcessor, Code.GOODBYE: GoodbyeProcessor, Code.SUBSCRIBE: pubsub.SubscribeProcessor, Code.CALL: rpc.CallProces...
Add PublishProcessor to processors' list
Add PublishProcessor to processors' list
Python
apache-2.0
ef-ctx/tornwamp
b2e0a123631d326f06192a01758ebe581284dbdf
src/pip/_internal/operations/generate_metadata.py
src/pip/_internal/operations/generate_metadata.py
"""Metadata generation logic for source distributions. """ def get_metadata_generator(install_req): if install_req.use_pep517: return install_req.prepare_pep517_metadata else: return install_req.run_egg_info
"""Metadata generation logic for source distributions. """ def get_metadata_generator(install_req): if not install_req.use_pep517: return install_req.run_egg_info return install_req.prepare_pep517_metadata
Return early for legacy processes
Return early for legacy processes
Python
mit
xavfernandez/pip,pfmoore/pip,rouge8/pip,rouge8/pip,pradyunsg/pip,rouge8/pip,pfmoore/pip,sbidoul/pip,xavfernandez/pip,pypa/pip,pradyunsg/pip,xavfernandez/pip,pypa/pip,sbidoul/pip
99b668594582882bb1fbca3b3793ff452edac2c1
updatebot/__init__.py
updatebot/__init__.py
# # Copyright (c) SAS Institute, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# # Copyright (c) SAS Institute, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Remove import of missing module
Remove import of missing module
Python
apache-2.0
sassoftware/mirrorball,sassoftware/mirrorball
f4777e994a29a8dbc704950411156cca4ff59ac3
oscar/core/compat.py
oscar/core/compat.py
from django.conf import settings from django.contrib.auth.models import User def get_user_model(): """ Return the User model Using this function instead of Django 1.5's get_user_model allows backwards compatibility with Django 1.4. """ try: # Django 1.5+ from django.contrib.au...
from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured def get_user_model(): """ Return the User model Using this function instead of Django 1.5's get_user_model allows backwards compatibility with Django 1.4. """ t...
Use better exception for AUTH_USER_MODEL
Use better exception for AUTH_USER_MODEL If AUTH_USER_MODEL is improperly configured as 'project.customer.User', the error is: ValueError: too many values to unpack Use rather standard Django's error: ImproperlyConfigured: AUTH_USER_MODEL must be of the form 'app_label.model_name'
Python
bsd-3-clause
faratro/django-oscar,rocopartners/django-oscar,thechampanurag/django-oscar,spartonia/django-oscar,vovanbo/django-oscar,saadatqadri/django-oscar,sasha0/django-oscar,pdonadeo/django-oscar,monikasulik/django-oscar,bschuon/django-oscar,mexeniz/django-oscar,jinnykoo/christmas,QLGu/django-oscar,manevant/django-oscar,jinnykoo...
690c70db9717bcc538db4e35597145870106844f
versioning/signals.py
versioning/signals.py
import sha from django.contrib.contenttypes.models import ContentType from versioning import _registry from versioning.diff import unified_diff from versioning.models import Revision def pre_save(instance, **kwargs): """ """ model = kwargs["sender"] fields = _registry[model] original = mode...
import sha from django.contrib.contenttypes.models import ContentType from versioning import _registry from versioning.diff import unified_diff from versioning.models import Revision def pre_save(instance, **kwargs): """ """ model = kwargs["sender"] fields = _registry[model] original = mode...
Use splitlines instead of hard-coding the line endings.
Use splitlines instead of hard-coding the line endings. git-svn-id: 15b99a5ef70b6649222be30eb13433ba2eb40757@14 cdb1d5cb-5653-0410-9e46-1b5f511687a6
Python
bsd-3-clause
luzfcb/django-versioning,luzfcb/django-versioning
c79d040cb952e8e37c231caf90eda92d152978b8
openfisca_country_template/__init__.py
openfisca_country_template/__init__.py
# -*- coding: utf-8 -*- import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) # Our country tax and benefit class inherits from the general TaxBenefitSystem class. # The name CountryTaxBenefitSystem must not be chan...
# -*- coding: utf-8 -*- import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) # Our country tax and benefit class inherits from the general TaxBenefitSystem class. # The name CountryTaxBenefitSystem must not be chan...
Use YAML params instead of XML params
Use YAML params instead of XML params
Python
agpl-3.0
openfisca/country-template,openfisca/country-template
07bd41f4588570a3b026efad0a70d979f4bf8e5b
esis/__init__.py
esis/__init__.py
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0'
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0' from esis.es import Client
Make client available at the package level
Make client available at the package level This will make imports easier for anyone willing to use esis as a library
Python
mit
jcollado/esis
cc3f28e74145729c8b572fd9d2ed04d8fb297360
Testing/TestDICOMPython.py
Testing/TestDICOMPython.py
#! /usr/bin/env python2 import sys import vtk import vtkDICOMPython # put everything into the vtk namespace for a in dir(vtkDICOMPython): if a[0] != '_': setattr(vtk, a, getattr(vtkDICOMPython, a)) m = vtk.vtkDICOMMetaData() m.SetAttributeValue(vtk.vtkDICOMTag(0x0008, 0x0005), 'ISO_IR 100') v = m.GetAtt...
#! /usr/bin/env python2 import sys import vtk import vtkDICOMPython # put everything into the vtk namespace for a in dir(vtkDICOMPython): if a[0] != '_': setattr(vtk, a, getattr(vtkDICOMPython, a)) m = vtk.vtkDICOMMetaData() if vtk.vtkVersion.GetVTKMajorVersion() < 6: sys.stderr.write("This test req...
Modify python test for VTK 5.
Modify python test for VTK 5.
Python
bsd-3-clause
dgobbi/vtk-dicom,dgobbi/vtk-dicom,hendradarwin/vtk-dicom,dgobbi/vtk-dicom,hendradarwin/vtk-dicom,hendradarwin/vtk-dicom
5d9fa1838ffe7ffedb59453a0eca520b5f8d5849
pyscf/ci/__init__.py
pyscf/ci/__init__.py
from pyscf.ci.cisd import CISD
from pyscf.ci import cisd def CISD(mf, frozen=[], mo_coeff=None, mo_occ=None): from pyscf import scf if isinstance(mf, (scf.uhf.UHF, scf.rohf.ROHF)): raise NotImplementedError('RO-CISD, UCISD are not available in this pyscf version') return cisd.CISD(mf, frozen, mo_coeff, mo_occ)
Revert accidental changes to ci
Revert accidental changes to ci
Python
apache-2.0
gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf
f957a71b65336c403e876fc04eb45779b873c511
hapi/events.py
hapi/events.py
from base import BaseClient EVENTS_API_VERSION = 'v1' class EventsClient(BaseClient): def _get_path(self, subpath): return 'events/%s/%s' % (EVENTS_API_VERSION, subpath) def get_events(self, **options): return self._call('events', **options) def create_event(self, description,...
from base import BaseClient EVENTS_API_VERSION = 'v1' class EventsClient(BaseClient): def _get_path(self, subpath): return 'events/%s/%s' % (EVENTS_API_VERSION, subpath) def get_events(self, **options): return self._call('events', **options) def get_event(self, event_id, **optio...
Add method to fetch a single event
Add method to fetch a single event
Python
apache-2.0
jonathan-s/happy,CurataEng/hapipy,HubSpot/hapipy,CBitLabs/hapipy
7eb71da0822cdf6ea724a87662952fe90e65a6f6
UM/Operations/ScaleOperation.py
UM/Operations/ScaleOperation.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import Operation from UM.Scene.SceneNode import SceneNode class ScaleOperation(Operation.Operation): def __init__(self, node, scale, **kwargs): super().__init__() self._node = node sel...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import Operation from UM.Scene.SceneNode import SceneNode class ScaleOperation(Operation.Operation): def __init__(self, node, scale, **kwargs): super().__init__() self._node = node sel...
Convert ScaleTool to use add_scale
Convert ScaleTool to use add_scale Contributes to Ultimaker/Uranium/#73 Contributes to Ultimaker/Cura/#493 contributes to #CURA-287 contributes to #CURA-235
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
920c1cd03645bd04df59bdb1f52aab07c710746b
fabtools/__init__.py
fabtools/__init__.py
# Keep imports sorted alphabetically import fabtools.arch import fabtools.cron import fabtools.deb import fabtools.files import fabtools.git import fabtools.group import fabtools.mysql import fabtools.network import fabtools.nginx import fabtools.nodejs import fabtools.openvz import fabtools.pkg import fabtools.postgre...
# Keep imports sorted alphabetically import fabtools.arch import fabtools.cron import fabtools.deb import fabtools.disk import fabtools.files import fabtools.git import fabtools.group import fabtools.mysql import fabtools.network import fabtools.nginx import fabtools.nodejs import fabtools.openvz import fabtools.pkg im...
Add missing import for new disk module
Add missing import for new disk module
Python
bsd-2-clause
ahnjungho/fabtools,badele/fabtools,wagigi/fabtools-python,fabtools/fabtools,davidcaste/fabtools,AMOSoft/fabtools,prologic/fabtools,ronnix/fabtools,n0n0x/fabtools-python,pombredanne/fabtools,sociateru/fabtools,hagai26/fabtools,bitmonk/fabtools
7d28400cc11fec86f542f1a0b03df6b6ed0086ea
dipy/stats/__init__.py
dipy/stats/__init__.py
# code support tractometric statistical analysis for dipy
# code support tractometric statistical analysis for dipy import warnings w_string = "The `dipy.stats` module is still under heavy development " w_string += "and functionality, as well as the API is likely to change " w_string += "in future versions of the software" warnings.warn(w_string)
Add a warning about future changes that will happen in dipy.stats.
Add a warning about future changes that will happen in dipy.stats.
Python
bsd-3-clause
FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy
887c90bbe82fb0ddc85af0a2a9a294bd38677bda
test/lib/test_util.py
test/lib/test_util.py
import unittest import amara from amara.lib import util class Test_util(unittest.TestCase): def test_trim_word_count(self): x = amara.parse('<a>one two <b>three four </b><c>five <d>six seven</d> eight</c> nine</a>') for i in range(1, 11): trimmed_tree = util.trim_word_count(x, i) ...
import unittest import amara from amara.lib import util class Test_trim_word_count(unittest.TestCase): 'Testing amara.lib.util.trim_word_count' def test_flat_doc(self): 'Input doc with just top-level text' x = amara.parse('<a>one two three four five six seven eight nine</a>') for i in ...
Expand trim_word_count test a bit
Expand trim_word_count test a bit
Python
apache-2.0
zepheira/amara,zepheira/amara,zepheira/amara,zepheira/amara,zepheira/amara,zepheira/amara
19fd2795e1cd909bb969a4c4e514d8cb1fd884f5
plugins/XmlMaterialProfile/__init__.py
plugins/XmlMaterialProfile/__init__.py
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import XmlMaterialProfile from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "na...
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import XmlMaterialProfile from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "na...
Mark XmlMaterialProfile as type "material" so the import/export code can find it
Mark XmlMaterialProfile as type "material" so the import/export code can find it Contributes to CURA-341
Python
agpl-3.0
senttech/Cura,fieldOfView/Cura,totalretribution/Cura,hmflash/Cura,Curahelper/Cura,totalretribution/Cura,fieldOfView/Cura,hmflash/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,senttech/Cura,Curahelper/Cura
79c38342193a1ae9a2f12e4b45ccc30cda212c18
indico/modules/events/papers/settings.py
indico/modules/events/papers/settings.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
Add setting to optionally enforce PR deadlines
Add setting to optionally enforce PR deadlines
Python
mit
OmeGak/indico,ThiefMaster/indico,OmeGak/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,indico/indico,pferreir/indico,OmeGak/indico,indico/indico,ThiefMaster/indico,mvidalgarcia/indico,DirkHoffmann/indico,pferreir/indico,mic4ael/indico,mic4ael/indico,mvidalgarcia/indico,mic4ael/indico,ThiefMaster/indico,DirkH...
11a19916c084b5ceee32180988eee9c2e1ebff05
django_payzen/admin.py
django_payzen/admin.py
from django.contrib import admin from . import models class PaymentRequestAdmin(admin.ModelAdmin): model = models.PaymentRequest list_display = ("vads_amount", "get_vads_currency_display", "vads_trans_id", "vads_trans_date") class PaymentResponseAdmin(admin.ModelAdmin): model = mode...
from django.contrib import admin from . import models class PaymentRequestAdmin(admin.ModelAdmin): model = models.PaymentRequest list_display = ("vads_trans_id", "vads_trans_date", "vads_amount", "get_vads_currency_display") class PaymentResponseAdmin(admin.ModelAdmin): model = mode...
Reorder list dispay in RequestPayment and RequestResponse lists.
Reorder list dispay in RequestPayment and RequestResponse lists.
Python
mit
zehome/django-payzen,bsvetchine/django-payzen,zehome/django-payzen,bsvetchine/django-payzen
565ff4653b0dca4bb4831d263dae118d044b6b9c
test/test_molecule.py
test/test_molecule.py
import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def ...
import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/master/requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" pl...
Fix broken requirements file references
Fix broken requirements file references
Python
mit
nephelaiio/cookiecutter-ansible-role
fc4b36c34f8f9edbb688ff4d5ab1d50b4f8c6dac
armstrong/core/arm_layout/utils.py
armstrong/core/arm_layout/utils.py
import warnings from django.conf import settings from armstrong.utils.backends import GenericBackend NEW = "ARMSTRONG_LAYOUT_BACKEND" OLD = "ARMSTRONG_RENDER_MODEL_BACKEND" render_model = (GenericBackend(NEW, defaults="armstrong.core.arm_layout.backends.BasicLayoutBackend") .get_backend()) if hasattr(set...
import warnings from django.conf import settings from armstrong.utils.backends import GenericBackend NEW = "ARMSTRONG_LAYOUT_BACKEND" OLD = "ARMSTRONG_RENDER_MODEL_BACKEND" render_model = (GenericBackend(NEW, defaults="armstrong.core.arm_layout.backends.BasicLayoutBackend") .get_backend()) if hasattr(set...
Use older style string formatting for Python 2.6
Use older style string formatting for Python 2.6
Python
apache-2.0
armstrong/armstrong.core.arm_layout,armstrong/armstrong.core.arm_layout
877f59134c64f3c2e50436289b1cd676d471f66f
src/gramcore/features/tests/test_descriptors.py
src/gramcore/features/tests/test_descriptors.py
"""Tests for module gramcore.features.descriptors""" import numpy from nose.tools import assert_equal from gramcore.features import descriptors def test_hog_size(): """Create a fixture and check hog result size Creates a square array and inputs it to hog. For simplicity the blocks and the cells are squ...
"""Tests for module gramcore.features.descriptors""" import numpy from nose.tools import assert_equal from gramcore.features import descriptors def test_hog_size(): """Create a fixture and check hog result size There are already enough tests in skimage for this, just adding so to document how many valu...
Add note in hog test doc string
Add note in hog test doc string
Python
mit
cpsaltis/pythogram-core
e77cb240d522da47208b60384c40f03f5c9182e3
tests/test_encoder.py
tests/test_encoder.py
# -*- coding: utf-8 -*- import os import glob import pvl DATA_DIR = os.path.join(os.path.dirname(__file__), 'data/') PDS_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data', 'pds3') def test_dump(): files = glob.glob(os.path.join(PDS_DATA_DIR, "*.lbl")) for infile in files: label = pvl.load(i...
# -*- coding: utf-8 -*- import os import glob import pvl DATA_DIR = os.path.join(os.path.dirname(__file__), 'data/') PDS_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data', 'pds3') def test_dump(): files = glob.glob(os.path.join(PDS_DATA_DIR, "*.lbl")) for infile in files: label = pvl.load(i...
Add tests for cube and isis encoders.
Add tests for cube and isis encoders.
Python
bsd-3-clause
pbvarga1/pvl,bvnayak/pvl,wtolson/pvl,planetarypy/pvl
710a2a6d9c462041bae6c41f0578d99262c6a861
tests/test_execute.py
tests/test_execute.py
import asyncpg from asyncpg import _testbase as tb class TestExecuteScript(tb.ConnectedTestCase): async def test_execute_script_1(self): r = await self.con.execute(''' SELECT 1; SELECT true FROM pg_type WHERE false = true; SELECT 2; ''') self.assertIs...
import asyncpg from asyncpg import _testbase as tb class TestExecuteScript(tb.ConnectedTestCase): async def test_execute_script_1(self): r = await self.con.execute(''' SELECT 1; SELECT true FROM pg_type WHERE false = true; SELECT 2; ''') self.assertIs...
Test that con.execute() propagate Postgres exceptions
Test that con.execute() propagate Postgres exceptions
Python
apache-2.0
MagicStack/asyncpg,MagicStack/asyncpg
d95d817bdb1fba7eb0ce0cdabcd64a9908796d2a
tests/unit/test_ls.py
tests/unit/test_ls.py
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = sel...
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = sel...
Fix concurrency bug in ls tests
Fix concurrency bug in ls tests
Python
apache-2.0
globus/globus-cli,globus/globus-cli
71e2bc7976dcb4230c20e2c60a7e23634c38603f
apps/references/autoref.py
apps/references/autoref.py
import os.path import string import urllib, re from datetime import datetime from xml.dom.minidom import parse, parseString # Django from django.core import serializers from django.conf import settings from django.db import models # Methodmint def pubmed(keywords, latest_query=None): # Get matching publications f...
import os.path import string import urllib, re from datetime import datetime from xml.dom.minidom import parse, parseString # Django from django.core import serializers from django.conf import settings from django.db import models # Methodmint def pubmed(keywords, latest_query=None): # Get matching publications f...
Change publication date to Epub; more up-to-date
Change publication date to Epub; more up-to-date
Python
bsd-3-clause
mfitzp/django-golifescience
d410a5295b67b17ca1cdc4d53ed8f776159278bc
json2parquet/__init__.py
json2parquet/__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .client import load_json, ingest_data, write_parquet, convert_json __title__ = 'json2parquet' __version__ = '0.0.24' __all__ = ['load_json', 'ingest_data', 'write_parquet', 'convert_json', 'write_parquet_dataset']
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .client import load_json, ingest_data, write_parquet, convert_json, write_parquet_dataset __title__ = 'json2parquet' __version__ = '0.0.24' __all__ = ['load_json', 'ingest_data', 'write_parquet', 'convert_json', 'write_parquet_dataset']
Make client.write_parquet_dataset available for export
Make client.write_parquet_dataset available for export This commit adds write_parquet_dataset to the imports from .client in __init__.py Previously, `from json2parquet import write_parquet_dataset` would result in an error: `ImportError: cannot import name 'write_parquet_dataset' from 'json2parquet' `
Python
mit
andrewgross/json2parquet
3d570864a39f10d6e502e4005e7931793fca3d01
flask_app/models.py
flask_app/models.py
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import UserMixin, RoleMixin db = SQLAlchemy() ### Add models here roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(...
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import UserMixin, RoleMixin db = SQLAlchemy() ### Add models here roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')), db.Column('role_i...
Add missing cascade deletes on user/roles
Add missing cascade deletes on user/roles
Python
mit
getslash/mailboxer,vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,getslash/mailboxer,Infinidat/lanister,vmalloc/mailboxer,getslash/mailboxer
e2bb78a1587b7d5c0416c3632ca9674339826d55
src/yawf/creation.py
src/yawf/creation.py
from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sende...
from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sende...
Make start_message_params optional in start_workflow()
Make start_message_params optional in start_workflow()
Python
mit
freevoid/yawf
f8bdd7c8139cfc6d7af4bb3d89e983073db976bf
mecodesktop.py
mecodesktop.py
""" MacroecoDesktop script for making standalone executable """ from macroeco import desktop desktop()
""" MacroecoDesktop script for making standalone executable """ import sys as _sys from macroeco import desktop if len(_sys.argv) > 1: desktop(_sys.argv[1]) else: desktop()
Allow compiled OS X app to take parameter file as input on command line
Allow compiled OS X app to take parameter file as input on command line
Python
bsd-2-clause
jkitzes/macroeco
59e4e193ea41d05229f2748743e9783d68d8dabf
apps/__init__.py
apps/__init__.py
## module loader, goes to see which submodules have 'html' directories ## and declares them at the toplevel import os,importlib def find_module_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))] ...
## module loader, goes to see which submodules have 'html' directories ## and declares them at the toplevel import os,importlib def find_module_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))] ...
Handle application erroring to not break the server
Handle application erroring to not break the server
Python
agpl-3.0
sociam/indx,sociam/indx,sociam/indx
5510814b2d186c6bf6d1c8af96eab16302e1675f
test/library/gyptest-shared-obj-install-path.py
test/library/gyptest-shared-obj-install-path.py
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ import...
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ # Pyth...
Add with_statement import for python2.5.
Add with_statement import for python2.5. See http://www.python.org/dev/peps/pep-0343/ which describes the with statement. Review URL: http://codereview.chromium.org/5690003 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@863 78cadc50-ecff-11dd-a971-7dbc132099af
Python
bsd-3-clause
bnq4ever/gypgoogle,sport-monkey/GYP,chromium/gyp,trafi/gyp,xin3liang/platform_external_chromium_org_tools_gyp,pyokagan/gyp,Danath/gyp,luvit/gyp,tarc/gyp,MIPS/external-chromium_org-tools-gyp,trafi/gyp,mgamer/gyp,springmeyer/gyp,ttyangf/pdfium_gyp,trafi/gyp,duanhjlt/gyp,kevinchen3315/gyp-git,pandaxcl/gyp,turbulenz/gyp,ca...
55c183ad234ec53e2c7ba82e9e19793564373200
comics/comics/dieselsweetiesweb.py
comics/comics/dieselsweetiesweb.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.meta.base import MetaBase class Meta(MetaBase): name = 'Diesel Sweeties (web)' language = 'en' url = 'http://www.dieselsweeties.com/' start_date = '2000-01-01' rights = 'Richard Stevens' class Crawler(CrawlerBase): his...
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.meta.base import MetaBase class Meta(MetaBase): name = 'Diesel Sweeties (web)' language = 'en' url = 'http://www.dieselsweeties.com/' start_date = '2000-01-01' rights = 'Richard Stevens' class Crawler(CrawlerBase): his...
Check if field exists, not if it's empty
Check if field exists, not if it's empty
Python
agpl-3.0
jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics
15838f52f7f0cc40bcec8f64ad59dffe6bd945a5
hatarake/__init__.py
hatarake/__init__.py
import os import platform from hatarake.version import __version__ ISSUES_LINK = 'https://github.com/kfdm/hatarake/issues' ISSUES_API = 'https://api.github.com/repos/kfdm/hatarake/issues?state=open' USER_AGENT = 'Hatarake/%s https://github.com/kfdm/hatarake' % __version__ GROWL_INTERVAL = 30 if 'Darwin' in platform...
import os import platform from hatarake.version import __version__ ISSUES_LINK = 'https://github.com/kfdm/hatarake/issues' ISSUES_API = 'https://api.github.com/repos/kfdm/hatarake/issues?state=open' USER_AGENT = 'Hatarake/%s https://github.com/kfdm/hatarake' % __version__ GROWL_INTERVAL = 30 if 'Darwin' in platform...
Add path for sqlite file
Add path for sqlite file
Python
mit
kfdm/hatarake
9ca8b4bddabe8bdf91019d0bbc9a792feacbaff9
config.py
config.py
# Log config import logging BASE_PATH = "/home/user/workspace/OSHI-monitoring/" RRD_LOG_PATH = BASE_PATH+"logs/" TRAFFIC_MONITOR_LOG_PATH = BASE_PATH+"logs/" LOG_LEVEL = logging.ERROR # RRD config RRD_STEP = "300" RRD_STORE_PATH = BASE_PATH+"rrd/" RRD_DATA_SOURCE_TYPE = "GAUGE" RRD_DATA_SOURCE_HEARTBEAT = "600" # T...
# Log config import logging BASE_PATH = "/home/user/workspace/OSHI-monitoring/" RRD_LOG_PATH = BASE_PATH + "logs/" TRAFFIC_MONITOR_LOG_PATH = BASE_PATH + "logs/" LOG_LEVEL = logging.ERROR # Traffic monitor config REQUEST_INTERVAL = 30 LLDP_NOISE_BYTE_S = 19 LLDP_NOISE_PACK_S = 0.365 # RRD config RRD_STEP = str(REQU...
Set RRD STEP equal to REQUEST_INTERVAL.
Set RRD STEP equal to REQUEST_INTERVAL.
Python
mit
StefanoSalsano/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,netgroup/OSHI-monitoring,ferrarimarco/OSHI-monitoring,ferrarimarco/OSHI-monitoring,netgroup/OSHI-monitoring
9a7654c727a24eecadc26ac400408cb4837ec0cc
pywayland/protocol/__init__.py
pywayland/protocol/__init__.py
# Copyright 2015 Sean Vig # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
# Copyright 2015 Sean Vig # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
Fix intflag on Python 3.5
Fix intflag on Python 3.5 Just define it to IntEnum, which is definitely not going to be correct, but this should fix the tests on Python 3.5
Python
apache-2.0
flacjacket/pywayland
131cb9abd711cc71c558e5a89d5e2b8a28ae8517
tests/integration/test_gists.py
tests/integration/test_gists.py
from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist ...
# -*- coding: utf-8 -*- """Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): """Gist integration tests.""" def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cas...
Add docstrings to Gist integration tests
Add docstrings to Gist integration tests @esacteksab would be so proud
Python
bsd-3-clause
krxsky/github3.py,balloob/github3.py,jim-minter/github3.py,ueg1990/github3.py,wbrefvem/github3.py,agamdua/github3.py,christophelec/github3.py,icio/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,h4ck3rm1k3/github3.py,degustaf/github3.py
02550f389a6b3208d86e7a92f01c9e1df42561f7
sahara/tests/unit/testutils.py
sahara/tests/unit/testutils.py
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Use immutable arg rather mutable arg
Use immutable arg rather mutable arg Passing mutable objects as default args is a known Python pitfall. We'd better avoid this. This commit changes mutable default args with None, then use 'arg = arg or []'. Change-Id: If3a10d58e6cd792a2011c177c49d3b865a7421ff
Python
apache-2.0
henaras/sahara,ekasitk/sahara,esikachev/scenario,redhat-openstack/sahara,ekasitk/sahara,tellesnobrega/sahara,tellesnobrega/sahara,keedio/sahara,citrix-openstack-build/sahara,mapr/sahara,ekasitk/sahara,matips/iosr-2015,bigfootproject/sahara,mapr/sahara,zhujzhuo/Sahara,esikachev/sahara-backup,zhangjunli177/sahara,bigfoot...
19fb0aa1daceed336c7f452ed361ad79107e75a2
server/src/voodoo/sessions/sqlalchemy_data.py
server/src/voodoo/sessions/sqlalchemy_data.py
#-*-*- encoding: utf-8 -*-*- # # Copyright (C) 2005-2009 University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # listed below: # # A...
#-*-*- encoding: utf-8 -*-*- # # Copyright (C) 2005-2009 University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # listed below: # # A...
Remove sqlalchemy 0.7 warning (Binary => LargeBinary)
Remove sqlalchemy 0.7 warning (Binary => LargeBinary)
Python
bsd-2-clause
morelab/weblabdeusto,weblabdeusto/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,zstars/weblabdeusto,weblabdeusto/weblabdeusto,weblabdeusto/weblabdeusto,weblabdeusto/weblabdeusto,morelab/weblabdeusto,zstars/weblabdeusto,zstars/weblabdeusto,weblabdeusto/weblabdeusto,morelab/weblabdeusto,weblabdeusto/weblabdeusto...
9d184e1d323078d7ce73300ba90f6711c6e8f4c1
oauth_access/models.py
oauth_access/models.py
import datetime from django.db import models from django.contrib.auth.models import User class UserAssociation(models.Model): user = models.ForeignKey(User) service = models.CharField(max_length=75, db_index=True) identifier = models.CharField(max_length=255, db_index=True) token = models.CharF...
import datetime from django.db import models from django.contrib.auth.models import User class UserAssociation(models.Model): user = models.ForeignKey(User) service = models.CharField(max_length=75, db_index=True) identifier = models.CharField(max_length=255, db_index=True) token = models.CharF...
Check if an association has an expiry time before deciding if it's expired
Check if an association has an expiry time before deciding if it's expired
Python
bsd-3-clause
eldarion/django-oauth-access,eldarion/django-oauth-access
45bbd9c64fb19d22a04b19c3bc61081e38e154a3
mail_corpus.py
mail_corpus.py
import sys import mailbox import mail_parser import nltk import itertools try: import cPickle as pickle except ImportError: import pickle def main(): """Extract the texts of emails from a specified mailbox and from a specified set of senders and write corpus.txt. Usage: python mail_corpus.py outpu...
import sys import mailbox import mail_parser import nltk import itertools try: import cPickle as pickle except ImportError: import pickle def main(): """Extract the texts of emails from a specified mailbox and from a specified set of senders and write corpus.txt. Usage: python mail_corpus.py mboxf...
Switch back to always write corpus.txt
Switch back to always write corpus.txt
Python
mit
RawPlutonium/BaymaxKE
8eb9360e575d57b2414468c8ec6c895baf239d63
mwikiircbot.py
mwikiircbot.py
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
Remove unnecessary conditional in argument parsing
Remove unnecessary conditional in argument parsing
Python
mit
fenhl/mwikiircbot
3fd7c331273f9fadacae1fcb0ff51b9817b009e3
telethon/network/connection/tcpfull.py
telethon/network/connection/tcpfull.py
import struct from zlib import crc32 from .connection import Connection from ...errors import InvalidChecksumError class ConnectionTcpFull(Connection): """ Default Telegram mode. Sends 12 additional bytes and needs to calculate the CRC value of the packet itself. """ def __init__(self, ip, port, ...
import struct from zlib import crc32 from .connection import Connection from ...errors import InvalidChecksumError class ConnectionTcpFull(Connection): """ Default Telegram mode. Sends 12 additional bytes and needs to calculate the CRC value of the packet itself. """ def __init__(self, ip, port, ...
Fix automatic reconnect (e.g. on bad auth key)
Fix automatic reconnect (e.g. on bad auth key) This took more time than it should have to debug.
Python
mit
LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon
7435d508ae95c69dcb596e74f62bfb030011201f
tests/general/test_required_folders.py
tests/general/test_required_folders.py
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = 'bob@bob.com' access_token = None imap_e...
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = 'bob@bob.com' access_token = None imap_e...
Update mock Account in tests.
Update mock Account in tests.
Python
agpl-3.0
jobscore/sync-engine,jobscore/sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,closeio/nylas,nylas/sync-engine,nylas/sync-engine,closeio/nylas
d72882dfa24e1dfd8d1b85103cbc5388e4af3266
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.view...
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.view...
Handle case for error formatting where errors are a list of dictionaries (as you would see in bulk create).
Handle case for error formatting where errors are a list of dictionaries (as you would see in bulk create).
Python
apache-2.0
jnayak1/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,abought/osf.io,SSJohns/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,GageGaskins/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,baylee-d/osf.io,felliott/osf.io,caseyrygt/osf.io,asanfilippo7/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,cslzchen/osf....
79d7ba8e3b590bc4ecdc4ae2b8808f14093902d0
pikos/logging.py
pikos/logging.py
from __future__ import absolute_import import inspect import os import sys import psutil from collections import namedtuple from functools import wraps from pikos.abstract_monitors import AbstractMonitor __all__ = [ 'FunctionLogger', 'FunctionRecord', ] FunctionRecord = namedtuple('FunctionRecord', ...
from __future__ import absolute_import import inspect from collections import namedtuple from pikos._profile_functions import ProfileFunctions from pikos._trace_functions import TraceFunctions __all__ = [ 'FunctionLogger', 'FunctionRecord', ] FunctionRecord = namedtuple('FunctionRecord', ...
Make the FunctionLogger a context manager
Make the FunctionLogger a context manager
Python
bsd-3-clause
enthought/pikos,enthought/pikos,enthought/pikos
b9654ffbbd1c2057d1ff377a0190b115f568d080
knights/defaulttags.py
knights/defaulttags.py
from .library import Library import datetime register = Library() @register.tag(name='now') def now(parser, token): args, kwargs = parser.parse_args(token) def _now(context): a, k = parser.resolve_args(context, args, kwargs) val = datetime.datetime.now() return val.strftime(a[0]) ...
from .library import Library from .parse import BasicNode import datetime register = Library() @register.tag(name='now') class NowNode(BasicNode): def render(self, fmt): val = datetime.datetime.now() return val.strftime(fmt)
Rewrite 'now' tag to use BasicNode
Rewrite 'now' tag to use BasicNode
Python
mit
funkybob/knights-templater,funkybob/knights-templater
d610e03ef113d37d516bd9432bd3f43f3d443563
tests/test_commands.py
tests/test_commands.py
import os from subprocess import call import unittest from testpath.commands import * class CommandsTests(unittest.TestCase): def test_assert_calls(self): initial_path = os.environ['PATH'] with assert_calls('foobar'): call(['foobar']) with self.assertR...
import os from subprocess import call import unittest from testpath.commands import * class CommandsTests(unittest.TestCase): def test_assert_calls(self): initial_path = os.environ['PATH'] with assert_calls('foobar'): call(['foobar']) with self.assertR...
Add failing test for gh-5
Add failing test for gh-5
Python
bsd-3-clause
jupyter/testpath
1977ab5bd97feb114dedd1619c89413f109f0480
tests/validate_test.py
tests/validate_test.py
from pytest import raises from nirum.validate import (validate_boxed_type, validate_record_type, validate_union_type) def test_validate_boxed_type(): assert validate_boxed_type(3.14, float) with raises(TypeError): validate_boxed_type('hello', float) def test_validate_rec...
from pytest import raises from nirum.validate import (validate_boxed_type, validate_record_type, validate_union_type) def test_validate_boxed_type(): assert validate_boxed_type(3.14, float) with raises(TypeError): validate_boxed_type('hello', float) def test_validate_rec...
Remove assert in error-rasing test
Remove assert in error-rasing test
Python
mit
spoqa/nirum-python,spoqa/nirum-python