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 |
|---|---|---|---|---|---|---|---|---|---|
3dbca57a197bcf3161939a748b3ced181e7a49e4 | carafe/response.py | carafe/response.py | """Extension of flask.Response.
"""
from flask import Response as ResponseBase, json, current_app, request
class Response(ResponseBase):
"""Extend flask.Response with support for list/dict conversion to JSON."""
def __init__(self, content=None, *args, **kargs):
if isinstance(content, (list, dict)):
... | """Extension of flask.Response.
"""
from flask import Response as ResponseBase, json, current_app, request
class Response(ResponseBase):
"""Extend flask.Response with support for list/dict conversion to JSON."""
def __init__(self, content=None, *args, **kargs):
if isinstance(content, (list, dict)):
... | Add explicit JSON separators and append newline to end of JSON string. | Add explicit JSON separators and append newline to end of JSON string.
| Python | mit | dgilland/carafe |
d9fc83ec526df1bf732d8f65f445f48f1b764dfe | selvbetjening/api/rest/models.py | selvbetjening/api/rest/models.py |
from tastypie.authentication import Authentication
from tastypie.resources import ModelResource
from provider.oauth2.models import AccessToken
from selvbetjening.core.members.models import SUser
class OAuth2Authentication(Authentication):
def is_authenticated(self, request, **kwargs):
access_key = re... |
from tastypie.authentication import Authentication
from tastypie.resources import ModelResource
from provider.oauth2.models import AccessToken
from selvbetjening.core.members.models import SUser
class OAuth2Authentication(Authentication):
def is_authenticated(self, request, **kwargs):
access_key = re... | Fix mistake returning the wrong authenticated user | Fix mistake returning the wrong authenticated user
| Python | mit | animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening |
205ce071b4376872afd3d58c815a2c6804741627 | names.py | names.py | import re
# A regular expression is a string like what you see below between the quote
# marks, and the ``re`` module interprets it as a pattern. Each regular
# expression describes a small program that takes another string as input and
# returns information about that string. See
# http://docs.python.org/library/re.... | import re
# A regular expression is a string like what you see below between the quote
# marks, and the ``re`` module interprets it as a pattern. Each regular
# expression describes a small program that takes another string as input and
# returns information about that string. See
# http://docs.python.org/library/re.... | Use PEP8 style for conditionals | Use PEP8 style for conditionals
| Python | unlicense | wkschwartz/first-last |
4653b9f493d28a6beb88a97d3d396ec1c9288f53 | Sketches/JT/Jam/library/trunk/Kamaelia/Apps/Jam/Audio/Mixer.py | Sketches/JT/Jam/library/trunk/Kamaelia/Apps/Jam/Audio/Mixer.py | import numpy
import Axon
class MonoMixer(Axon.AdaptiveCommsComponent.AdaptiveCommsComponent):
channels = 8
bufferSize = 1024
def __init__(self, **argd):
super(MonoMixer, self).__init__(**argd)
for i in range(self.channels):
self.addInbox("in%i" % i)
def main(self):
... | import numpy
import Axon
import time
from Axon.SchedulingComponent import SchedulingAdaptiveCommsComponent
class MonoMixer(SchedulingAdaptiveCommsComponent):
channels = 8
bufferSize = 1024
sampleRate = 44100
def __init__(self, **argd):
super(MonoMixer, self).__init__(**argd)
for i in r... | Change the mixer to be a scheduled component, and stop it from sending unnecessary messages when it has only received data from a few of it's inputs. | Change the mixer to be a scheduled component, and stop it from sending unnecessary messages when it has only received data from a few of it's inputs.
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia |
c81a5e42bdbbeda58e661667b0613e8e5f8d41c6 | softwareindex/handlers/coreapi.py | softwareindex/handlers/coreapi.py | # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import reque... | # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import reque... | Enforce type of identifier parameter. | Enforce type of identifier parameter.
| Python | bsd-3-clause | softwaresaved/softwareindex,softwaresaved/softwareindex |
178bf48c01b61c6db15dc03020687c50962dafa8 | bin/get_value_stream_status.py | bin/get_value_stream_status.py | #!/usr/bin/env python
# This script uses the built-in Python module to check whether a given
# pipeline is passing, failing, or blocked. To check for a blocked
# pipeline, it looks through all upstream pipelines for any that are
# failing or paused.
from __future__ import print_function
import json
import gocd_parser... | #!/usr/bin/env python
# This script uses the built-in Python module to check whether a given
# pipeline is passing, failing, or blocked. To check for a blocked
# pipeline, it looks through all upstream pipelines for any that are
# failing or paused.
from __future__ import print_function
import json
import gocd_parser... | Make the get_status script quieter | Make the get_status script quieter
| Python | mit | greenmoss/gocd-parser |
5386edbd7c88a1f53c88869abbf63c00ce212352 | pyaxiom/netcdf/utils.py | pyaxiom/netcdf/utils.py | #!python
# coding=utf-8
def cf_safe_name(name):
import re
if isinstance(name, str):
if re.match('^[0-9_]', name):
# Add a letter to the front
name = "v_{}".format(name)
return re.sub(r'[^_a-zA-Z0-9]', "_", name)
| #!python
# coding=utf-8
def isstr(s):
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
def cf_safe_name(name):
import re
if isstr(name):
if re.match('^[0-9_]', name):
# Add a letter to the front
name = "v_{}".format(nam... | Fix cf_safe_name for python 2.7 | Fix cf_safe_name for python 2.7
| Python | mit | axiom-data-science/pyaxiom,axiom-data-science/pyaxiom |
c2b3173a1246538d0b11a89a696288e41993eb5a | paws/conf.py | paws/conf.py | import os
class env(object):
def __init__(self, default=None):
self.name = None
self.default = default
def __get__(self, obj, cls=None):
if cls:
return os.environ.get(self.name.upper(), self.default)
class MetaConfig(type):
'''Quickly tell the env attrs their names.'... | import os
class env(object):
def __init__(self, default=None):
self.name = None
self.default = default
def __get__(self, obj, cls=None):
if not obj:
return self
return os.environ.get(self.name.upper(), self.default)
class MetaConfig(type):
'''Quickly tell the... | Fix detecting class access of descriptor. Set name on attr, not env class! | Fix detecting class access of descriptor. Set name on attr, not env class!
| Python | bsd-3-clause | funkybob/paws |
8c8fbb8c3cf53ce0b193926fc89e426fb360eb81 | database_import.py | database_import.py | import sys
import csv
from sqlalchemy.exc import IntegrityError
from openledger.models import db, Image
filename = sys.argv[1]
fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License',
'AuthorProfileURL', 'Author', 'Title')
with open(filename) as csvfile:
db.create_all()
reade... | import csv
import argparse
from sqlalchemy.exc import IntegrityError
from openledger.models import db, Image
def import_from_open_images(filename):
fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License',
'AuthorProfileURL', 'Author', 'Title')
with open(filename) as csvf... | Tidy up database import to take arguments for multiple sources | Tidy up database import to take arguments for multiple sources
| Python | mit | creativecommons/open-ledger,creativecommons/open-ledger,creativecommons/open-ledger |
3b215b5c6fea45f11f3e1969e6626b175a5b9b6a | medical_medication_us/models/medical_medicament.py | medical_medication_us/models/medical_medicament.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class MedicalMedicament(models.Model):
_inherit = 'medical.medicament'
ndc = fields.Char(
string='NDC',
help='National Drug Code for medication... | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class MedicalMedicament(models.Model):
_inherit = 'medical.medicament'
ndc = fields.Char(
string='NDC',
help='National Drug Code for medication... | Add gpi and gcn to medicament in medical_medication_us | Add gpi and gcn to medicament in medical_medication_us
| Python | agpl-3.0 | laslabs/vertical-medical,laslabs/vertical-medical |
eb8218de72d1789b9e054e2ee76c51558cc1a653 | django_fake_model/case_extension.py | django_fake_model/case_extension.py | from __future__ import unicode_literals
from django.test import SimpleTestCase
class CaseExtension(SimpleTestCase):
_models = tuple()
@classmethod
def append_model(cls, model):
cls._models += (model, )
def _pre_setup(self):
super(CaseExtension, self)._pre_setup()
self._map_m... | from __future__ import unicode_literals
from django.test import SimpleTestCase
class CaseExtension(SimpleTestCase):
_models = tuple()
@classmethod
def append_model(cls, model):
cls._models += (model, )
def _pre_setup(self):
super(CaseExtension, self)._pre_setup()
self._map_m... | Fix ordering of deletions on MySQL | Fix ordering of deletions on MySQL
| Python | bsd-3-clause | erm0l0v/django-fake-model |
f53071faad4abb4f935425aa9b56c6dcae51abd4 | nodeconductor/server/test_runner.py | nodeconductor/server/test_runner.py | # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'nodeconductor.server.test_settings'
test_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '..'))
sys.path.insert(0, test_dir)
import django
from django.conf impor... | # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'nodeconductor.server.test_settings'
test_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '..'))
sys.path.insert(0, test_dir)
import django
from django.conf impor... | Move django initialization closer to execution | Move django initialization closer to execution
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
3088096b4a0289939c93f6dcffb3e893e30ca23c | chaser/__init__.py | chaser/__init__.py | __version__ = "0.5"
import argparse
from chaser import chaser
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser_g = subparsers.add_parser('get')
parser_g.add_argument('package')
parser_g.set_defaults(func=chaser.get_source_files)
parser_i = subparser... | __version__ = "0.6"
import argparse
from chaser import chaser
def main():
parser = argparse.ArgumentParser(
description="Next-generation community package management for Chakra."
)
subparsers = parser.add_subparsers()
parser.add_argument('-v', '--version',
help="show version... | Add help info and version flag, bump to 0.6 | Add help info and version flag, bump to 0.6
| Python | bsd-3-clause | rshipp/chaser,rshipp/chaser |
c010c5cc0c3de0a8147e4e50e8d67769ab399770 | django/__init__.py | django/__init__.py | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... | Update django.VERSION in trunk per previous discussion | Update django.VERSION in trunk per previous discussion
git-svn-id: http://code.djangoproject.com/svn/django/trunk@9103 bcc190cf-cafb-0310-a4f2-bffc1f526a37
--HG--
extra : convert_revision : 3c1e3bd735d17d3eb58195c0362d505521706fcc
| Python | bsd-3-clause | adieu/django-nonrel,adieu/django-nonrel,heracek/django-nonrel,heracek/django-nonrel,heracek/django-nonrel,adieu/django-nonrel |
4c96280421d93a3fa851a7baa7ddb94c388c6d25 | cryptography/hazmat/bindings/openssl/dsa.py | cryptography/hazmat/bindings/openssl/dsa.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | Add binding for the DSA parameters generation function | Add binding for the DSA parameters generation function
| Python | bsd-3-clause | Hasimir/cryptography,sholsapp/cryptography,dstufft/cryptography,Hasimir/cryptography,bwhmather/cryptography,sholsapp/cryptography,Lukasa/cryptography,bwhmather/cryptography,skeuomorf/cryptography,kimvais/cryptography,Lukasa/cryptography,bwhmather/cryptography,Hasimir/cryptography,Ayrx/cryptography,dstufft/cryptography,... |
5439552e2e2ba0e5333b86ae23eece9edde43185 | src/syntax/syntactic_simplifier.py | src/syntax/syntactic_simplifier.py | __author__ = 's7a'
# All imports
from parser import Parser
from breaker import Breaker
import re
# The Syntactic simplification class
class SyntacticSimplifier:
# Constructor for the Syntactic Simplifier
def __init__(self):
self.parser = Parser()
self.breaker = Breaker()
# Simplify cont... | __author__ = 's7a'
# All imports
from parser import Parser
from breaker import Breaker
import re
# The Syntactic simplification class
class SyntacticSimplifier:
# Constructor for the Syntactic Simplifier
def __init__(self):
self.parser = Parser()
self.breaker = Breaker()
# Simplify cont... | Add a trailing separator to all sents | Add a trailing separator to all sents
| Python | mit | Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify |
3080c44c23adcb3a09fb94343da872b8b26ce9fc | tests/conftest.py | tests/conftest.py | """Configuration for test environment"""
import sys
from .fixtures import *
collect_ignore = []
if sys.version_info < (3, 5):
collect_ignore.append("test_async.py")
if sys.version_info < (3, 4):
collect_ignore.append("test_coroutines.py")
| """Configuration for test environment"""
import sys
from .fixtures import *
| Remove no longer necessary test ignore logic | Remove no longer necessary test ignore logic
| Python | mit | timothycrosley/hug,timothycrosley/hug,timothycrosley/hug |
9c6f27465fea5303ee167d7da5e648ef9f0c0e47 | setup.py | setup.py | from distutils.core import setup
import os
# Load version string
_verfile = os.path.join(os.path.dirname(__file__), 'openslide', '_version.py')
exec open(_verfile)
setup(
name = 'openslide-python',
version = __version__,
packages = [
'openslide',
],
author = 'OpenSlide project',
author... | from distutils.core import setup
import os
# Load version string
_verfile = os.path.join(os.path.dirname(__file__), 'openslide', '_version.py')
exec open(_verfile)
setup(
name = 'openslide-python',
version = __version__,
packages = [
'openslide',
],
maintainer = 'OpenSlide project',
ma... | Use package maintainer rather than author | Use package maintainer rather than author
| Python | lgpl-2.1 | openslide/openslide-python,openslide/openslide-python |
e19487f21d2de5edeaa2edbb295c43d140797310 | tapioca_harvest/tapioca_harvest.py | tapioca_harvest/tapioca_harvest.py | # coding: utf-8
from tapioca import (
TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin)
from requests.auth import HTTPBasicAuth
from .resource_mapping import RESOURCE_MAPPING
class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter):
resource_mapping = RESOURCE_MAPPING
api_root = 'ht... | # coding: utf-8
from tapioca import (
TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin)
from requests.auth import HTTPBasicAuth
from .resource_mapping import RESOURCE_MAPPING
class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter):
resource_mapping = RESOURCE_MAPPING
api_root = 'ht... | Correct header params on adapter | Correct header params on adapter
| Python | mit | vintasoftware/tapioca-harvest |
bc0aa4d8793857e2c7b43a6cbba6c1c89f3adead | backend/web/test_settings.py | backend/web/test_settings.py | import tempfile
from .settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
DATA_DIR = tempfile.mkdtemp()
CACHE_DIR = str(Path(DATA_DIR) / 'cache')
THUMBNAIL_ROOT = str(Path(CACHE_DIR) / 'thumbnails')
| import tempfile
from .settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
DATA_DIR = tempfile.mkdtemp()
CACHE_DIR = str(Path(DATA_DIR) / 'cache')
PHOTO_RAW_PROCESSED_DIR = str(Path(DATA_DIR) / 'raw-photos-processed')
THUMBNAIL_ROO... | Test settings to include PHOTO_RAW_PROCESSED_DIR | Test settings to include PHOTO_RAW_PROCESSED_DIR
| Python | agpl-3.0 | damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager |
608a1b4c546fba8f79a30b0ed8d0629aa97d1489 | test/features/test_create_pages.py | test/features/test_create_pages.py | from hamcrest import *
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
assert_that(self.browser.find_by_css('h1').text, is_('High-volume ... | from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending")
assert_that(self.browser.find_by_css('h1... | Disable test for html not generated by this branch | Disable test for html not generated by this branch
(Also remove .html from urls)
| Python | mit | gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer |
8a2371a74c27de5e74796d3544670dcc066ce04a | sasview/__init__.py | sasview/__init__.py | __version__ = "4.0b1"
__build__ = "GIT_COMMIT"
try:
import logging
import subprocess
import os
import platform
FNULL = open(os.devnull, 'w')
if platform.system() == "Windows":
args = ['git', 'describe', '--tags']
else:
args = ['git describe --tags']
git_revision = subproc... | __version__ = "4.0b1"
__build__ = "GIT_COMMIT"
try:
import logging
import subprocess
import os
import platform
FNULL = open(os.devnull, 'w')
if platform.system() == "Windows":
args = ['git', 'describe', '--tags']
else:
args = ['git describe --tags']
git_revision = subproc... | Clean up un-needed commented line after jkrzywon fixed subprocess bad behaviour | Clean up un-needed commented line after jkrzywon fixed subprocess bad behaviour
| Python | bsd-3-clause | SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview |
989efc46c1d39804ee5997d85455853db5965788 | ckanext/requestdata/controllers/request_data.py | ckanext/requestdata/controllers/request_data.py | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationEr... | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationEr... | Return exception as error message | Return exception as error message
| Python | agpl-3.0 | ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata |
a0d007d0135f74faa10c9df1cd29320e32d317b3 | codonpdx/insert.py | codonpdx/insert.py | #!/usr/bin/env python
import json
import sys
from db import dbManager
# insert an organism into a database table
def insert(args):
if hasattr(args, 'json'):
data = json.loads(args.json)
else:
data = json.load(args.infile)
with dbManager('config/db.cfg') as db:
for org in data:
... | #!/usr/bin/env python
import json
import sys
from db import dbManager
# insert an organism into a database table
def insert(args):
try:
data = json.loads(args.json)
except AttributeError:
data = json.load(args.infile)
with dbManager('config/db.cfg') as db:
for org in data:
... | Use exception block instead as exception was still being thrown. | Use exception block instead as exception was still being thrown.
| Python | apache-2.0 | PDX-Flamingo/codonpdx-python,PDX-Flamingo/codonpdx-python |
9567e79a5a5925b23a33c5216a9c13edf656151d | test/test_modes/test_backspace.py | test/test_modes/test_backspace.py | from pyqode.qt import QtCore
from pyqode.qt.QtTest import QTest
from pyqode.core.api import TextHelper
from pyqode.core import modes
from test.helpers import editor_open
def get_mode(editor):
return editor.modes.get(modes.SmartBackSpaceMode)
def test_enabled(editor):
mode = get_mode(editor)
assert mode.... | from pyqode.qt import QtCore
from pyqode.qt.QtTest import QTest
from pyqode.core.api import TextHelper
from pyqode.core import modes
from test.helpers import editor_open
def get_mode(editor):
return editor.modes.get(modes.SmartBackSpaceMode)
def test_enabled(editor):
mode = get_mode(editor)
assert mode.... | Reduce test backspace, we just need to ensure it really eats tab_len spaces | Reduce test backspace, we just need to ensure it really eats tab_len spaces
| Python | mit | pyQode/pyqode.core,pyQode/pyqode.core,zwadar/pyqode.core |
1dc11a6959616dbb0ff2bd3266223d0584bfa704 | opps/core/tests/channel_models.py | opps/core/tests/channel_models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from opps.core.models.channel import Channel
class ChannelModelTest(TestCase):
def setUp(self):
self.site = Site.objects.filter(name=u'example.com').get()
self.channel = C... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from opps.core.models.channel import Channel
class ChannelModelTest(TestCase):
def setUp(self):
self.site = Site.objects.filter(name=u'example.com').get()
self.channel = C... | Rename test check channel home to check create home | Rename test check channel home to check create home
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,opps/opps,opps/opps |
de3161d66ab0a5661d98ace04f5f0ae7c01062bf | smsgateway/utils.py | smsgateway/utils.py | import logging
logger = logging.getLogger(__name__)
def strspn(source, allowed):
newchrs = []
for c in source:
if c in allowed:
newchrs.append(c)
return u''.join(newchrs)
def check_cell_phone_number(number):
cleaned_number = strspn(number, u'+0123456789')
if not u'+' in cleane... | import logging
logger = logging.getLogger(__name__)
def strspn(source, allowed):
newchrs = []
for c in source:
if c in allowed:
newchrs.append(c)
return u''.join(newchrs)
def check_cell_phone_number(number):
cleaned_number = strspn(number, u'0123456789')
#if not u'+' in cleaned... | Use international MSISDN format according to SMPP protocol spec: 4.2.6.1.1 | Use international MSISDN format
according to SMPP protocol spec: 4.2.6.1.1
| Python | bsd-3-clause | peterayeni/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway |
22888f6731cf7e6ab0a6cb14088075cf7061d310 | sympy/interactive/ipythonprinting.py | sympy/interactive/ipythonprinting.py | """
A print function that pretty prints SymPy objects.
:moduleauthor: Brian Granger
Usage
=====
To use this extension, execute:
%load_ext sympy.interactive.ipythonprinting
Once the extension is loaded, SymPy Basic objects are automatically
pretty-printed in the terminal and rendered in LaTeX in the Qt console ... | """
A print function that pretty prints SymPy objects.
:moduleauthor: Brian Granger
Usage
=====
To use this extension, execute:
%load_ext sympy.interactive.ipythonprinting
Once the extension is loaded, SymPy Basic objects are automatically
pretty-printed in the terminal and rendered in LaTeX in the Qt console ... | Remove checks that module is loaded | Remove checks that module is loaded
| Python | bsd-3-clause | wanglongqi/sympy,meghana1995/sympy,skirpichev/omg,ga7g08/sympy,jamesblunt/sympy,Shaswat27/sympy,amitjamadagni/sympy,saurabhjn76/sympy,shikil/sympy,ga7g08/sympy,kevalds51/sympy,maniteja123/sympy,sampadsaha5/sympy,postvakje/sympy,debugger22/sympy,emon10005/sympy,farhaanbukhsh/sympy,diofant/diofant,sunny94/temp,souravsing... |
10a5f15b1a7703179edac113dcdadd6042fb29f8 | txircd/modules/cmode_s.py | txircd/modules/cmode_s.py | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "s" in chan.mode and chan.name not in user.channe... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "s" in chan.mode and chan.name not in user.channe... | Fix LIST command crashing (again) on certain input | Fix LIST command crashing (again) on certain input
| Python | bsd-3-clause | DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd |
857350154e11f09a1b4aeecd411ab41df2acf378 | tests/integration/test_crossmodel.py | tests/integration/test_crossmodel.py | import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
ch... | import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
ch... | Remove offer with model name | Remove offer with model name
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju |
6715e42b5a3e0b8b9caea853a073d1aac0495885 | phplint.py | phplint.py | import subprocess
import os
class PHPLint:
def __init__(self):
self.silent = False
def setSilentLint(self, isSilent):
self.silent = isSilent
def lint(self, path):
if os.path.isfile(path):
self.lintFile(path)
elif os.path.isdir(path):
self.lintDir(pa... | import subprocess
import os
class PHPLint:
def __init__(self):
self.silent = False
def set_silent_lint(self, is_silent):
self.silent = is_silent
def lint(self, path):
if os.path.isfile(path):
self.lint_file(path)
elif os.path.isdir(path):
self.lint_... | Change code to be compliant with PEP 8 | Change code to be compliant with PEP 8
This change camel cased functions for underscored function names and
properties.
| Python | mit | nelsonsar/phplinter |
e2bc8b6010e979a9c00851d21ee783c8e8e27a55 | adaptive/typecheck.py | adaptive/typecheck.py | # Tools for type checking
def assertListOf(lst, typ):
assert isinstance(lst, list), lst
for idx, value in enumerate(lst):
#assert isinstance(value, typ), (idx, value)
assert value is None or isinstance(value, typ), (idx, value)
return True
| # Tools for type checking
def assertListOf(lst, typ, orNone=True):
assert isinstance(lst, list), lst
if orNone:
for idx, value in enumerate(lst):
assert value is None or isinstance(value, typ), (idx, value)
else:
for idx, value in enumerate(lst):
assert isinstance(va... | Add type check helper; make typ or None optional for lists | Add type check helper; make typ or None optional for lists | Python | apache-2.0 | datawire/adaptive |
ae78e44461ec710c65479b094dcff257944e1f83 | pyof/v0x01/controller2switch/stats_request.py | pyof/v0x01/controller2switch/stats_request.py | """Query the datapath about its current state."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import ConstantTypeList, UBInt16
# Local imports
from pyof.v0x01.common.header import Header, Type
from pyof.v0x01.controller2switch.common import ... | """Query the datapath about its current state."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import BinaryData, UBInt16
# Local imports
from pyof.v0x01.common.header import Header, Type
from pyof.v0x01.controller2switch.common import StatsT... | Fix StatsRequest body type; add default values | Fix StatsRequest body type; add default values
| Python | mit | cemsbr/python-openflow,kytos/python-openflow |
490f2b1f31fb1ec99bdd09db0e3806fc070ea32a | daemon/__init__.py | daemon/__init__.py | # -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Fo... | # -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Fo... | Update package docstring for PEP number. | Update package docstring for PEP number. | Python | apache-2.0 | wting/python-daemon,eaufavor/python-daemon |
1c8674029a1f1fa4a8f9545f540402ba418bd693 | docs/generate_documentation.py | docs/generate_documentation.py | # -*- coding: utf-8 -*-
#!/usr/bin/python
import os
from subprocess import Popen, PIPE
import shutil
docs_folder_path = os.path.join(os.path.dirname(__file__))
p1 = Popen(u'sphinx-build -M html {src} {dst}'.format(
src=docs_folder_path, dst=os.path.join(docs_folder_path, u'_build')
), shell=True, stdin=PIPE, stdo... | # -*- coding: utf-8 -*-
#!/usr/bin/python3
import os
from subprocess import Popen, PIPE
import shutil
docs_folder_path = os.path.abspath(os.path.dirname(__file__))
p1 = Popen('python -m sphinx -v -b html {src} {dst}'.format(
src=docs_folder_path, dst=os.path.join(docs_folder_path, '_build')
), shell=True, stdin=P... | Fix documentation generating script to work with Python 3 | Fix documentation generating script to work with Python 3
| Python | agpl-3.0 | nabla-c0d3/sslyze |
ceee44182b24ecdc0563a9e9a6841993d1978d0c | setup.py | setup.py | from distutils.core import setup
setup(
name='aJohnShots',
version="1.0.0",
description='Python module/library for saving Security Hash Algorithms into JSON format.',
author='funilrys',
author_email='contact@funilrys.com',
license='GPL-3.0 https://opensource.org/licenses/GPL-3.0',
url='http... | from distutils.core import setup
setup(
name='a_john_shots',
version="1.0.0",
description='Python module/library for saving Security Hash Algorithms into JSON format.',
long_description=open('README').read(),
author='funilrys',
author_email='contact@funilrys.com',
license='GPL-3.0 https://o... | Rename + add long_description + update keywords | Rename + add long_description + update keywords
| Python | mit | funilrys/A-John-Shots |
5ad5bcef00c807dadd9c829f1eb459c4cc73cb5f | src/books/models.py | src/books/models.py | from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
year = models.DateTimeField('year published',
help_text="Please use the following for... | from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
edition = models.SmallIntegerField(default=1)
author = models.CharField(max_length=200)
year = models.DateTimeField('year publis... | Refactor some book model variables | Refactor some book model variables
Add an edition field, help texts to some of the fields.
Change behaviour of the __str__ method to be more informative.
| Python | mit | melkisedek/sen_project,melkisedek/sen_project,melkisedek/sen_project |
febb5d9890b074985ca99f05c5b8ffc2572d2652 | apps/posters/forms.py | apps/posters/forms.py | # -*- coding: utf-8 -*-
from django import forms
from apps.posters.models import Poster
class AddPosterForm(forms.ModelForm):
when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'}))
display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(... | # -*- coding: utf-8 -*-
from django import forms
from apps.posters.models import Poster
class AddPosterForm(forms.ModelForm):
display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'}))
display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(a... | Remove event start field from form | Remove event start field from form
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
6f20554c2a7b0223b2291227b67fb3ede003f525 | setup.py | setup.py | #!/usr/bin/env python
"""
Setup script
"""
import os
import sys
from distutils.core import setup
from fedwatch import __version__
setup(
name = 'fedwatch',
description = 'Module for creating simple scripts reacting to fedmsg messages',
version = __version__,
license = 'LGPLv2+',
py_modules = ['fed... | #!/usr/bin/env python
"""
Setup script
"""
import os
import sys
from distutils.core import setup
from fedwatch import __version__
setup(
name = 'fedwatch',
description = 'Module for creating simple scripts reacting to fedmsg messages',
version = __version__,
license = 'LGPLv2+',
py_modules = ['fed... | Add fedwatch-cli as installed script | Add fedwatch-cli as installed script
| Python | lgpl-2.1 | pombredanne/fedwatch,sochotnicky/fedwatch,pombredanne/fedwatch,mizdebsk/fedwatch,sochotnicky/fedwatch,mizdebsk/fedwatch |
88451dba53aaf2257ece516d027bdbb0449cb8b4 | globus_cli/commands/task/event_list.py | globus_cli/commands/task/event_list.py | import click
from globus_cli.parsing import common_options, task_id_arg
from globus_cli.helpers import outformat_is_json, print_table
from globus_cli.services.transfer import print_json_from_iterator, get_client
@click.command('event-list', help='List Events for a given Task')
@common_options
@task_id_arg
def task_... | import click
from globus_cli.parsing import common_options, task_id_arg
from globus_cli.helpers import outformat_is_json, print_table
from globus_cli.services.transfer import print_json_from_iterator, get_client
@click.command('event-list', help='List Events for a given Task')
@common_options
@task_id_arg
@click.op... | Add --limit and filtering options to task event-list | Add --limit and filtering options to task event-list
| Python | apache-2.0 | globus/globus-cli,globus/globus-cli |
1d83021ab395804020d1907db7b6db897dbd1efd | bin/upload_version.py | bin/upload_version.py | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps... | #!python
import os
import sys
import json
import requests
import subprocess
def capture_output(command):
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
return proc.stdout.read()
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
... | Update upload script to include checksums | Update upload script to include checksums
| Python | bsd-2-clause | moritz9/redash,pubnative/redash,ninneko/redash,hudl/redash,pubnative/redash,vishesh92/redash,imsally/redash,easytaxibr/redash,jmvasquez/redashtest,guaguadev/redash,vishesh92/redash,jmvasquez/redashtest,easytaxibr/redash,44px/redash,amino-data/redash,chriszs/redash,jmvasquez/redashtest,jmvasquez/redashtest,amino-data/re... |
60e208200970201f37b0eb4f85b6008681e1f35d | tasks.py | tasks.py | """
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser
from invoke import task, run
DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')
@task
def docs(output='html', rebuild=False, show=True):
"""Build the docs and show them in default web browser."""
build_cmd ... | """
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser
import sys
from invoke import task, run
DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')
@task
def docs(output='html', rebuild=False, show=True):
"""Build the docs and show them in default web browser."""
... | Fix to showing generated docs on OSX | Fix to showing generated docs on OSX
| Python | bsd-3-clause | Xion/callee |
af7122220447b1abe771f37400daeb4370603dd4 | collection_pipelines/core.py | collection_pipelines/core.py | import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
rais... | import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
rais... | Add base class for output pipeline processors | Add base class for output pipeline processors
| Python | mit | povilasb/pycollection-pipelines |
93358a04380f427f3ac1cea84689a430bcb0c883 | jenkins/management/commands/import_jenkinsserver.py | jenkins/management/commands/import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args ... | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args ... | Make the command-line tool pass the right parameters. | Make the command-line tool pass the right parameters.
| Python | mit | timrchavez/capomastro,caio1982/capomastro,caio1982/capomastro,caio1982/capomastro,timrchavez/capomastro |
f93555f1039857d1c4ba06d3f5a95810f1f1d26e | devp2p/__init__.py | devp2p/__init__.py | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
try:
_dist = get_distribution('devp2p')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
... | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_d... | Use version extraction code from pyethapp / pyethereum | Use version extraction code from pyethapp / pyethereum | Python | mit | ethereum/pydevp2p,ms83/pydevp2p |
4dd28beddc2df9efeef798491d1963800113f801 | django_bootstrap_calendar/models.py | django_bootstrap_calendar/models.py | # -*- coding: utf-8 -*-
__author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warni... | # -*- coding: utf-8 -*-
__author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warni... | Allow `css_class` to have blank value. | Allow `css_class` to have blank value.
Currently the default value for the `css_class` field (name `Normal`)
has the value of a blank string. To allow the value to be used
`blank=True` must be set.
| Python | bsd-3-clause | sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar |
cea4e45dc95310993e3b23ceadf83cbda810f536 | EasyEuler/commands/list.py | EasyEuler/commands/list.py | import click
from tabulate import tabulate
from EasyEuler import data
@click.command()
@click.option('--sort', '-s', type=click.Choice(['id', 'difficulty']),
default='id', help='Sort the list by problem attribute.')
def cli(sort):
""" Lists all available problems. """
problems = sorted(data.pr... | import click
from tabulate import tabulate
from EasyEuler import data
@click.command()
@click.option('--sort', '-s', type=click.Choice(['id', 'difficulty']),
default='id', help='Sort the list by problem attribute.')
def cli(sort):
""" Lists all available problems. """
problems = sorted(data.pr... | Add percentage sign to difficulty | Add percentage sign to difficulty
| Python | mit | Encrylize/EasyEuler |
13e141c1686198deaccc6c38d14cdbde8c4c8fb4 | passpie/_compat.py | passpie/_compat.py | import os
import sys
try:
from shutil import which as _which
except ImportError:
from distutils.spawn import find_executable as _which
def which(binary):
path = _which(binary)
if path:
realpath = os.path.realpath(path)
return realpath
return None
def is_python2():
return sys.... | import os
import sys
try:
from shutil import which as _which
except ImportError:
from distutils.spawn import find_executable as _which
try:
basestring
except NameError:
basestring = str
def which(binary):
path = _which(binary)
if path:
realpath = os.path.realpath(path)
return real... | Add basestring py2/py3 to compat | Add basestring py2/py3 to compat
| Python | mit | marcwebbie/passpie,eiginn/passpie,scorphus/passpie,marcwebbie/passpie,eiginn/passpie,scorphus/passpie |
8259a733e1f039cea55cfc5aad7d69e0fb37c43c | tests.py | tests.py | from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.asse... | from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.asse... | Add test that validates method call | Add test that validates method call
| Python | mit | mdsrosa/money-conversion-py |
0c2dc7714f2dbb1140f8c03b2181f1fd15c434bf | djlint/parsers.py | djlint/parsers.py | import ast
import os
class Parser(object):
def __init__(self, repo_path):
if not os.path.isabs(repo_path):
raise ValueError('Repository path is not absolute: %s' % repo_path)
self.repo_path = repo_path
def walk(self):
for root, dirnames, filenames in os.walk(self.repo_pat... | import ast
import os
class Parser(object):
"""
Find all *.py files inside `repo_path` and parse its into ast nodes.
If file has syntax errors SyntaxError object will be returned except
ast node.
"""
def __init__(self, repo_path):
if not os.path.isabs(repo_path):
raise Val... | Add docstrings to Parser class | Add docstrings to Parser class
| Python | isc | alfredhq/djlint |
b91b0d667f64960fd1f07b7dc42290f287ab4c5b | scripts/endpoints_json.py | scripts/endpoints_json.py | #!/usr/bin/env python3
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
def __init__(self):
pass
def find(self):
page = requests.get(self._page)
... | #!/usr/bin/env python3
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like... | Add default headers, fix output | Add default headers, fix output
| Python | mit | thatJavaNerd/JRAW,ccrama/JRAW,fbis251/JRAW,fbis251/JRAW,fbis251/JRAW,thatJavaNerd/JRAW,Saketme/JRAW,hzsweers/JRAW,hzsweers/JRAW,ccrama/JRAW,thatJavaNerd/JRAW,ccrama/JRAW,Saketme/JRAW,hzsweers/JRAW,Saketme/JRAW |
0a119e379150a8c1bbbd412d2b0734dd9748cf77 | windows_install/omni-config-setup.py | windows_install/omni-config-setup.py | from distutils.core import setup
import py2exe
import sys
setup(console=['..\src\omni-configure.py'],
name="omni-configure",
py_modules=['sfa','ConfigParser','logging','optparse',
'os','sys','string',
're','platform','shutil','zipfile','logging','subprocess']... | from distutils.core import setup
import py2exe
import sys
setup(console=['..\src\omni-configure.py', '..\examples/readyToLogin.py', '..\src\clear-passphrases.py'],
name="omni-configure",
py_modules=['sfa','ConfigParser','logging','optparse',
'os','sys','string',
... | Add readyToLogin.py and clear-passphrases.py to setup.py script. | Add readyToLogin.py and clear-passphrases.py to setup.py script.
| Python | mit | ahelsing/geni-tools,plantigrade/geni-tools,tcmitchell/geni-tools,tcmitchell/geni-tools,ahelsing/geni-tools,plantigrade/geni-tools |
088e30bd675e2102f62493fd295808a7a48ae615 | project/functions/main.py | project/functions/main.py | # Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | import base64, json
from google.cloud import datastore
from fetch_trends import get_updated_daily_data
from database_updates import update_investment_database
def update(event, context):
eventdata = event["data"]
decoded = base64.b64decode(eventdata)
data = json.loads(decoded)
start_date = int(dat... | Update entry point for cloud function data fetch | Update entry point for cloud function data fetch
| Python | apache-2.0 | googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks |
e229779753f3c5f44319d882d19feab324abe119 | api/migrations/0011_user_preferences_update_troposphere_user.py | api/migrations/0011_user_preferences_update_troposphere_user.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-09-28 19:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0010_sitemetadata_site_footer_link'),
]
operations = [
# migrations.RunSQL(
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-09-28 19:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0010_sitemetadata_site_footer_link'),
]
# These one-off operations are no longer nece... | Add note after testing on all three 'valid' environment formats: (Clean, CyVerse, Jetstream) | Add note after testing on all three 'valid' environment formats: (Clean, CyVerse, Jetstream)
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend |
27844c3a386616834f92cd34f4790b3117e7ac05 | test_utils/templatetags/utils.py | test_utils/templatetags/utils.py | from django import template
register = template.Library()
def parse_ttag(token):
bits = token.split_contents()
tags = {}
possible_tags = ['as', 'for', 'limit', 'exclude']
for index, bit in enumerate(bits):
if bit.strip() in possible_tags:
tags[bit.strip()] = bits[index+1]
retu... | from django import template
def parse_ttag(token, possible_tags=['as', 'for', 'limit', 'exclude']):
"""
A function to parse a template tag.
Pass in the token to parse, and a list of keywords to look for.
It sets the name of the tag to 'tag_name' in the hash returned.
Default list of keywords is::... | Add some hotness to the parse_ttags function. Now allows you to pass a custom list of things to parse, much nicer. | Add some hotness to the parse_ttags function. Now allows you to pass a custom list of things to parse, much nicer. | Python | mit | frac/django-test-utils,ericholscher/django-test-utils,frac/django-test-utils,acdha/django-test-utils,ericholscher/django-test-utils,acdha/django-test-utils |
fd6f45aa96599a90d9ece06ffa71d8612f9f64a7 | run_tests.py | run_tests.py | #!/usr/bin/env python
import os, sys, re, shutil
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.core.management import call_command
names_prefix = 'tests.tests' if django.VERSION >= (1, 6) else 'tests'
names = next((a for a in sys.argv[1:] if not a.startswith('-')), None)
if names ... | #!/usr/bin/env python
import os, sys, re, shutil
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.core.management import call_command
names_prefix = 'tests.tests' if django.VERSION >= (1, 6) else 'tests'
names = next((a for a in sys.argv[1:] if not a.startswith('-')), None)
if names ... | Make makemigrations verbose in ./runtests.py -v | Make makemigrations verbose in ./runtests.py -v
| Python | bsd-3-clause | whyflyru/django-cacheops,Suor/django-cacheops,andwun/django-cacheops,rutube/django-cacheops,bourivouh/django-cacheops,ErwinJunge/django-cacheops,LPgenerator/django-cacheops |
4e2fd5e78922eea0f6a65afd6d50ed4b0f03448c | tests/blueprints/board/topic_moderation_base.py | tests/blueprints/board/topic_moderation_base.py | """
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.board.models.topic import Topic
from testfixtures.board import create_board, create_category, create_topic
from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_t... | """
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.board.models.topic import Topic
from byceps.services.party import settings_service as party_settings_service
from testfixtures.board import create_board, create_category, create_topic
from tests.b... | Configure board ID as party setting for board tests | Configure board ID as party setting for board tests
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps |
06d3aeda83e54edf7a2b972b9b44ae9bfa7f7178 | icekit/project/hosts.py | icekit/project/hosts.py | from django_hosts import patterns, host
host_patterns = patterns(
'',
host(r'www', 'icekit.project.urls', name='www'),
host(r'api', 'icekit.api.urls', name='api'),
)
| from django_hosts import patterns, host
from django.conf import settings
host_patterns = patterns(
'',
host(r'www', settings.ROOT_URLCONF, name='www'),
host(r'api', 'icekit.api.urls', name='api'),
)
| Use project ROOT_URLCONF on default host, not hardcoded urls. | Use project ROOT_URLCONF on default host, not hardcoded urls.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
6ee7d39c7c39a018a71cbb028dd847e3da521263 | views.py | views.py | from rest_framework import viewsets, permissions
from rest_framework_word_filter import FullWordSearchFilter
from quotedb.models import Quote
from quotedb.permissions import IsOwnerOrReadOnly
from quotedb.serializers import QuoteSerializer
class QuoteViewSet(viewsets.ModelViewSet):
"""
This viewset automati... | from rest_framework import viewsets, permissions
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework_word_filter import FullWordSearchFilter
from quotedb.models import Quote
from quotedb.permissions import IsOwnerOrReadOnly
from quotedb.serializers import Q... | Add route to get random quote | Add route to get random quote
| Python | mit | kfdm/django-qdb,kfdm/django-qdb |
4208538a2b7c5f2280f67520a73bd87b74de26dd | scripts/getsent.py | scripts/getsent.py | #!/usr/bin/python
import sys
import depio
sentnum = int(sys.argv[2])
fnames = [sys.argv[1]]
for fname in fnames:
sents = list(depio.depread(fname))
i=0
out = open("%d.%s" % (sentnum,fname),'w')
for outl in sents[sentnum]:
out.write('\t'.join(outl) + '\n')
break
out.close()
| #!/usr/bin/python
import sys
import depio
sentnum = int(sys.argv[2])
fnames = [sys.argv[1]]
for fname in fnames:
sents = list(depio.depread(fname))
i=0
out = open("%d.%s" % (sentnum,fname),'w')
for outl in sents[sentnum]:
out.write('\t'.join(outl) + '\n')
out.write('\n')
out.close()
| Fix script to output new line at end of file | Fix script to output new line at end of file
| Python | apache-2.0 | habeanf/yap,habeanf/yap |
78e7fd90db429793c2b4ceee34f5296484bb0fd4 | run_tests.py | run_tests.py | #!/usr/bin/env python
# This file is closely based on tests.py from matplotlib
#
# This allows running the matplotlib tests from the command line: e.g.
#
# $ python tests.py -v -d
#
# The arguments are identical to the arguments accepted by nosetests.
#
# See https://nose.readthedocs.org/ for a detailed description o... | #!/usr/bin/env python
import sys
import pytest
if __name__ == '__main__':
# show output results from every test function
args = ['-v']
# show the message output for skipped and expected failure tests
args.append('-rxs')
args.extend(sys.argv[1:])
# call pytest and exit with the return code from ... | Use pytest to run tests | TST: Use pytest to run tests
| Python | bsd-3-clause | NSLS-II/metadatastore,hhslepicka/metadatastore,arkilic/metadatastore,arkilic/metadatastore,ericdill/databroker,NSLS-II/metadatastore,ericdill/databroker,tacaswell/metadataStore,tacaswell/metadataStore,hhslepicka/metadatastore |
e6206c2bdacfbd2632beb6ed56ccb6856d299e08 | tests/test_suggestion_fetcher.py | tests/test_suggestion_fetcher.py | import unittest2
from google.appengine.ext import testbed
from models.account import Account
from models.suggestion import Suggestion
from helpers.suggestions.suggestion_fetcher import SuggestionFetcher
class TestEventTeamRepairer(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
... | import unittest2
from google.appengine.ext import testbed
from models.account import Account
from models.suggestion import Suggestion
from helpers.suggestions.suggestion_fetcher import SuggestionFetcher
class TestSuggestionFetcher(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
... | Fix class name of test. | Fix class name of test.
| Python | mit | phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeuge... |
d65643e1bb74210a458b370aca5343f5c7059022 | wm_metrics/period.py | wm_metrics/period.py | """Representation of a period of time."""
class Period(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return "%s-%s" % (self.start, self.end)
| """Representation of a period of time."""
class Period(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return "%s-%s" % (self.start, self.end)
def __eq__(self, other):
return ((other.start == self.start) and
... | Add __eq__ method to Period object | Add __eq__ method to Period object
Ultimately we probably want to reuse Python objects
like timestamps.
| Python | mit | Commonists/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics |
f3a8c5504d75bde7fe66aeb736f4d45aa24bf6f7 | workbench/request.py | workbench/request.py | """Helpers for WebOb requests and responses."""
import webob
def webob_to_django_response(webob_response):
"""Returns a django response to the `webob_response`"""
from django.http import HttpResponse
django_response = HttpResponse(
webob_response.app_iter,
content_type=webob_response.cont... | """Helpers for WebOb requests and responses."""
import webob
def webob_to_django_response(webob_response):
"""Returns a django response to the `webob_response`"""
from django.http import HttpResponse
django_response = HttpResponse(
webob_response.app_iter,
content_type=webob_response.cont... | Delete unused webob conversion method | Delete unused webob conversion method
| Python | apache-2.0 | nagyistoce/edx-XBlock,edx-solutions/xblock-sdk,Pilou81715/hackathon_edX,EDUlib/XBlock,jamiefolsom/xblock-sdk,nagyistoce/edx-xblock-sdk,edx/xblock-sdk,lovehhf/XBlock,lovehhf/xblock-sdk,mitodl/XBlock,lovehhf/xblock-sdk,lovehhf/xblock-sdk,jamiefolsom/xblock-sdk,edx/XBlock,cpennington/XBlock,nagyistoce/edx-xblock-sdk,edx/X... |
fe3e43e4d894a0d7009dcbfcafb2546d12cb6296 | vumi/middleware/session_length.py | vumi/middleware/session_length.py | # -*- test-case-name: vumi.middleware.tests.test_session_length -*-
import time
from twisted.internet.defer import inlineCallbacks, returnValue
from vumi.message.TransportUserMessage import SESSION_NEW, SESSION_CLOSE
from vumi.middleware.base import BaseMiddleware
from vumi.persist.txredis_manager import TxRedisMana... | # -*- test-case-name: vumi.middleware.tests.test_session_length -*-
import time
from twisted.internet.defer import inlineCallbacks, returnValue
from vumi.message import TransportUserMessage
from vumi.middleware.base import BaseMiddleware
from vumi.persist.txredis_manager import TxRedisManager
class SessionLengthMi... | Fix session event variable import. | Fix session event variable import.
| Python | bsd-3-clause | vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi,TouK/vumi |
a2a1e53d289d39d4df6c6552f89602e96e4775c6 | django_ses/tests/__init__.py | django_ses/tests/__init__.py | from backend import SESBackendTest
from commands import SESCommandTest
from stats import StatParsingTest
from configuration import SettingsImportTest
| from .backend import *
from .commands import *
from .stats import *
from .configuration import *
| Make sure to load *all* tests | Make sure to load *all* tests
| Python | mit | smaato/django-ses,django-ses/django-ses,ticosax/django-ses,piotrbulinski/django-ses-backend,ticosax/django-ses,brutasse/django-ses,grumbler/django-ses,brutasse/django-ses,django-ses/django-ses,grumbler/django-ses,350dotorg/django-ses,smaato/django-ses |
1607a12c80b09616f7607e167de8ebb720fb0f3d | demo.py | demo.py |
from __future__ import print_function
import pynbs
my_file = pynbs.read('demo_song.nbs')
print(my_file.header.song_length)
print(my_file.header.description)
print(my_file.notes)
print(my_file.layers)
print(my_file.instruments)
for tick, chord in my_file.song():
print(tick, [note.key for note ... |
from __future__ import print_function
import pynbs
# read file
my_file = pynbs.read('demo_song.nbs')
print(my_file.header.song_length)
print(my_file.header.description)
print(my_file.notes)
print(my_file.layers)
print(my_file.instruments)
for tick, chord in my_file.song():
print(tick, [not... | Add examples for editing and saving file | Add examples for editing and saving file
| Python | mit | fizzy81/pynbs |
7a7059a28a43e736d963f83b4ea42b08e9200691 | fellowms/tests.py | fellowms/tests.py | from django.test import TestCase
from .models import Event
class EventTestCase(TestCase):
def setUp(self):
events = (
{
"fellow": 1,
"category": "O",
"name": "CW16",
"url": "http://www.software.ac.uk/cw16",
... | from django.test import TestCase
from .models import Fellow, Event
class FellowTestCase(TestCase):
def setUp(self):
fellows = (
{
"forenames": "A",
"surname": "C",
"affiliation": "King's College",
"research_area... | Add test for fellow model | Add test for fellow model
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat |
31ddb8ec0cba2afd4787906c6b6e299df33a8714 | ldapdb/__init__.py | ldapdb/__init__.py | # -*- coding: utf-8 -*-
# This software is distributed under the two-clause BSD license.
# Copyright (c) The django-ldapdb project
from django.conf import settings
import ldap.filter
def escape_ldap_filter(value):
return ldap.filter.escape_filter_chars(str(value))
# Legacy single database support
if hasattr(set... | # -*- coding: utf-8 -*-
# This software is distributed under the two-clause BSD license.
# Copyright (c) The django-ldapdb project
from django.conf import settings
import sys
import ldap.filter
def escape_ldap_filter(value):
if sys.version_info[0] < 3:
text_value = unicode(value)
else:
text_... | Fix encoding issue with legacy python (2.7) | Fix encoding issue with legacy python (2.7)
| Python | bsd-2-clause | django-ldapdb/django-ldapdb,jlaine/django-ldapdb |
b1380edda27c021c67cfd686a30410c15c1f023e | scoring_engine/engine/execute_command.py | scoring_engine/engine/execute_command.py | from scoring_engine.celery_app import celery_app
from billiard.exceptions import SoftTimeLimitExceeded
import subprocess
from scoring_engine.logger import logger
@celery_app.task(name='execute_command', soft_time_limit=30)
def execute_command(job):
output = ""
logger.info("Running cmd for " + str(job))
t... | from scoring_engine.celery_app import celery_app
from billiard.exceptions import SoftTimeLimitExceeded
import subprocess
from scoring_engine.logger import logger
@celery_app.task(name='execute_command', soft_time_limit=30)
def execute_command(job):
output = ""
# Disable duplicate celery log messages
if l... | Disable duplicate celery log messages | Disable duplicate celery log messages
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
9216224d96770e32778c46b4959731ac70cb2c88 | london_commute_alert.py | london_commute_alert.py | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... | Move from python anywhere to webfaction | Move from python anywhere to webfaction
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit |
7a59999961b67dbd480c80a4a4f95fa6738b2949 | day-20/solution.py | day-20/solution.py | from __future__ import print_function
def findFirst(data, target):
for idx, value in enumerate(data):
if value >= target:
return idx
return None
target = 34000000
# Target is achieved at itself/10, so reasonable upper bound.
upperbound = target // 10
# Use a varation of Erathostenes' si... | from __future__ import print_function
def findFirst(data, target):
return next(idx for idx, value in enumerate(data) if value >= target)
target = 34000000
# Target is achieved at itself/10, so reasonable upper bound.
upperbound = target // 10
# Use a varation of Erathostenes' sieve to compute the results
sieve1... | Improve getting the first valid value. | Improve getting the first valid value.
| Python | mit | bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv... |
61bbfbcdd2b23b24233ea6543cbfc880b6b01ea9 | husk/decorators.py | husk/decorators.py | from argparse import ArgumentParser
def cached_property(func):
cach_attr = '_{}'.format(func.__name__)
@property
def wrap(self):
if not hasattr(self, cach_attr):
value = func(self)
if value is not None:
setattr(self, cach_attr, value)
return getattr... | from argparse import ArgumentParser
def cached_property(func):
cach_attr = '_{}'.format(func.__name__)
@property
def wrap(self):
if not hasattr(self, cach_attr):
value = func(self)
if value is not None:
setattr(self, cach_attr, value)
return getattr... | Add `handle_raw` method that does not catch all upstream exceptions | Add `handle_raw` method that does not catch all upstream exceptions | Python | bsd-2-clause | husk/husk |
8e2a42369228f3d19b046a610c93de4bec06d5bf | avocado/core/structures.py | avocado/core/structures.py | try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
class ChoicesDict(OrderedDict):
"OrdereDict that yields the key and value on iteration."
def __iter__(self):
iterator = super(ChoicesDict, self).__iter__()
for key in iterator:
... | try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
REPR_OUTPUT_SIZE = 20
class ChoicesDict(OrderedDict):
"OrdereDict that yields the key and value on iteration."
def __iter__(self):
iterator = super(ChoicesDict, self).__iter__()
for key ... | Add __repr__ to ChoicesDict structure | Add __repr__ to ChoicesDict structure | Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado |
9af50ecde67e593533898040e63e6a456fc16da5 | tests/test_style.py | tests/test_style.py | import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
flake8([])
except SystemExit as e:
if e.code != 0:
self.fa... | import logging
import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
logger = logging.getLogger('flake8')
logger.setLevel(logging.ERROR)
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
... | Decrease noise from code-style test | Decrease noise from code-style test
| Python | mit | ministryofjustice/django-zendesk-tickets,ministryofjustice/django-zendesk-tickets |
2b9828541066ec4adb09f80fe29468cb0ce2a1e0 | readthedocs/core/management/commands/build_files.py | readthedocs/core/management/commands/build_files.py | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from projects.models import ImportedFile
from builds.models import Version
log = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''\
Delete and re-create ImportedFile ... | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from projects.models import ImportedFile
from builds.models import Version
log = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''\
Delete and re-create ImportedFile ... | Add ability to index specific project. | Add ability to index specific project.
| Python | mit | SteveViss/readthedocs.org,takluyver/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,stevepiercy/readthedocs.org,fujita-shintaro/readthedocs.org,espdev/readthedocs.org,royalwang/readthedocs.org,raven47git/readthedocs.org,royalwang/readthedocs.org,agjohnson/readthedocs.org,pombredanne/readthedocs.... |
93ba327a3198c587d791aeb1d285f6e7f339df20 | app/grandchallenge/archives/models.py | app/grandchallenge/archives/models.py | from django.db import models
from grandchallenge.core.models import UUIDModel
from grandchallenge.cases.models import Image
from grandchallenge.patients.models import Patient
class Archive(UUIDModel):
"""
Model for archive. Contains a collection of images
"""
name = models.CharField(max_length=255, d... | from django.db import models
from grandchallenge.core.models import UUIDModel
from grandchallenge.cases.models import Image
from grandchallenge.patients.models import Patient
class Archive(UUIDModel):
"""
Model for archive. Contains a collection of images
"""
name = models.CharField(max_length=255, d... | Add args and kwargs to delete method | Add args and kwargs to delete method
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
056c2922bd8304d054915bca10c9510148d96398 | isAccessedInFunction.py | isAccessedInFunction.py | #! /usr/bin/env python
import subprocess, sys, re
try:
classfile = sys.argv[1]
functionRE = re.compile(sys.argv[2])
toSearch = re.compile(sys.argv[3])
except (re.error, IndexError) as e:
print("""usage: %s classfile functionregex searchregex
Will disassemble classfile, then search for searchregex in... | #! /usr/bin/env python
import subprocess, sys, re
try:
classfile = sys.argv[1]
functionRE = re.compile(sys.argv[2])
toSearch = re.compile(sys.argv[3])
except (re.error, IndexError) as e:
print("""usage: %s classfile functionregex searchregex
Will disassemble classfile, then search for searchregex in... | Improve detection of function start. | Improve detection of function start.
| Python | apache-2.0 | FAU-Inf2/AuDoscore,FAU-Inf2/AuDoscore |
f1754acb58fe9088e90692f5200babff3fa49bdf | src/zeit/cms/tests/test_celery.py | src/zeit/cms/tests/test_celery.py | import datetime
import zeit.cms.celery
import zeit.cms.testing
@zeit.cms.celery.CELERY.task()
def task(context, datetime):
pass
class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase):
def test_registering_task_without_json_serializable_arguments_raises(self):
now = datetime.datetime.now()
w... | import datetime
import zeit.cms.celery
import zeit.cms.testing
@zeit.cms.celery.CELERY.task()
def dummy_task(context, datetime):
"""Dummy task to test our framework."""
class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase):
"""Testing ..celery.TransactionAwareTask."""
def test_registering_task_without... | Improve naming and add docstrings. | ZON-3409: Improve naming and add docstrings.
| Python | bsd-3-clause | ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms |
ea287daca69d0385c2792cd0021a0b1a23fb912b | helpers/datadog_reporting.py | helpers/datadog_reporting.py | import os
import yaml
from dogapi import dog_stats_api, dog_http_api
def setup():
"""
Initialize connection to datadog during locust startup.
Reads the datadog api key from (in order):
1) An environment variable named DATADOG_API_KEY
2) the DATADOG_API_KEY of a yaml file at
2a) the enviro... | import os
import yaml
from dogapi import dog_stats_api, dog_http_api
def setup():
"""
Initialize connection to datadog during locust startup.
Reads the datadog api key from (in order):
1) An environment variable named DATADOG_API_KEY
2) the DATADOG_API_KEY of a yaml file at
2a) the enviro... | Fix reading of API key from yaml file. | Fix reading of API key from yaml file.
| Python | apache-2.0 | edx/edx-load-tests,edx/edx-load-tests,edx/edx-load-tests,edx/edx-load-tests |
8548822ed0755a17cc3dc95cac582683a1ffb11c | linguist/models/base.py | linguist/models/base.py | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | Rename content field to field_value. | Rename content field to field_value.
| Python | mit | ulule/django-linguist |
b7fd4b9db379fc9bc28f22f6608c804e9f08e181 | oonib/input/handlers.py | oonib/input/handlers.py | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config
class InputDescHandler(OONIBHandler):
def get(self, inputID):
#XXX return the input descriptor
# see oonib.md in ooni-spec
bn = os.path.basename(inputID) + ".desc"
try:
... | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config, log
class InputDescHandler(OONIBHandler):
def get(self, inputID):
bn = os.path.basename(inputID) + ".desc"
try:
f = open(os.path.join(config.main.input_dir, bn))
... | Implement input API as spec'd in oonib.md | Implement input API as spec'd in oonib.md
| Python | bsd-2-clause | DoNotUseThisCodeJUSTFORKS/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend,dstufft/ooni-backend |
8ecc24ab865ff9dec647fe69d78af0a63f0a902a | nap/rest/models.py | nap/rest/models.py | from __future__ import unicode_literals
from .. import http
from .publisher import Publisher
from django.db import transaction
from django.shortcuts import get_object_or_404
class ModelPublisher(Publisher):
'''A Publisher with useful methods to publish Models'''
@property
def model(self):
'''By... | from __future__ import unicode_literals
from .. import http
from ..shortcuts import get_object_or_404
from .publisher import Publisher
from django.db import transaction
class ModelPublisher(Publisher):
'''A Publisher with useful methods to publish Models'''
@property
def model(self):
'''By defa... | Use our own get_object_or_404 for ModelPublisher.get_object | Use our own get_object_or_404 for ModelPublisher.get_object
| Python | bsd-3-clause | MarkusH/django-nap,limbera/django-nap |
1599d4ed14fb3d7c7e551c9f6ce3f86d9df17cbd | mammoth/writers/html.py | mammoth/writers/html.py | from __future__ import unicode_literals
from .abc import Writer
import cgi
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
attribute_string = _gen... | from __future__ import unicode_literals
from xml.sax.saxutils import escape
from .abc import Writer
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
... | Use xml.sax.saxutils.escape instead of deprecated cgi.escape | Use xml.sax.saxutils.escape instead of deprecated cgi.escape
```
/usr/local/lib/python3.6/dist-packages/mammoth/writers/html.py:34: DeprecationWarning: cgi.escape is deprecated, use html.escape instead
return cgi.escape(text, quote=True)
```
| Python | bsd-2-clause | mwilliamson/python-mammoth |
bb190d54324e15ed6ce99845047228eaef5e57cb | test_core.py | test_core.py | #!/usr/bin/env python
from ookoobah import core
from ookoobah import utils
game = core.Game()
utils.populate_grid_from_string(game.grid, """
######
#>..\#
#.#..#
#....#
#.\./#
######
""")
game.start()
for n in range(10):
print utils.dump_grid_to_string(game.grid, game.ball)
game.step... | #!/usr/bin/env python
from ookoobah import core
from ookoobah import utils
game = core.Game()
utils.populate_grid_from_string(game.grid, """
######
#>..\#
#.#..#
#....#
#.\./#
######
""")
game.start()
print "hit <enter> to render next; ^C to abort"
while True:
print utils.dump_grid_to_st... | Make the core dumper interactive | test: Make the core dumper interactive
| Python | mit | vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah |
7f2d9b94bdcbfb90870591d7cb497bb0aa2ac069 | test/test_yeast.py | test/test_yeast.py | import unittest
from yeast_harness import *
class TestYeast(unittest.TestCase):
def test_single_c_source(self):
mk = Makefile(
spores=SporeFile(
sources=CSourceFile('tree'),
products='static_lib',
path='tree'),
name='Makefile')
... | import unittest
from yeast_harness import *
class TestYeast(unittest.TestCase):
def test_single_c_source(self):
mk = Makefile(
spores=SporeFile(
sources=CSourceFile('tree'),
products='static_lib',
path='tree'),
name='Makefile')
... | Create initial test case for large tree | Create initial test case for large tree
| Python | mit | sjanhunen/yeast,sjanhunen/moss,sjanhunen/gnumake-molds,sjanhunen/moss |
77d0fe3daec4f6e4f9166dcd32943b21384a2073 | tests/test_core.py | tests/test_core.py | from grazer.core import crawler
from bs4 import BeautifulSoup
def test_extract_links():
text = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were... | from grazer.core import crawler
from bs4 import BeautifulSoup
def test_extract_links():
text = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were... | Test to validate trimming scenario | Test to validate trimming scenario
| Python | mit | CodersOfTheNight/verata |
fdc23d97064220e1042bcf7a7cb9714f476c4219 | busstops/management/commands/import_operators.py | busstops/management/commands/import_operators.py | """
Usage:
./manage.py import_operators < NOC_db.csv
"""
from busstops.management.import_from_csv import ImportFromCSVCommand
from busstops.models import Operator
class Command(ImportFromCSVCommand):
@staticmethod
def get_region_id(region_id):
if region_id in ('ADMIN', 'Admin', ''):
... | """
Usage:
./manage.py import_operators < NOC_db.csv
"""
from busstops.management.import_from_csv import ImportFromCSVCommand
from busstops.models import Operator
class Command(ImportFromCSVCommand):
@staticmethod
def get_region_id(region_id):
if region_id in ('ADMIN', 'Admin', ''):
... | Stop importing clearly duplicate operators (like the First Manchester operator without a name) | Stop importing clearly duplicate operators (like the First Manchester operator without a name)
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk |
4f27be336a58d0bba66a4f7ab57126d9dd734ab9 | talks/views.py | talks/views.py | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | Revert "Temporarily make talks visible only to committee" | Revert "Temporarily make talks visible only to committee"
This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web |
2161910a53604bdc48027c5c4e71f9af4228cbaa | keras/backend/common.py | keras/backend/common.py | import numpy as np
# the type of float to use throughout the session.
_FLOATX = 'float32'
_EPSILON = 10e-8
def epsilon():
return _EPSILON
def set_epsilon(e):
global _EPSILON
_EPSILON = e
def floatx():
return _FLOATX
def set_floatx(floatx):
global _FLOATX
if floatx not in {'float32', 'fl... | import numpy as np
# the type of float to use throughout the session.
_FLOATX = 'float32'
_EPSILON = 10e-8
def epsilon():
return _EPSILON
def set_epsilon(e):
global _EPSILON
_EPSILON = e
def floatx():
return _FLOATX
def set_floatx(floatx):
global _FLOATX
if floatx not in {'float32', 'fl... | Fix floatx encoding on Python3 | Fix floatx encoding on Python3 | Python | apache-2.0 | keras-team/keras,nebw/keras,daviddiazvico/keras,kemaswill/keras,DeepGnosis/keras,keras-team/keras,dolaameng/keras,relh/keras,kuza55/keras |
ce42ab724ad8a76dd04e24e4df6d20d96255989f | kitchen/lib/__init__.py | kitchen/lib/__init__.py | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | Allow list to be sorted by a key in the node's data | Allow list to be sorted by a key in the node's data
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen |
74a3fe9d83c3ccf2f6972277df3a34c47bc06c26 | slave/skia_slave_scripts/run_gyp.py | slave/skia_slave_scripts/run_gyp.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def _Run(self)... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def __init__(s... | Increase timeout for RunGYP step BUG=skia:1631 (SkipBuildbotRuns) | Increase timeout for RunGYP step
BUG=skia:1631
(SkipBuildbotRuns)
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11229 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbo... |
96ef8f3f2c81822df635a373496d2f638178f85a | backend/project_name/settings/test.py | backend/project_name/settings/test.py | from .base import * # noqa
SECRET_KEY = "test"
DATABASES = {
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),}
}
STATIC_ROOT = "staticfiles"
STATIC_URL = "/static/"
MEDIA_ROOT = "mediafiles"
MEDIA_URL = "/media/"
DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSy... | from .base import * # noqa
SECRET_KEY = "test"
DATABASES = {
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),}
}
STATIC_ROOT = base_dir_join('staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = base_dir_join('mediafiles')
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = "dj... | Revert "Fix ci build by adjust static root and media root path" | Revert "Fix ci build by adjust static root and media root path"
This reverts commit e502c906
| Python | mit | vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate |
74c770b8b457b14a297193e0cd8e9d5bb6b4b031 | utils/retry.py | utils/retry.py | import time
import urllib2
import socket
from google.appengine.api import datastore_errors
from google.appengine.runtime import apiproxy_errors
MAX_ATTEMPTS = 10
def retry(func, *args, **kwargs):
for attempt in range(MAX_ATTEMPTS):
if attempt:
seconds = min(300, 2 ** attempt)
pri... | import logging
import time
import urllib2
import socket
from google.appengine.api import datastore_errors
from google.appengine.runtime import apiproxy_errors
MAX_ATTEMPTS = 10
def retry(func, *args, **kwargs):
for attempt in range(MAX_ATTEMPTS):
if attempt:
seconds = min(300, 2 ** attempt)
... | Use logging module for debug messages, not stdout. | Use logging module for debug messages, not stdout.
| Python | mit | jcrocholl/nxdom,jcrocholl/nxdom |
b2d121a2ee8750afd0f4d527c80371bd501f841c | neo/io/nixio_fr.py | neo/io/nixio_fr.py | from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.nixrawio import NIXRawIO
# This class subjects to limitations when there are multiple asymmetric blocks
class NixIO(NIXRawIO, BaseFromRaw):
name = 'NIX IO'
_prefered_signal_group_mode = 'group-by-same-units'
_prefered_units_group_mode = 'split... | from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.nixrawio import NIXRawIO
# This class subjects to limitations when there are multiple asymmetric blocks
class NixIO(NIXRawIO, BaseFromRaw):
name = 'NIX IO'
_prefered_signal_group_mode = 'group-by-same-units'
_prefered_units_group_mode = 'split... | Use Python2 compatible super() call | [nixio] Use Python2 compatible super() call
| Python | bsd-3-clause | NeuralEnsemble/python-neo,JuliaSprenger/python-neo,samuelgarcia/python-neo,INM-6/python-neo,rgerkin/python-neo,apdavison/python-neo |
0c67cff030592cd44023444a5f10eef6570bfdf0 | odinweb/testing.py | odinweb/testing.py | """
Testing Helpers
~~~~~~~~~~~~~~~
Collection of Mocks and Tools for testing APIs.
"""
from odin.codecs import json_codec
from odinweb.constants import Method
class MockRequest(object):
"""
Mocked Request object
"""
def __init__(self, query=None, post=None, headers=None, method=Method.GET, body=''... | """
Testing Helpers
~~~~~~~~~~~~~~~
Collection of Mocks and Tools for testing APIs.
"""
from typing import Dict, Any
from odin.codecs import json_codec
try:
from urllib.parse import urlparse, parse_qs
except ImportError:
from urlparse import urlparse, parse_qs
from odinweb.constants import Method
class Mo... | Expand Mock Request to include path and built in URL parsing. | Expand Mock Request to include path and built in URL parsing.
| Python | bsd-3-clause | python-odin/odinweb,python-odin/odinweb |
8da30d3752fd6a056891960aa2892bcd8001c79b | lintreview/processor.py | lintreview/processor.py | import logging
import lintreview.tools as tools
from lintreview.diff import DiffCollection
from lintreview.review import Problems
from lintreview.review import Review
log = logging.getLogger(__name__)
class Processor(object):
def __init__(self, client, number, head, target_path):
self._client = client
... | import logging
import lintreview.tools as tools
from lintreview.diff import DiffCollection
from lintreview.review import Problems
from lintreview.review import Review
log = logging.getLogger(__name__)
class Processor(object):
def __init__(self, client, number, head, target_path):
self._client = client
... | Make check against None instead of falsey things. | Make check against None instead of falsey things.
| Python | mit | markstory/lint-review,markstory/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,markstory/lint-review |
f62ccee6bffa4dff9047a2f4b7499412dd3e2fb1 | tomviz/python/SwapAxes.py | tomviz/python/SwapAxes.py | def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
data_py = dataset.active_scalars
dataset.active_scalars = data_py.swapaxes(axis1, axis2)
| def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
import numpy as np
data_py = dataset.active_scalars
swapped = data_py.swapaxes(axis1, axis2)
dataset.active_scalars = np.asfortranarray(swapped)
| Convert array back to fortran before setting | Convert array back to fortran before setting
Unfortunately, it looks like numpy.ndarray.swapaxes converts
the ordering from Fortran to C. When this happens, a warning
message will be printed to the console later that a conversion to
Fortran ordering is required.
Instead of printing the warning, just convert it back t... | Python | bsd-3-clause | OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz |
5558b19b46fbe1db6f25b227ac581095fedcff2e | us_ignite/maps/views.py | us_ignite/maps/views.py | import json
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.template.response import TemplateResponse
from us_ignite.maps.models import Location
def location_list(request):
"""Shows a list of locations in a map."""
object_list = Location.published.... | from django.template.response import TemplateResponse
from us_ignite.common.response import json_response
from us_ignite.maps.models import Location
def location_list(request):
"""Shows a list of locations in a map."""
object_list = Location.published.select_related('category').all()
context = {
... | Update ``maps`` to use the ``json_response`` function. | Update ``maps`` to use the ``json_response`` function.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
9bdf9455344b83fc28c5ecceafba82036bb2c75d | foodsaving/management/tests/test_makemessages.py | foodsaving/management/tests/test_makemessages.py | from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
makemessages = MakeMessagesCommand
django_jinja_makemessages = DjangoJinjaMakeMessages... | from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
makemessages = MakeMessagesCommand
django_jinja_makemessages = DjangoJinjaMakeMessages... | Fix makemessages test to look for jinja2 | Fix makemessages test to look for jinja2
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.