commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
5493848ddca54a57a6dceb781bd417a9232cf1c4 | tests/test_profile.py | tests/test_profile.py | """Test the profile listing and creation
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import pytest
import dodocs
# fixtures
@pytest.fixture
def profile_list():
"""Execute the command profile list"""
command_line = 'profile list'
dodocs.main(command_line.split())
# profile listing
def test_l... | """Test the profile listing and creation
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import pytest
import dodocs
# fixtures
@pytest.fixture
def profile_list():
"""Execute the command profile list"""
command_line = 'profile list'
dodocs.main(command_line.split())
@pytest.fixture
def profile_... | Add remove and edit on non existing dodocs directories | Add remove and edit on non existing dodocs directories
| Python | mit | montefra/dodocs |
0d8283a066fd0bdfe278a5516a299971f7492cea | auth/src/db/crypto.py | auth/src/db/crypto.py | from passlib.context import CryptContext
from config import HASH_ROUNDS
crypt_context = CryptContext(
schemes=["pbkdf2_sha512"],
all__vary_rounds=0.1,
pbkdf2_sha512__default_rounds=HASH_ROUNDS
)
encrypt = crypt_context.encrypt
verify = crypt_context.verify
| from passlib.context import CryptContext
from config import HASH_ROUNDS, HASH_ALGORITHM
crypt_context = CryptContext(
schemes=[HASH_ALGORITHM],
all__vary_rounds=0.1,
pbkdf2_sha512__default_rounds=HASH_ROUNDS
)
encrypt = crypt_context.encrypt
verify = crypt_context.verify
| Make algorithm configurable, for real this time | Make algorithm configurable, for real this time
| Python | mit | jackfirth/docker-auth |
fce10cb35be29ba265f2ed189198703c718ad479 | quantecon/__init__.py | quantecon/__init__.py | """
Import the main names to top level.
"""
from . import models as models
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
from .estspec import smooth, periodogram, ar_periodogram
from .graph_tools import DiGraph
from .gridtools import cartesian, mlinspace
from .g... | """
Import the main names to top level.
"""
from . import models as models
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
from .estspec import smooth, periodogram, ar_periodogram
from .graph_tools import DiGraph
from .gridtools import cartesian, mlinspace
from .g... | Fix for python 3 relative import statement | Fix for python 3 relative import statement
| Python | bsd-3-clause | andybrnr/QuantEcon.py,oyamad/QuantEcon.py,agutieda/QuantEcon.py,jviada/QuantEcon.py,QuantEcon/QuantEcon.py,QuantEcon/QuantEcon.py,gxxjjj/QuantEcon.py,agutieda/QuantEcon.py,gxxjjj/QuantEcon.py,oyamad/QuantEcon.py,jviada/QuantEcon.py,andybrnr/QuantEcon.py |
e80169bf4ec40609f768f8c84519824b8a209e44 | fedoracommunity/mokshaapps/updates/controllers/root.py | fedoracommunity/mokshaapps/updates/controllers/root.py | from moksha.lib.base import Controller
from moksha.api.widgets import ContextAwareWidget, Grid
from tg import expose, tmpl_context
class UpdatesGrid(Grid, ContextAwareWidget):
template='mako:fedoracommunity.mokshaapps.updates.templates.table_widget'
updates_grid = UpdatesGrid('updates_table')
class RootControlle... | from tg import expose, tmpl_context, validate
from formencode import validators
from moksha.lib.base import Controller
from moksha.api.widgets import ContextAwareWidget, Grid
class UpdatesGrid(Grid, ContextAwareWidget):
template='mako:fedoracommunity.mokshaapps.updates.templates.table_widget'
updates_grid = Upda... | Use formencode validators in our updates app, instead of doing hacks | Use formencode validators in our updates app, instead of doing hacks
| Python | agpl-3.0 | fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages |
3736b02d3b0004809bafb0a40625e26caffc1beb | opal/ddd.py | opal/ddd.py | """
DDD Integration for OPAL
"""
from django.conf import settings
import requests
CHANGE_ENDPOINT = settings.DDD_ENDPOINT + 'change/'
OUR_ENDPOINT = settings.DEFAULT_DOMAIN + '/ddd/'
def change(pre, post):
r = requests.post(
CHANGE_ENDPOINT,
params={'pre': pre, 'post': post, 'endpoint': OUR_ENDPOI... | """
DDD Integration for OPAL
"""
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
import json
import requests
CHANGE_ENDPOINT = settings.DDD_ENDPOINT + 'change/'
OUR_ENDPOINT = settings.DEFAULT_DOMAIN + '/ddd/'
def change(pre, post):
payload = {
'pre': json.d... | Use the real send POST params keyword. | Use the real send POST params keyword.
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal |
77704e80a32fbb2f4c9533778565a92dbb346ab6 | highlander/highlander.py | highlander/highlander.py | from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_fi... | from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_fi... | Make sure filename is a string. | Make sure filename is a string.
| Python | mit | chriscannon/highlander |
9178e4d6a8fb54c6124c192765a9ff8cc3a582c6 | docs/recipe_bridge.py | docs/recipe_bridge.py | #!/usr/bin/env python
import time
from picraft import World, Vector, Block
world = World(ignore_errors=True)
world.say('Auto-bridge active')
last_pos = None
while True:
this_pos = world.player.pos
if last_pos is not None:
# Has the player moved more than 0.2 units in a horizontal direction?
m... | #!/usr/bin/env python
from __future__ import unicode_literals
import time
from picraft import World, Vector, Block
from collections import deque
world = World(ignore_errors=True)
world.say('Auto-bridge active')
try:
bridge = deque()
last_pos = None
while True:
this_pos = world.player.pos
... | Update bridge recipe to limit length | Update bridge recipe to limit length
Also removes bridge at the end
| Python | bsd-3-clause | waveform80/picraft,radames/picraft |
4b46ecb6304527b38d0c2f8951b996f8d28f0bff | config/freetype2/__init__.py | config/freetype2/__init__.py | import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OS... | import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OS... | Add fallback to freetype-config for compatibility. | Add fallback to freetype-config for compatibility.
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang |
ef2618e25cc6dfed119da8d0d4d3c26f2832a33b | ds/utils/logbuffer.py | ds/utils/logbuffer.py | from __future__ import absolute_import
from tempfile import NamedTemporaryFile
class LogBuffer(object):
def __init__(self, chunk_size=4096):
self.chunk_size = chunk_size
self.fp = NamedTemporaryFile()
def fileno(self):
return self.fp.fileno()
def write(self, chunk):
self... | from __future__ import absolute_import
from tempfile import NamedTemporaryFile
class LogBuffer(object):
def __init__(self, chunk_size=4096):
self.chunk_size = chunk_size
self.fp = NamedTemporaryFile()
def fileno(self):
return self.fp.fileno()
def write(self, chunk):
self... | Move flush logic into close | Move flush logic into close
| Python | apache-2.0 | jkimbo/freight,jkimbo/freight,getsentry/freight,klynton/freight,jkimbo/freight,getsentry/freight,klynton/freight,klynton/freight,rshk/freight,jkimbo/freight,getsentry/freight,klynton/freight,getsentry/freight,getsentry/freight,rshk/freight,rshk/freight,rshk/freight |
adf1fc4646e18db1f4f2ad9c89e6d23799cd3b5f | dtoolcore/__init__.py | dtoolcore/__init__.py | """Tool for managing (scientific) data.
"""
__version__ = "2.0.0"
| """API for creating and interacting with dtool datasets.
"""
__version__ = "2.0.0"
| Update dtoolcore module summary line | Update dtoolcore module summary line
| Python | mit | JIC-CSB/dtoolcore |
681379125ca83641e6906318c01b6932e0cb100b | whois_search.py | whois_search.py | from ipwhois import IPWhois
import whois
'''
############################################
# WHOIS #
############################################
'''
def whois_target(host):
# Technically this is still passive recon
# because you still aren't hitting target
w = whois.whoi... | from ipwhois import IPWhois
import whois
'''
############################################
# WHOIS #
############################################
'''
def whois_target(host):
# Technically this is still passive recon
# because you still aren't hitting target
w = whois.whoi... | Fix whois ip search (rename ranges/mult var) | Fix whois ip search (rename ranges/mult var)
| Python | unlicense | nethunteros/punter |
b48e39aafd9ef413216444a6bfb97e867aa40e1c | tests/auto/keras/test_constraints.py | tests/auto/keras/test_constraints.py | import unittest
import numpy as np
from theano import tensor as T
class TestConstraints(unittest.TestCase):
def setUp(self):
self.some_values = [0.1,0.5,3,8,1e-7]
self.example_array = np.random.random((100,100))*100. - 50.
self.example_array[0,0] = 0. # 0 could possibly cause trouble
d... | import unittest
import numpy as np
from theano import tensor as T
class TestConstraints(unittest.TestCase):
def setUp(self):
self.some_values = [0.1,0.5,3,8,1e-7]
self.example_array = np.random.random((100,100))*100. - 50.
self.example_array[0,0] = 0. # 0 could possibly cause trouble
d... | Add a test for the identity, non-negative, and unit-norm constraints | Add a test for the identity, non-negative, and unit-norm constraints
| Python | mit | saurav111/keras,kfoss/keras,Aureliu/keras,stephenbalaban/keras,chenych11/keras,jiumem/keras,cvfish/keras,xiaoda99/keras,rodrigob/keras,iamtrask/keras,wubr2000/keras,navyjeff/keras,keskarnitish/keras,eulerreich/keras,zxytim/keras,tencrance/keras,printedheart/keras,rudaoshi/keras,dribnet/keras,pthaike/keras,cheng6076/ker... |
8b7660193f5a18a2d0addd218f2fd2d77d8f98ac | app/grandchallenge/cases/serializers.py | app/grandchallenge/cases/serializers.py | from rest_framework import serializers
from grandchallenge.cases.models import Image, ImageFile
class ImageFileSerializer(serializers.ModelSerializer):
class Meta:
model = ImageFile
fields = ("pk", "image", "file")
class ImageSerializer(serializers.ModelSerializer):
files = ImageFileSeriali... | from rest_framework import serializers
from grandchallenge.cases.models import Image, ImageFile
class ImageFileSerializer(serializers.ModelSerializer):
class Meta:
model = ImageFile
fields = ("pk", "image", "file", "image_type")
class ImageSerializer(serializers.ModelSerializer):
files = Im... | Return image type of file in api | Return image type of file in api
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
8297ca0006362d6a99fef6d8ad94c9fc094cc3ee | oscar/templatetags/form_tags.py | oscar/templatetags/form_tags.py | from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by ... | from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by ... | Adjust form templatetag to handle missing field var | Adjust form templatetag to handle missing field var
When a non-existant field gets passed, the templatetag was raising an
unseemly AttributeError. This change checks to see if the passed var is
actually a form field to avoid said error.
| Python | bsd-3-clause | WillisXChen/django-oscar,spartonia/django-oscar,solarissmoke/django-oscar,ka7eh/django-oscar,manevant/django-oscar,ademuk/django-oscar,dongguangming/django-oscar,thechampanurag/django-oscar,elliotthill/django-oscar,vovanbo/django-oscar,jlmadurga/django-oscar,lijoantony/django-oscar,spartonia/django-oscar,WadeYuChen/dja... |
a968cbcd4b5a2aec5e1253221598eb53f9f0c2e9 | osgtest/tests/test_10_condor.py | osgtest/tests/test_10_condor.py | import os
import osgtest.library.core as core
import unittest
class TestStartCondor(unittest.TestCase):
def test_01_start_condor(self):
core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
core.state['condor.started-service'] = False
core.state['condor.running-service'] = Fals... | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondor(osgunittest.OSGTestCase):
def test_01_start_condor(self):
core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
core.state['condor.started-service'] = False
core.state['condor.running-... | Update 10_condor to use OkSkip functionality | Update 10_condor to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16522 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
9616afb9e8c7a5a599096b588cd71a714e001e2b | dduplicated/fileManager.py | dduplicated/fileManager.py | import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in pat... | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | Fix in link action. Remove the `_link` method and add action to `_delete`, this fix concurrency problems. | Fix in link action. Remove the `_link` method and add action to `_delete`, this fix concurrency problems.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli |
64147133f2140777c5b3aafcdf7510d816dd6462 | core/data/DataTransformer.py | core/data/DataTransformer.py | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | Fix for data transformer giving no output. | Fix for data transformer giving no output.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop |
d708fa46b135fb1104d827ec4e64412f0028d94e | pyleus/compat.py | pyleus/compat.py | import sys
if sys.version_info[0] < 3:
from cStringIO import StringIO
BytesIO = StringIO
else:
from io import BytesIO
from io import StringIO
_ = BytesIO
_ = StringIO
| import sys
if sys.version_info[0] < 3:
from cStringIO import StringIO
BytesIO = StringIO
else:
from io import BytesIO
from io import StringIO
_ = BytesIO # pyflakes
_ = StringIO # pyflakes
| Add comments about pyflakes appeasement | Add comments about pyflakes appeasement
| Python | apache-2.0 | poros/pyleus,patricklucas/pyleus,mzbyszynski/pyleus,Yelp/pyleus,imcom/pyleus,dapuck/pyleus,stallman-cui/pyleus,stallman-cui/pyleus,mzbyszynski/pyleus,imcom/pyleus,poros/pyleus,ecanzonieri/pyleus,Yelp/pyleus,imcom/pyleus,jirafe/pyleus,jirafe/pyleus,ecanzonieri/pyleus,patricklucas/pyleus,dapuck/pyleus |
f21ebbaabb5ce38432961b7786b78ad4d23f3259 | django_mercadopago/urls.py | django_mercadopago/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^notifications$', views.create_notification),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^notifications$', views.create_notification, name='notifications'),
]
| Add a view to the notifications name (for reversing) | Add a view to the notifications name (for reversing)
| Python | isc | asermax/django-mercadopago |
748e713fdb2f3126f463651562e1f938a7ce1511 | src/dcm/agent/scripts/common-linux/general_cleanup.py | src/dcm/agent/scripts/common-linux/general_cleanup.py | import os
import sys
import logging
_g_logger = logging.getLogger(__name__)
def main(bin_path, dcm_basedir, dbfile):
dirs_to_clean = [os.path.join(dcm_basedir, 'logs'),
os.path.join(dcm_basedir, 'secure')]
for clean_dir in dirs_to_clean:
for (dirpath, dirname, filenames) in os.w... | import os
import sys
import logging
_g_logger = logging.getLogger(__name__)
def main(bin_path, dcm_basedir, dbfile):
dirs_to_clean = [os.path.join(dcm_basedir, 'logs'),
os.path.join(dcm_basedir, 'secure')]
for clean_dir in dirs_to_clean:
for (dirpath, dirname, filenames) in os.w... | Clean Azure images before snapshot | Clean Azure images before snapshot
For waagent to provision the following file must not exist:
/var/lib/waagent/provisioned
| Python | apache-2.0 | buzztroll/unix-agent,JPWKU/unix-agent,buzztroll/unix-agent,buzztroll/unix-agent,buzztroll/unix-agent,JPWKU/unix-agent,enStratus/unix-agent,enStratus/unix-agent,JPWKU/unix-agent,enStratus/unix-agent,JPWKU/unix-agent,enStratus/unix-agent |
67bcacb60a9e24970345d5f6daf3ba3649677b5c | froide/campaign/listeners.py | froide/campaign/listeners.py | from .utils import connect_foirequest
def connect_campaign(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
parts = reference.split(':', 1)
if len(parts) != 2:
return
namespace = parts[0]
connect_foirequest(sender, namespace)
| from .utils import connect_foirequest
def connect_campaign(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if '@' in reference:
parts = reference.split('@', 1)
else:
parts = reference.split(':', 1)
if len(parts) != 2:
return
names... | Allow connecting froide_campaigns to campaign app | Allow connecting froide_campaigns to campaign app | Python | mit | fin/froide,fin/froide,fin/froide,fin/froide |
ffd917c5ace8e815b185495aec17cf47b0a7648a | storage_service/administration/tests/test_languages.py | storage_service/administration/tests/test_languages.py | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
class TestLanguageSwitching(TestCase):
@classmethod
def setUpClass(cls):
User.objects.create_user(
username="admin", password="admin", email="admin@example.com"
)
super(TestLangu... | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
class TestLanguageSwitching(TestCase):
@classmethod
def setUpClass(cls):
super(TestLanguageSwitching, cls).setUpClass()
User.objects.create_user(
username="admin", password="admin", emai... | Fix integrity error reusing db in tests | Fix integrity error reusing db in tests
Base `setUpClass` needs to be called first so the transaction is initialized
before we mutate the data.
This solves a conflic raised when using `--reuse-db`.
| Python | agpl-3.0 | artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service |
cc86cb09854cc5656a99e209b27a4c9d9a407bb1 | turbinia/config/turbinia_config.py | turbinia/config/turbinia_config.py | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Make turbinia-psq the default pubsub queue name | Make turbinia-psq the default pubsub queue name
| Python | apache-2.0 | google/turbinia,google/turbinia,google/turbinia,google/turbinia,google/turbinia |
be127957f35a4673c95a81884adf3484943af079 | future/tests/test_imports_urllib.py | future/tests/test_imports_urllib.py | import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
... | from __future__ import absolute_import, print_function
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard... | Tweak to a noisy test module | Tweak to a noisy test module
| Python | mit | krischer/python-future,michaelpacer/python-future,krischer/python-future,michaelpacer/python-future,QuLogic/python-future,QuLogic/python-future,PythonCharmers/python-future,PythonCharmers/python-future |
cad499437969e6b1b23ab7d2639003d4ec6a86b1 | datasets/ccgois/transform.py | datasets/ccgois/transform.py | import datetime
import json
import sys
import ffs
import re
from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader
def main(workspace):
DATA_DIR = ffs.Path(workspace)
datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))
u = Uploader("ccgo... | import datetime
import json
import sys
import ffs
import re
from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader
def main(workspace):
DATA_DIR = ffs.Path(workspace)
datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))
u = Uploader("ccgo... | Fix the naming of the newly created resources | Fix the naming of the newly created resources
| Python | mit | nhsengland/publish-o-matic |
3842fef4a2f291b64d83a3977946b07c86ac46d6 | build/identfilter.py | build/identfilter.py | #!/usr/bin/env python
import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about types that end with '_t'
if not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need to do this f... | #!/usr/bin/env python
import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about types that end with '_t'
if not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need to d... | Fix spacing in the filter script | Fix spacing in the filter script
Conflicting file loading directives in Vim screwed up the tab stops.
| Python | mit | criptych/graphene,criptych/graphene,ebassi/graphene,criptych/graphene,criptych/graphene,ebassi/graphene |
f4cb832d61437ad6e871a1596393adc06ceafab9 | cookiecutter/utils.py | cookiecutter/utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that... | Add docstring. 4 spaces for consistency. | Add docstring. 4 spaces for consistency.
| Python | bsd-3-clause | lgp171188/cookiecutter,janusnic/cookiecutter,dajose/cookiecutter,agconti/cookiecutter,willingc/cookiecutter,letolab/cookiecutter,christabor/cookiecutter,cichm/cookiecutter,vincentbernat/cookiecutter,terryjbates/cookiecutter,atlassian/cookiecutter,foodszhang/cookiecutter,michaeljoseph/cookiecutter,cguardia/cookiecutter,... |
20d02eef92d458dac890f1ab814ca146f2bd1853 | s3direct/urls.py | s3direct/urls.py | from django.conf.urls import patterns, url
from s3direct.views import get_upload_params
urlpatterns = patterns('',
url('^get_upload_params/',
get_upload_params, name='s3direct'),
)
| from django.conf.urls import url
from s3direct.views import get_upload_params
urlpatterns = [
url('^get_upload_params/', get_upload_params, name='s3direct')
]
| Update urlpatterns to use list of url() | Update urlpatterns to use list of url()
| Python | mit | AlexRiina/django-s3direct,yunojuno/django-s3-upload,yunojuno/django-s3-upload,bradleyg/django-s3direct,yunojuno/django-s3-upload,Artory/django-s3direct,Artory/django-s3direct,bradleyg/django-s3direct,Artory/django-s3direct,AlexRiina/django-s3direct,AlexRiina/django-s3direct,bradleyg/django-s3direct |
cff73bbff666745a72a8ffc6750c33aebb80fa4b | feature_extraction.py | feature_extraction.py | from PIL import Image
import glob
def _get_masks():
TRAIN_MASKS = './data/train/*_mask.tif'
return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)]
def _get_mask_labels():
mask_labels = []
for image in _get_masks():
mask_labels.append((image.filename, 255 in image.getdata(... | import re
import glob
from PIL import Image
from tqdm import tqdm
def _get_file_root_name(file_path):
file_root_name_expression = re.compile(r'/[^/]*\.', re.IGNORECASE)
return file_root_name_expression.search(file_path).group(0)[1:-1]
def _get_feature_label_images():
TRAIN_FILES = './data/train/*.tif'
... | Return all data instead of just mask data | Return all data instead of just mask data
| Python | mit | Brok-Bucholtz/Ultrasound-Nerve-Segmentation |
0cf60c650b81d2d396d673e4256be19a5193774e | app/main/helpers/s3.py | app/main/helpers/s3.py | import os
import boto
import datetime
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, file, acl='public-re... | import os
import boto
import datetime
import mimetypes
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, fil... | Set Content-Type header for S3 uploads | Set Content-Type header for S3 uploads
Current document updates do not preserve the content type - it is reset to "application/octet-stream"
We should set the correct content type so that browsers know what to do when users access the documents.
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace... |
8c5aca4b9957e883a9dab8c95933de7285ab335b | login/middleware.py | login/middleware.py | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api') \
... | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api') \
... | Revert trying to fix activation redirection bug | Revert trying to fix activation redirection bug
This reverts commit c2d63335062abea4cece32bd01132bcf8dce44f2.
It seems like the commit doesn't actually do anything to alleviate the
bug. Since it's also more lenient with its checks, I'll rather revert
it.
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
7d862be1aba5a062eeaf54ada9587278e7e93f5b | apps/provider/urls.py | apps/provider/urls.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
url(r'^fhir/push$', fhir_practitioner_push, name="fhir_p... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
url(r'^fhir/practioner/push$', fhir_practitioner_push, n... | Change fhir practitioner url and add organization url | Change fhir practitioner url and add organization url
| Python | apache-2.0 | TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client |
9771428d7b0c4a2c0fe057e1030024b13344ccc7 | moa/device/__init__.py | moa/device/__init__.py |
from moa.threading import CallbackQueue
from moa.base import MoaBase
from kivy.properties import BooleanProperty
from kivy.clock import Clock
try:
from Queue import Queue
except ImportError:
from queue import Queue
class Device(MoaBase):
''' By default, the device does not support multi-threading.
''... |
from moa.base import MoaBase
class Device(MoaBase):
''' By default, the device does not support multi-threading.
'''
def activate(self, **kwargs):
pass
def recover(self, **kwargs):
pass
def deactivate(self, **kwargs):
pass
| Clean the base device class. | Clean the base device class.
| Python | mit | matham/moa |
ff19efc1b5a51bc4b29c82d32bfe066661dbadca | sonnet/src/conformance/api_test.py | sonnet/src/conformance/api_test.py | # Copyright 2019 The Sonnet 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 applicable l... | # Copyright 2019 The Sonnet 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 applicable l... | Use six.moves to reference `reload`. | Use six.moves to reference `reload`.
PiperOrigin-RevId: 253199825
Change-Id: Ifb9bf182572900a813ea1b0dbbda60f82495eac1
| Python | apache-2.0 | deepmind/sonnet,deepmind/sonnet |
06907e310169db7084f9e40f93e60182ba6e6423 | python/animationBase.py | python/animationBase.py | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
... | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
red = Ball(5, 9, 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)
try:
print "Press Ctrl + ... | Add two balls to animation | Add two balls to animation
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix |
1adc660916eafe5937b96f1b5bc480185efc96ad | aospy_user/__init__.py | aospy_user/__init__.py | """aospy_user: Library of user-defined aospy objects."""
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
... | """aospy_user: Library of user-defined aospy objects."""
from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
TIME_STR, TIME_STR_IDEALIZED)
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import pr... | Use aospy coord label constants | Use aospy coord label constants
| Python | apache-2.0 | spencerahill/aospy-obj-lib |
721f837cbfa0de8804def607908a9744b0d099a8 | asl/vendor/__init__.py | asl/vendor/__init__.py | import sys
import os
_vendor_initialized = False
def append_paths(path, vendor_modules):
new_path = []
for v in vendor_modules:
new_path.append(path + os.sep + v)
sys.path = new_path + sys.path
def do_init():
global _vendor_initialized
if _vendor_initialized:
return
_vendor_i... | import sys
import os
_vendor_initialized = False
def append_paths(path, vendor_modules):
new_path = []
for v in vendor_modules:
new_path.append(path + os.sep + v)
sys.path = new_path + sys.path
def do_init():
global _vendor_initialized
if _vendor_initialized:
return
_vendor_i... | Fix of vendor directory search. | Fix of vendor directory search.
| Python | mit | AtteqCom/zsl,AtteqCom/zsl |
75ce7463218609129151ea96fae4590763165961 | array/quick-sort.py | array/quick-sort.py | # Sort list using recursion
def quick_sort(lst):
if len(lst) == 0:
print []
left = []
right = []
pivot = lst[0]
# compare first element in list to the rest
for i in range(1, len(lst)):
if lst[i] < pivot:
left.append(lst[i])
else:
right.append(lst[i])
# recursion
print quick_sort(left) + pivot + ... | # Sort list using recursion
def quick_sort(lst):
if len(lst) <= 1:
return lst
left = []
right = []
# compare first element in list to the rest
for i in lst[1:]:
if lst[i] < lst[0]:
left.append(i)
else:
right.append(i)
# recursion
return quick_sort(left) + lst[0:1] + quick_sort(right)
# test cas... | Debug and add test case | Debug and add test case
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
d7219365197ff22aec44836e37af19f62420f996 | paystackapi/tests/test_tcontrol.py | paystackapi/tests/test_tcontrol.py | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
http... | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
http... | Add test for transfer control resend otp | Add test for transfer control resend otp
| Python | mit | andela-sjames/paystack-python |
b682addf7d65dbb48ad5c0a3506987103ea43835 | miura/morph.py | miura/morph.py | import MeCab
class MeCabParser(object):
def __init__(self, arg=''):
self.model = MeCab.Model_create(arg)
def parse(self, s):
tagger = self.model.createTagger()
lattice = self.model.createLattice()
lattice.set_sentence(s)
tagger.parse(lattice)
node = latt... | import MeCab
class MeCabParser(object):
def __init__(self, arg=''):
self.model = MeCab.Model_create(arg)
def parse(self, s):
tagger = self.model.createTagger()
lattice = self.model.createLattice()
lattice.set_sentence(s)
tagger.parse(lattice)
node = latt... | Use find instead of split | Use find instead of split
| Python | mit | unnonouno/mrep |
fce1a7e5c1466ef79c5387f4b9f0c231e745f380 | basics/candidate.py | basics/candidate.py |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._y = props[0]
self._x = props[1]
self._major = props[2]
self._minor = props[3]
self.... |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._y = props[0]
self._x = props[1]
self._major = props[2]
self._minor = props[3]
self.... | Return as array; start of finding shell fraction | Return as array; start of finding shell fraction
| Python | mit | e-koch/BaSiCs |
bfa446d5fc399b685419ad00c376bcd9a13a8605 | mediacrush/decorators.py | mediacrush/decorators.py | from flask import jsonify, request
from functools import wraps
import json
def json_output(f):
@wraps(f)
def wrapper(*args, **kwargs):
def jsonify_wrap(obj):
callback = request.args.get('callback', False)
jsonification = jsonify(obj)
if callback:
jso... | from flask import jsonify, request
from functools import wraps
import json
jsonp_notice = """
// MediaCrush supports Cross Origin Resource Sharing requests.
// There is no reason to use JSONP; please use CORS instead.
// For more information, see https://mediacru.sh/docs/api"""
def json_output(f):
@wraps(f)
d... | Add JSONP notice to API | Add JSONP notice to API | Python | mit | nerdzeu/NERDZCrush,MediaCrush/MediaCrush,roderickm/MediaCrush,roderickm/MediaCrush,nerdzeu/NERDZCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush,roderickm/MediaCrush |
30dd3c8436ebe69aff2956322312072e8ab581f0 | example/tests/test_fields.py | example/tests/test_fields.py | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from shop.models.cart import BaseCartItem
class JSONFieldTest(TestCase):
"""JSONField Wrapper Tests"""
def test_json_field_create(self):
"""Test saving a JSON object in our JSONField"""
json_obj = {... | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from shop.models.defaults.customer import Customer
class JSONFieldTest(TestCase):
"""JSONField Wrapper Tests"""
def test_json_field_create(self):
"""Test saving a JSON object in our JSONField"""
jso... | Update model used to test | Update model used to test
| Python | bsd-3-clause | jrief/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,divio/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,khchine5/django-shop,nimbis/django-shop,divio/django-shop,jrief/django-shop,nimbis/django-shop,nimbis/django-shop,awesto/django-shop,awesto/django-shop,jrief/django-... |
b0a94dc2f696464db999e652b4a9dbdaf96f8532 | backend/talks/forms.py | backend/talks/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryse... | from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryse... | Mark conference and language as required | Mark conference and language as required
| Python | mit | patrick91/pycon,patrick91/pycon |
fb14ac15bcb1db14f756e8943f551ba428de4c7f | dusty/systems/known_hosts/__init__.py | dusty/systems/known_hosts/__init__.py | import os
import logging
from ...subprocess import check_output
def _get_known_hosts_path():
ssh_dir = os.path.expanduser('~root/.ssh')
if not os.path.isdir(ssh_dir):
os.makedirs(ssh_dir)
return os.path.join(ssh_dir, 'known_hosts')
def ensure_known_hosts(hosts):
known_hosts_path = _get_known_... | import os
import logging
from ...subprocess import check_output
def _get_known_hosts_path():
ssh_dir = os.path.expanduser('~root/.ssh')
if not os.path.isdir(ssh_dir):
os.makedirs(ssh_dir)
return os.path.join(ssh_dir, 'known_hosts')
def ensure_known_hosts(hosts):
known_hosts_path = _get_known_... | Create required known_hosts file if it does not exists | Create required known_hosts file if it does not exists
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty |
4cb455890b7afa4f44da9d96a5c9820598731b36 | sedlex/AddGitHubIssueVisitor.py | sedlex/AddGitHubIssueVisitor.py | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | Fix missing githubIssue field when the corresponding issue already existed. | Fix missing githubIssue field when the corresponding issue already existed.
| Python | agpl-3.0 | Legilibre/SedLex |
7503ebff7ded94a52ed5bb6e0a72935071576e20 | tests/test_default.py | tests/test_default.py | def test_confluence_user(User):
user = User("confluence")
assert user.exists
assert user.group == "confluence"
| def test_confluence_user(User):
user = User("confluence")
assert user.exists
assert user.group == "confluence"
def test_confluence_group(Group):
group = Group("confluence")
assert group.exists
| Add a testinfra group example | Add a testinfra group example
| Python | apache-2.0 | telstra-digital/ansible-role-confluence,telstra-digital/ansible-role-confluence |
843601dbd89d7ac99b128684bb19e9363e867b8a | tests/test_stumpff.py | tests/test_stumpff.py | from numpy import cos, cosh, sin, sinh
from numpy.testing import assert_allclose, assert_equal
from poliastro._math.special import stumpff_c2 as c2, stumpff_c3 as c3
def test_stumpff_functions_near_zero():
psi = 0.5
expected_c2 = (1 - cos(psi**0.5)) / psi
expected_c3 = (psi**0.5 - sin(psi**0.5)) / psi**1... | from numpy import cos, cosh, sin, sinh
from numpy.testing import assert_allclose
from poliastro._math.special import stumpff_c2 as c2, stumpff_c3 as c3
def test_stumpff_functions_near_zero():
psi = 0.5
expected_c2 = (1 - cos(psi**0.5)) / psi
expected_c3 = (psi**0.5 - sin(psi**0.5)) / psi**1.5
assert... | Use numpy.testing.assert_allclose with small relative tolerance | test: Use numpy.testing.assert_allclose with small relative tolerance
To avoid having numpy.testing.assert_equal fail in some cases at the
level of machine precision, use numpy.testing.assert_allclose instead
with a relative tolerance set small, 1e-10, to still be restrictive in
the level of equality accepted.
| Python | mit | poliastro/poliastro |
62f6e116306901aedaa738236075c4faa00db74d | tests/config_test.py | tests/config_test.py | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Fix module path (config -> config_yaml) to unbreak test. | Fix module path (config -> config_yaml) to unbreak test.
| Python | apache-2.0 | mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher |
c47b2d88fce9f890e7356288faf097cf4a97f0b8 | simplesqlite/_logger/_logger.py | simplesqlite/_logger/_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import sqliteschema
import tabledata
from ._null_logger import NullLogger
MODULE_NAME = "simplesqlite"
try:
from loguru import logger
logger.disable(MODULE_... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import sqliteschema
import tabledata
from ._null_logger import NullLogger
MODULE_NAME = "simplesqlite"
_is_enable = False
try:
from loguru import logger
log... | Add check for logging state | Add check for logging state
| Python | mit | thombashi/SimpleSQLite,thombashi/SimpleSQLite |
c784fb30beac7abe958867345161f74876ca940d | causalinfo/__init__.py | causalinfo/__init__.py | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | Fix silly boiler plate copy issue. | Fix silly boiler plate copy issue.
| Python | mit | brettc/causalinfo |
8c203bfb28e027e4fdd490096296f712c3afd28e | consulrest/keyvalue.py | consulrest/keyvalue.py | import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if k... | import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if k... | Return None if key is not found | Return None if key is not found
| Python | mit | vcoque/consul-ri |
a013927ee9772e05ae4255cff98ecfe4819f205c | flask_app/__init__.py | flask_app/__init__.py | """
The flask application package.
"""
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# See co... | """
The flask application package.
"""
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return... | Set login view for login_required | Set login view for login_required
| Python | mit | szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft |
9698e531ffd528b6b56e285f5cf8087aa06d4a02 | test/conftest.py | test/conftest.py | import pytest
@pytest.fixture
def namespaces():
import class_namespaces
return class_namespaces
@pytest.fixture
def compat():
import class_namespaces.compat
return class_namespaces.compat
@pytest.fixture
def abc():
import class_namespaces.compat.abc
return class_namespaces.compat.abc
| import pytest
@pytest.fixture
def namespaces():
import class_namespaces
return class_namespaces
@pytest.fixture
def namespace(namespaces):
return namespaces.Namespace
@pytest.fixture
def compat():
import class_namespaces.compat
return class_namespaces.compat
@pytest.fixture
def abc():
im... | Add fixture for Namespace specifically. | Add fixture for Namespace specifically.
| Python | mit | mwchase/class-namespaces,mwchase/class-namespaces |
a9fd1154c99d1377e0da5127762d6248f3c9f81f | github3/gists/file.py | github3/gists/file.py | # -*- coding: utf-8 -*-
"""
github3.gists.file
------------------
Module containing the logic for the GistFile object.
"""
from __future__ import unicode_literals
import requests
from ..models import GitHubObject
class GistFile(GitHubObject):
"""This represents the file object returned by interacting with gis... | # -*- coding: utf-8 -*-
"""
github3.gists.file
------------------
Module containing the logic for the GistFile object.
"""
from __future__ import unicode_literals
from ..models import GitHubCore
class GistFile(GitHubCore):
"""This represents the file object returned by interacting with gists.
It stores th... | Load content from raw_url if empty | Load content from raw_url if empty
| Python | bsd-3-clause | balloob/github3.py,christophelec/github3.py,sigmavirus24/github3.py |
d6f13599f47ff4b4926d07d79962d3fff36ab6c4 | gradebook/__init__.py | gradebook/__init__.py | from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
... | from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
... | Add placeholder for CSV file | Add placeholder for CSV file
| Python | bsd-2-clause | jarrodmillman/gradebook |
465a13cad35b62a0fc64768ec6b2aed0573566da | ubersmith/__init__.py | ubersmith/__init__.py |
__all__ = [
'api',
'calls',
'entities',
]
|
__all__ = [
'api',
'calls',
'entities',
'exceptions',
'utils',
]
| Add new modules to package init. | Add new modules to package init.
| Python | mit | jasonkeene/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,hivelocity/python-ubersmith |
cf5fb07651099e38e6487eae641da07feda40b05 | numba/tests/test_api.py | numba/tests/test_api.py | import numba
from numba.tests.support import TestCase
import unittest
class TestNumbaModule(TestCase):
"""
Test the APIs exposed by the top-level `numba` module.
"""
def check_member(self, name):
self.assertTrue(hasattr(numba, name), name)
self.assertIn(name, numba.__all__)
def ... | import numba
from numba import jit, njit
from numba.tests.support import TestCase
import unittest
class TestNumbaModule(TestCase):
"""
Test the APIs exposed by the top-level `numba` module.
"""
def check_member(self, name):
self.assertTrue(hasattr(numba, name), name)
self.assertIn(na... | Add testcases for jit and njit with forceobj and nopython | Add testcases for jit and njit with forceobj and nopython
| Python | bsd-2-clause | numba/numba,cpcloud/numba,seibert/numba,stuartarchibald/numba,sklam/numba,seibert/numba,stonebig/numba,IntelLabs/numba,cpcloud/numba,stuartarchibald/numba,IntelLabs/numba,IntelLabs/numba,numba/numba,stonebig/numba,stonebig/numba,IntelLabs/numba,seibert/numba,stonebig/numba,gmarkall/numba,numba/numba,sklam/numba,IntelLa... |
95245bb7fab6efe5a72cb8abbf4380a26b72a720 | corehq/apps/hqwebapp/middleware.py | corehq/apps/hqwebapp/middleware.py | import logging
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from django.conf import settings
logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [R... | from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from corehq.util.soft_assert import soft_assert
from django.conf import settings
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [R... | Revert "log to file, don't email" | Revert "log to file, don't email"
This reverts commit a132890ef32c99b938021717b67c3e58c13952b0.
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq |
ab4e279a6866d432cd1f58a07879e219360b4911 | src/tenyksscripts/scripts/8ball.py | src/tenyksscripts/scripts/8ball.py | import random
ateball = [
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes, definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try... | import random
ateball = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
... | Revert "Added nickname and punct, removed parens" | Revert "Added nickname and punct, removed parens"
This reverts commit 061de1a57a95cd2911c06bb58c29a8e488b7387e.
| Python | mit | colby/tenyks-contrib,cblgh/tenyks-contrib,kyleterry/tenyks-contrib |
6cf3baed6e5f707e5c307388018f4bb3121327f9 | nanoservice/config.py | nanoservice/config.py | """ Read configuration for a service from a json file """
import io
import json
from .client import Client
from .error import ConfigError
def load(filepath=None, filecontent=None, clients=True):
""" Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
... | """ Read configuration for a service from a json file """
import io
import json
from .client import Client
from .error import ConfigError
class DotDict(dict):
""" Access a dictionary like an object """
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self... | Access the conf like a object | Access the conf like a object
| Python | mit | walkr/nanoservice |
2b05a59b09e72f263761dae2feac360f5abd1f82 | promgen/__init__.py | promgen/__init__.py | default_app_config = 'promgen.apps.PromgenConfig'
import logging
logging.basicConfig(level=logging.DEBUG)
| default_app_config = 'promgen.apps.PromgenConfig'
| Remove some debug logging config | Remove some debug logging config
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen |
d4274336756ed6d6c36f94cbaae7e8328ac50f9a | djedi/auth/__init__.py | djedi/auth/__init__.py | def has_permission(request):
user = request.user
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
return False
def get_username(request):
user = request.user
if hasattr(user, 'ge... | import logging
_log = logging.getLogger(__name__)
def has_permission(request):
user = getattr(request, 'user', None)
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
else:
_log.w... | Handle wrong order of middleware. | Handle wrong order of middleware.
| Python | bsd-3-clause | andreif/djedi-cms,andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms |
2dfc3817881d9e90456dc3ea94b1fd0ec308fb5e | beavy/common/morphing_field.py | beavy/common/morphing_field.py | from marshmallow.fields import Field
class MorphingField(Field):
# registry = {
# }
def __init__(self, many=False, fallback=None, overwrite=None, **metadata):
self.many = False
self.fallback = fallback or self.FALLBACK
self.overwrite = overwrite
# Common alternative:
# d... | from marshmallow.fields import Field
class MorphingField(Field):
# registry = {
# }
def __init__(self, many=False, fallback=None, overwrite=None, **metadata):
self.many = False
self.fallback = fallback or self.FALLBACK
self.overwrite = overwrite
# Common alternative:
# d... | Fix MorphingField: polymorphic_identy is already the string we want | Fix MorphingField: polymorphic_identy is already the string we want
| Python | mpl-2.0 | beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy |
287c2da6d72155a4988665ac3c4031032dd835e3 | admin_tests/common_auth/test_logs.py | admin_tests/common_auth/test_logs.py | from nose import tools as nt
from tests.base import AdminTestCase
from osf.models.admin_log_entry import AdminLogEntry, update_admin_log
class TestUpdateAdminLog(AdminTestCase):
def test_add_log(self):
update_admin_log('123', 'dfqc2', 'This', 'log_added')
nt.assert_equal(AdminLogEntry.objects.co... | from nose import tools as nt
from tests.base import AdminTestCase
from osf_tests.factories import UserFactory
from osf.models.admin_log_entry import AdminLogEntry, update_admin_log
class TestUpdateAdminLog(AdminTestCase):
def test_add_log(self):
user = UserFactory()
update_admin_log(user.id, 'df... | Fix log test to use real user and id | Fix log test to use real user and id
| Python | apache-2.0 | sloria/osf.io,cwisecarver/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,laurenrevere/osf.io,aaxelb/osf.io,TomBaxter/osf.io,binoculars/osf.io,chrisseto/osf.io,cslzchen/osf.io,adlius/osf.io,baylee-d/osf.io,caneruguz/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,caseyrollins/o... |
07fabcc0fa08d95ec5f17f5cbfcd0c14b645f31c | child_compassion/migrations/11.0.1.0.0/post-migration.py | child_compassion/migrations/11.0.1.0.0/post-migration.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Nathan Flückiger <nathan.fluckiger@hotmail.ch>
#
# The licence is in the file __manifest__.py
#
#############################################################... | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Nathan Flückiger <nathan.fluckiger@hotmail.ch>
#
# The licence is in the file __manifest__.py
#
#############################################################... | Add migration for assigning security groups | Add migration for assigning security groups
| Python | agpl-3.0 | CompassionCH/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules |
ffd8bb1e85fe7ed80d85062e4d5932f28065b84c | auditlog/apps.py | auditlog/apps.py | from django.apps import AppConfig
class AuditlogConfig(AppConfig):
name = "auditlog"
verbose_name = "Audit log"
| from django.apps import AppConfig
class AuditlogConfig(AppConfig):
name = "auditlog"
verbose_name = "Audit log"
default_auto_field = 'django.db.models.AutoField'
| Apply default_auto_field to app config. | Apply default_auto_field to app config.
| Python | mit | jjkester/django-auditlog |
f6072411bf097ae3d493f5c95d05f4711fdc5195 | Discord/cogs/python.py | Discord/cogs/python.py |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Python())
class Python(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.command()
async def pep(self, ctx, number: int):
'''Generate Python Enhancement Pro... |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Python())
class Python(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.command()
async def pep(self, ctx, number: int):
'''Generate Python Enhancement Pro... | Handle package not found in pypi command | [Discord] Handle package not found in pypi command
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
2032de8bcf6ae6ed84a09ce3e294bae8fd86962a | dog/core/ext/health.py | dog/core/ext/health.py | """
Commands used to check the health of the bot.
"""
import datetime
from time import monotonic
from dog import Cog
from discord.ext import commands
class Health(Cog):
@commands.command()
async def ping(self, ctx):
""" Pong! """
# measure gateway delay
before = monotonic()
... | """
Commands used to check the health of the bot.
"""
import datetime
from time import monotonic
from dog import Cog
from discord.ext import commands
class Health(Cog):
@commands.command()
async def ping(self, ctx):
""" Pong! """
# measure gateway delay
before = monotonic()
... | Fix gateway lag being negative in d?ping | Fix gateway lag being negative in d?ping
| Python | mit | sliceofcode/dogbot,slice/dogbot,slice/dogbot,slice/dogbot,sliceofcode/dogbot |
a0585269f05189fb9ae4f5abe98cd36731ad8a53 | babel_util/scripts/json_to_pajek.py | babel_util/scripts/json_to_pajek.py | #!/usr/bin/env python3
from util.misc import open_file, Benchmark
from util.PajekFactory import PajekFactory
import ujson
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON")
parser.add_argument('outfile')
parser.add_argument('... | #!/usr/bin/env python3
from util.misc import open_file, Benchmark
from util.PajekFactory import PajekFactory
import ujson
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON")
parser.add_argument('outfile')
parser.add_argument('... | Support for multiple subjects and filtering out non-wos ids | Support for multiple subjects and filtering out non-wos ids
| Python | agpl-3.0 | jevinw/rec_utilities,jevinw/rec_utilities |
5f001d818459a2bd5e9f6a89e8ed097d379a26d2 | runtime/__init__.py | runtime/__init__.py | import builtins
import operator
import functools
from ..compile import varary
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
, ',': lambda a, *xs: (a,) + xs
, '<': operator.lt
, '<=': operator.le
, '=... | import builtins
import operator
import functools
import importlib
from ..compile import varary
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
, ',': lambda a, *xs: (a,) + xs
, '<': operator.lt
, '<=': o... | Use importlib.import_module instead of __import__. | Use importlib.import_module instead of __import__.
| Python | mit | pyos/dg |
9a0ababb3b8b4b23184ab7005d995c17edef2a2b | src/test/test_imagesaveblock.py | src/test/test_imagesaveblock.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import cv
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipfblock.imagesave
class TestImageSaveBlock(unittest.TestCase):
def setUp(sel... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import cv
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipfblock.imagesave
class TestImageSaveBlock(unittest.TestCase):
def setUp(sel... | Remove saved file in TestImageSaveBlock test case | Remove saved file in TestImageSaveBlock test case
| Python | lgpl-2.1 | anton-golubkov/Garland,anton-golubkov/Garland |
67a20401caaa63852e95fcaf8bafb6ed85ecd1f2 | test/selenium/src/lib/page/modal/__init__.py | test/selenium/src/lib/page/modal/__init__.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object # flake8: noqa
)
| # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object, # flake8: noqa
update_object # flake8: noqa
)
| Add a sort of hierarchy of modules for package | Add a sort of hierarchy of modules for package
| Python | apache-2.0 | AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core |
be0a9da80d46630d8958aa95838c5c7c67dda375 | blanc_basic_podcast/podcast/views.py | blanc_basic_podcast/podcast/views.py | from django.views.generic import ListView, DateDetailView
from .models import PodcastFile
class PodcastFileListView(ListView):
queryset = PodcastFile.objects.filter(published=True)
class PodcastFileDetailView(DateDetailView):
queryset = PodcastFile.objects.filter(published=True)
month_format = '%m'
... | from django.views.generic import ListView, DateDetailView
from django.utils import timezone
from django.conf import settings
from .models import PodcastFile
class PodcastFileListView(ListView):
paginate_by = getattr(settings, 'PODCAST_PER_PAGE', 10)
def get_queryset(self):
return PodcastFile.objects.... | Fix the list view for podcast files, and allow custom per page number in settings | Fix the list view for podcast files, and allow custom per page number in settings
| Python | bsd-2-clause | blancltd/blanc-basic-podcast |
9334e8059cd74086278133345566c4b4591c81a4 | amgut/__init__.py | amgut/__init__.py | #!/usr/bin/env python
from __future__ import division
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The American Gut Project Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed ... | #!/usr/bin/env python
from __future__ import division
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The American Gut Project Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed ... | Add DB connection to amgut init module | Add DB connection to amgut init module
| Python | bsd-3-clause | biocore/american-gut-web,ElDeveloper/american-gut-web,PersonalGenomesOrg/american-gut-web,josenavas/american-gut-web,josenavas/american-gut-web,wasade/american-gut-web,mortonjt/american-gut-web,adamrp/american-gut-web,biocore/american-gut-web,adamrp/american-gut-web,mortonjt/american-gut-web,mortonjt/american-gut-web,s... |
d28e884d832b63bef1434476a378de9b7e333264 | samples/WavGenerator.py | samples/WavGenerator.py | #############
# ECE 612 Spring 2017
# Joe Parrish
#
# Use the same logic from SpectrumTester.py to generate multiple sine waves
# but write that output to a .wav file for file based testing of the project code
#############
import wave
import numpy as np
def generate_sample_file(test_freqs, test_amps, chunk=4096, sa... | #############
# ECE 612 Spring 2017
# Joe Parrish
#
# Use the same logic from SpectrumTester.py to generate multiple sine waves
# but write that output to a .wav file for file based testing of the project code
#############
import wave
import argparse
import numpy as np
def generate_sample_file(test_freqs, test_amps... | Add a main function with command line arguments | Add a main function with command line arguments
Now able to generate wave files from command line | Python | mit | parrisha/raspi-visualizer |
ee6ad550ebeeaebf7c0959932ec60cbd923d480e | plowshare/__init__.py | plowshare/__init__.py | from .plowshare import *
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014 Storj Labs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | Add proper header and fix import. | Add proper header and fix import.
| Python | mit | Storj/plowshare-wrapper |
c5e5b3d6c3d8cad75b1d2eac16179872dd415eb9 | scripts/asgard-deploy.py | scripts/asgard-deploy.py | #!/usr/bin/env python
import sys
import logging
import click
import tubular.asgard as asgard
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
@click.command()
@click.option('--ami_id', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
except Exceptio... | #!/usr/bin/env python
import sys
import logging
import click
import tubular.asgard as asgard
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
... | Use environment var for AMI_ID. | Use environment var for AMI_ID.
| Python | agpl-3.0 | eltoncarr/tubular,eltoncarr/tubular |
51a126c0ada7c00a99416b241bb1c11888e82836 | esmgrids/jra55_grid.py | esmgrids/jra55_grid.py |
import numpy as np
import netCDF4 as nc
from .base_grid import BaseGrid
class Jra55Grid(BaseGrid):
def __init__(self, h_grid_def, description='JRA55 regular grid'):
self.type = 'Arakawa A'
self.full_name = 'JRA55'
with nc.Dataset(h_grid_def) as f:
x_t = f.variables['lon'][:]... |
import numpy as np
import netCDF4 as nc
from .base_grid import BaseGrid
class Jra55Grid(BaseGrid):
def __init__(self, h_grid_def, description='JRA55 regular grid'):
self.type = 'Arakawa A'
self.full_name = 'JRA55'
with nc.Dataset(h_grid_def) as f:
lon_bnds = f.variables['lon... | Use bounds to determing jra55 grid cell locations. | Use bounds to determing jra55 grid cell locations.
| Python | apache-2.0 | DoublePrecision/esmgrids |
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 |
3ce0db9cccea34998674e340c1dcc7f49b487e9a | TweetPoster/twitter.py | TweetPoster/twitter.py | from requests_oauthlib import OAuth1
from TweetPoster import User, config
class Twitter(User):
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twitter']['consumer_secret'],
... | from datetime import datetime
from requests_oauthlib import OAuth1
from TweetPoster import User, config
class Twitter(User):
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twit... | Convert JSON into Tweet and TwitterUser objects | Convert JSON into Tweet and TwitterUser objects
| Python | mit | joealcorn/TweetPoster,tytek2012/TweetPoster,r3m0t/TweetPoster,aperson/TweetPoster |
cb29f8522c4e90b7db82bac408bc16bd2f1d53da | cs251tk/common/run.py | cs251tk/common/run.py | import shlex
import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
# This env stuff is to catch glibc errors, because
# it apparently prints to /dev/tty instead of stderr.
# (see http://stackoverflow.com/a/27797579)
ENV = copy.copy(os.environ)
ENV["LIBC_FATAL_STDERR_"] =... | import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
# This env stuff is to catch glibc errors, because
# it apparently prints to /dev/tty instead of stderr.
# (see http://stackoverflow.com/a/27797579)
ENV = copy.copy(os.environ)
ENV["LIBC_FATAL_STDERR_"] = "1"
def ru... | Revert "revert part of 27cd680" | Revert "revert part of 27cd680"
c491bbc2302ac7c95c180d31845c643804fa30d3
| Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit |
b836a7347d66e6fb8df2f97c011b875e24c91e17 | dashboard/consumers.py | dashboard/consumers.py | from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
message.reply_channel.send({
'accept': True
})
| from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
Group('btc-price').add(message.reply_channel)
message.reply_channel.send({
'accept': True
})
| Add user to the group when he first connects | Add user to the group when he first connects
| Python | mit | alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor |
aeaf802100cd6869178dd9f412d35e452916a63d | common/commands/view_manipulation.py | common/commands/view_manipulation.py | from sublime_plugin import TextCommand
from ...core.git_command import GitCommand
__all__ = (
"gs_handle_vintageous",
"gs_handle_arrow_keys"
)
class gs_handle_vintageous(TextCommand, GitCommand):
"""
Set the vintageous_friendly view setting if needed.
Enter insert mode if vintageous_enter_inser... | from sublime_plugin import TextCommand
from ...core.git_command import GitCommand
__all__ = (
"gs_handle_vintageous",
"gs_handle_arrow_keys"
)
class gs_handle_vintageous(TextCommand, GitCommand):
"""
Set the vintageous_friendly view setting if needed.
Enter insert mode if vintageous_enter_inser... | Fix `vintageous_enter_insert_mode` for NeoVintageous 1.22.0 | Fix `vintageous_enter_insert_mode` for NeoVintageous 1.22.0
Fixes #1395
In NeoVintageous/NeoVintageous#749, pushed as 1.22.0 (Oct 2020), the
relevant commands were renamed.
We follow the new names, but for now also call the old ones.
| Python | mit | divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy |
a55b96a7d64643af6d2adcd6a15fe3348c5d1c41 | dbaas/workflow/settings.py | dbaas/workflow/settings.py | DEPLOY_MYSQL_WORKFLOW = (
'util.gen_names',
'util.gen_dbinfra',
'dbaas_cloudstack.create_vm'
)
DEPLOY_VIRTUALMACHINE = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
)
DEPLOY_MONGO_WORKFLOW = (
'util.gen_names... | DEPLOY_MYSQL_WORKFLOW = (
'util.gen_names',
'util.gen_dbinfra',
'dbaas_cloudstack.create_vm'
)
DEPLOY_VIRTUALMACHINE = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
'workflow.steps.create_dns.CreateDns'
... | Add create dns on main workflow | Add create dns on main workflow
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
6e9a19d362005125036f5c0ecdbe88fc1c4f01aa | product_computed_list_price/__init__.py | product_computed_list_price/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from . import product | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from . import product
from . import pricelist
| FIX price type 'list_price' inactivation | FIX price type 'list_price' inactivation
| Python | agpl-3.0 | ingadhoc/product,ingadhoc/product |
f2ea241e9bb6e5e927a90c56438bf7883ae3744f | siemstress/__init__.py | siemstress/__init__.py | __version__ = '0.2'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['core', 'querycore', 'query']
import siemstress.query
| __version__ = '0.2'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['core', 'querycore', 'query']
import siemstress.query
import siemstress.trigger
| Add trigger to module import | Add trigger to module import
| Python | mit | dogoncouch/siemstress |
3b0608e11da620f1e12aeb270dbaf2f255a35cec | Cura/Qt/Bindings/ControllerProxy.py | Cura/Qt/Bindings/ControllerProxy.py | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._controller = Application.getInstance().getControl... | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
from Cura.Scene.BoxRenderer import BoxRenderer
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._co... | Add a (temporary) bounding box around an added mesh | Add a (temporary) bounding box around an added mesh
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
e82ab299a6c68f682a9f9b769e79cf2054684e3b | reviewboard/attachments/evolutions/file_attachment_uuid.py | reviewboard/attachments/evolutions/file_attachment_uuid.py | from __future__ import unicode_literals
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('FileAttachment', 'uuid', models.CharField, max_length=255,
initial=None, null=True),
]
| from __future__ import unicode_literals
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('FileAttachment', 'uuid', models.CharField, max_length=255,
initial=''),
]
| Fix the FileAttachment.uuid evolution to match the model field. | Fix the FileAttachment.uuid evolution to match the model field.
The evolution that was included in the existing code didn't match the
definition of the field. This is a very simple fix.
Testing done:
Ran evolutions.
Reviewed at https://reviews.reviewboard.org/r/8141/
| Python | mit | davidt/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,sgallagher/reviewboard,brennie/reviewboard,reviewboard/reviewboard,brennie/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,brennie/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,davidt/reviewboard,chipx86/reviewboard,sgall... |
3e33849ded2c69760ce93b4b1e9ab8094904040f | space-age/space_age.py | space-age/space_age.py | class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
... | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def... | Implement __getattr__ to reduce code | Implement __getattr__ to reduce code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
15a5e6c1aca706330147475984848dfc33fd1a9d | common/djangoapps/mitxmako/tests.py | common/djangoapps/mitxmako/tests.py | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | Fix test so that it works with both CMS and LMS settings | Fix test so that it works with both CMS and LMS settings
| Python | agpl-3.0 | nanolearningllc/edx-platform-cypress,jjmiranda/edx-platform,SivilTaram/edx-platform,olexiim/edx-platform,eduNEXT/edx-platform,bdero/edx-platform,olexiim/edx-platform,nanolearningllc/edx-platform-cypress-2,cyanna/edx-platform,rismalrv/edx-platform,don-github/edx-platform,unicri/edx-platform,xuxiao19910803/edx-platform,U... |
6690479e46c9138c6f57ce9415b0429175545e96 | stock_transfer_restrict_lot/models/stock_production_lot.py | stock_transfer_restrict_lot/models/stock_production_lot.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
class St... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
class St... | FIX in lot name_get to show location with the stock | FIX in lot name_get to show location with the stock
| Python | agpl-3.0 | ingadhoc/stock |
a02791231dcc5ecd5bebbb698719e47bd01c68ed | src/__init__.py | src/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# 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
# Unles... | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# 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
# Unles... | Revert "Expose __version__ from the top level cgpm module." | Revert "Expose __version__ from the top level cgpm module."
This reverts commit 3b94d4111ea00ff15cf0566392861124fc31b430.
Shouldn't've jumped the gun like that, I guess. Apparently this
doesn't work and it's not clear to me why.
| Python | apache-2.0 | probcomp/cgpm,probcomp/cgpm |
8207d86b7b2a6e1f81454eefea4784d89c8674a8 | resolver_test/django_test.py | resolver_test/django_test.py | # Copyright (c) 2011 Resolver Systems Ltd.
# All Rights Reserved
#
from urlparse import urljoin
from mock import Mock
from resolver_test import ResolverTestMixins
import django
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpRequest
class R... | # Copyright (c) 2017 PythonAnywhere LLP.
# All Rights Reserved
#
from urlparse import urljoin
from mock import Mock
from resolver_test import ResolverTestMixins
import django
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpRequest
class Res... | Use different usernames for each test. by: Glenn, Giles | Use different usernames for each test. by: Glenn, Giles
| Python | mit | pythonanywhere/resolver_test |
50cc2ba3353cdd27513999465e854d01823605a4 | angr/knowledge_base.py | angr/knowledge_base.py | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = pr... | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = pr... | Fix the recursion bug in KnowledgeBase after the previous refactor. | Fix the recursion bug in KnowledgeBase after the previous refactor.
| Python | bsd-2-clause | f-prettyland/angr,axt/angr,tyb0807/angr,iamahuman/angr,angr/angr,angr/angr,axt/angr,angr/angr,chubbymaggie/angr,schieb/angr,chubbymaggie/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,axt/angr,schieb/angr,chubbymaggie/angr,schieb/angr,tyb0807/angr |
22eda7c2b844c9dccb31ad9cce882cc13d1adf75 | apel_rest/urls.py | apel_rest/urls.py | """This file maps url patterns to classes."""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from api.views.CloudRecordSummaryView import CloudRecordSummaryView
from api.views.CloudRecordView import CloudRecordView
admin.autodiscover()
urlpatterns = patterns('',
... | """This file maps url patterns to classes."""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from api.views.CloudRecordSummaryView import CloudRecordSummaryView
from api.views.CloudRecordView import CloudRecordView
admin.autodiscover()
urlpatterns = patterns('',
... | Add name to patterns in urlpatterns | Add name to patterns in urlpatterns
- so tests can use reverse()
| Python | apache-2.0 | apel/rest,apel/rest |
d2ce7b64c14e18ca395a2d1dc03123ae8a5735b7 | ab_game.py | ab_game.py | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.curre... | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.curre... | Enable min_priority again - seems to be working? | Enable min_priority again - seems to be working?
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai |
76600b63940da9322673ce6cd436129a7d65f10d | scripts/ec2/terminate_all.py | scripts/ec2/terminate_all.py | #!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##... | #!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##... | Add import statement for os | Add import statement for os | Python | bsd-2-clause | manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill |
2d64c01daebd918c3e6196b1eb3ad62f105c56e0 | django_google_charts/charts.py | django_google_charts/charts.py | import six
import json
from django.core.urlresolvers import reverse
from django.utils.html import format_html, mark_safe
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs)
if klass.chart_slug:
CHARTS... | import six
import json
from django.core.urlresolvers import reverse
from django.utils.html import format_html, mark_safe
from django.utils.encoding import python_2_unicode_compatible
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, ... | Make this Python 2.x compatible | Make this Python 2.x compatible
| Python | mit | danpalmer/django-google-charts,danpalmer/django-google-charts |
0bcecfdf33f42f85bb9a8e32e79686a41fb5226a | django_validator/exceptions.py | django_validator/exceptions.py | from rest_framework import status
import rest_framework.exceptions
class ValidationError(rest_framework.exceptions.ValidationError):
code = ''
def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST):
super(ValidationError, self).__init__(detail)
self.status_code = statu... | from rest_framework import status
import rest_framework.exceptions
class ValidationError(rest_framework.exceptions.APIException):
code = ''
def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST):
super(ValidationError, self).__init__(detail)
self.code = code
se... | Fix Validation import error in older DRF. | Fix Validation import error in older DRF.
| Python | mit | romain-li/django-validator,romain-li/django-validator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.