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 |
|---|---|---|---|---|---|---|---|---|---|
3ec71d3925a3551f6f25fc25e827c88caaff1fdd | tests/integration/test_redirection_external.py | tests/integration/test_redirection_external.py | """Check external REDIRECTIONS"""
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_in... | """Check external REDIRECTIONS"""
import os
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
... | Add test for external redirection. | Add test for external redirection.
| Python | mit | okin/nikola,okin/nikola,okin/nikola,getnikola/nikola,getnikola/nikola,getnikola/nikola,okin/nikola,getnikola/nikola |
ad4effbdf95b51f151d613f02f70b4501bbe453d | tests/unit/extensions/flask_babel_unit_test.py | tests/unit/extensions/flask_babel_unit_test.py | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.extensions.babel
"""
import unittest
import orchard
import orchard.extensions.flask_babel
class BabelUnitTest(unittest.TestCase):
def setUp(self):
self.app = orchard.create_app('Testing')
self.app.config['LANGUAGES'] = {
'de': 'Deu... | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.extensions.babel
"""
import unittest
import orchard
import orchard.extensions.flask_babel
class BabelUnitTest(unittest.TestCase):
def setUp(self):
self.app = orchard.create_app('Testing')
self.app.config['BABEL_DEFAULT_LOCALE'] = 'en'
... | Set default locale in test to avoid test failures when different default is used than expected. | Set default locale in test to avoid test failures when different default is used than expected.
| Python | mit | BMeu/Orchard,BMeu/Orchard |
09851ff2903db29703616da0fbc9ec003955712a | zerver/lib/markdown/preprocessor_priorities.py | zerver/lib/markdown/preprocessor_priorities.py | # Note that in the Markdown preprocessor registry, the highest
# numeric value is considered the highest priority, so the dict
# below is ordered from highest-to-lowest priority.
PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531... | # Note that in the Markdown preprocessor registry, the highest
# numeric value is considered the highest priority, so the dict
# below is ordered from highest-to-lowest priority.
# Priorities for the built-in preprocessors are commented out.
PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"gen... | Document built-in preprocessor priorities for convenience. | markdown: Document built-in preprocessor priorities for convenience.
Fixes #19810
| Python | apache-2.0 | eeshangarg/zulip,rht/zulip,rht/zulip,kou/zulip,eeshangarg/zulip,rht/zulip,eeshangarg/zulip,zulip/zulip,rht/zulip,andersk/zulip,kou/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip,andersk/zulip,kou/zulip,andersk/zulip,rht/zulip,rht/zulip,zulip/zulip,kou/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,andersk... |
6835fa9e8978a081186008785bd2e11522372aa9 | tests/utils.py | tests/utils.py | import os
import re
from lxml import etree
def validate_xml(xmlout):
with open(os.path.join(os.path.dirname(__file__), 'pain.008.001.02.xsd'), 'rb') as schema_file:
schema_xml = schema_file.read()
schema_root = etree.XML(schema_xml)
schema = etree.XMLSchema(schema_root)
parser = etree.XMLPars... | import os
import re
from lxml import etree
def validate_xml(xmlout):
with open(os.path.join(os.path.dirname(__file__), 'pain.008.001.02.xsd'), 'rb') as schema_file:
schema_xml = schema_file.read()
schema_root = etree.XML(schema_xml)
schema = etree.XMLSchema(schema_root)
parser = etree.XMLPars... | Fix dates in test output | Fix dates in test output
| Python | mit | raphaelm/python-sepadd,lutoma/python-sepadd |
d6b2dc137111e0a077625feefb0a2c70fc8e789b | Lib/__init__.py | Lib/__init__.py | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | Remove auto include of numpy namespace. | Remove auto include of numpy namespace.
| Python | bsd-3-clause | mgaitan/scipy,rgommers/scipy,Srisai85/scipy,tylerjereddy/scipy,juliantaylor/scipy,sonnyhu/scipy,apbard/scipy,juliantaylor/scipy,zxsted/scipy,behzadnouri/scipy,mikebenfield/scipy,richardotis/scipy,nmayorov/scipy,pnedunuri/scipy,befelix/scipy,anntzer/scipy,mortada/scipy,chatcannon/scipy,WarrenWeckesser/scipy,mingwpy/scip... |
56c25218cb3c987201839917930fc1ae791b5601 | reg/__init__.py | reg/__init__.py | # flake8: noqa
from .dispatch import dispatch, Dispatch
from .context import (dispatch_method, DispatchMethod,
methodify, clean_dispatch_methods)
from .arginfo import arginfo
from .error import RegistrationError
from .predicate import (Predicate, KeyIndex, ClassIndex,
match... | # flake8: noqa
from .dispatch import dispatch, Dispatch, LookupEntry
from .context import (dispatch_method, DispatchMethod,
methodify, clean_dispatch_methods)
from .arginfo import arginfo
from .error import RegistrationError
from .predicate import (Predicate, KeyIndex, ClassIndex,
... | Add LookupEntry to the API. | Add LookupEntry to the API.
| Python | bsd-3-clause | morepath/reg,taschini/reg |
00a5d82c99ce6fb7096d432f12959ab4d8218f4f | booster_bdd/features/src/importBooster.py | booster_bdd/features/src/importBooster.py | import pytest
import time
import requests
import support.helpers as helpers
import sys
import re
import os
class ImportBooster(object):
def importGithubRepo(self, gitRepo):
###############################################
# Environment variables
#
# Note: Pipelines = https://forge.... | import pytest
import time
import requests
import support.helpers as helpers
import sys
import re
import os
class ImportBooster(object):
def importGithubRepo(self, gitRepo):
###############################################
# Environment variables
#
# Note: Pipelines = https://forge.... | Replace hardcoded Forge API URL by variable. | booster-bdd: Replace hardcoded Forge API URL by variable.
| Python | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test |
c9e4a05ed2677fd569642e0ef77dd9f63bf3e15f | vumi/persist/tests/test_redis_base.py | vumi/persist/tests/test_redis_base.py | """Tests for vumi.persist.redis_base."""
from twisted.trial.unittest import TestCase
from vumi.persist.redis_base import Manager
class ManagerTestCase(TestCase):
def mk_manager(self, client, key_prefix='test'):
return Manager(client, key_prefix)
def test_sub_manager(self):
dummy_client = ob... | """Tests for vumi.persist.redis_base."""
from twisted.trial.unittest import TestCase
from vumi.persist.redis_base import Manager
class ManagerTestCase(TestCase):
def mk_manager(self, client=None, key_prefix='test'):
if client is None:
client = object()
return Manager(client, key_pref... | Make sub_manager test neater and also check key_separator. | Make sub_manager test neater and also check key_separator.
| Python | bsd-3-clause | TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi |
ce28d39244b75ee0dd865017b4cf1a0125bf4887 | ynr/apps/parties/serializers.py | ynr/apps/parties/serializers.py | from rest_framework import serializers
from parties.models import Party, PartyDescription, PartyEmblem
class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PartyEmblem
fields = (
"image",
"description",
"date_approved",
... | from rest_framework import serializers
from parties.models import Party, PartyDescription, PartyEmblem
class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PartyEmblem
fields = (
"image",
"description",
"date_approved",
... | Add legacy slug to embedded Party on memberships | Add legacy slug to embedded Party on memberships
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
c37abb2849dc3c4b885673220f9f9965109f0be6 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
not_prime.update(range(i*i, n+1, i))
yield i
| Revert back to a generator - it's actually slight faster | Revert back to a generator - it's actually slight faster
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
2127e3adf190736e14f8500753ffc58126cb39f4 | ovp_search/tests/test_execution.py | ovp_search/tests/test_execution.py | import ovp_search.apps
| import ovp_search.apps
from django.test import TestCase
from django.core.management import call_command
class RebuildIndexTestCase(TestCase):
def test_rebuild_index_execution(self):
call_command('rebuild_index', '--noinput', verbosity=0)
| Add test case for index rebuilding | Add test case for index rebuilding
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-search |
e23d5a64cfd5604f74cce583db3366f2cabb5e1f | tests/basics/builtin_minmax.py | tests/basics/builtin_minmax.py | # test builtin min and max functions
print(min(0,1))
print(min(1,0))
print(min(0,-1))
print(min(-1,0))
print(max(0,1))
print(max(1,0))
print(max(0,-1))
print(max(-1,0))
print(min([1,2,4,0,-1,2]))
print(max([1,2,4,0,-1,2]))
# test with key function
lst = [2, 1, 3, 4]
print(min(lst, key=lambda x:x))
print(min(lst, ke... | # test builtin min and max functions
print(min(0,1))
print(min(1,0))
print(min(0,-1))
print(min(-1,0))
print(max(0,1))
print(max(1,0))
print(max(0,-1))
print(max(-1,0))
print(min([1,2,4,0,-1,2]))
print(max([1,2,4,0,-1,2]))
# test with key function
lst = [2, 1, 3, 4]
print(min(lst, key=lambda x:x))
print(min(lst, ke... | Add min/max "default" agrument test | tests: Add min/max "default" agrument test
| Python | mit | mpalomer/micropython,dinau/micropython,henriknelson/micropython,deshipu/micropython,blazewicz/micropython,supergis/micropython,MrSurly/micropython-esp32,henriknelson/micropython,torwag/micropython,matthewelse/micropython,swegener/micropython,dmazzella/micropython,turbinenreiter/micropython,Timmenem/micropython,tralamaz... |
d90d91906981a4393810069b494d68230f17439e | frameworks/Scala/spray/setup.py | frameworks/Scala/spray/setup.py |
import subprocess
import sys
import time
import os
def start(args, logfile, errfile):
if os.name == 'nt':
subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile)
else:
subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile... |
import subprocess
import sys
import time
import os
def start(args, logfile, errfile):
if os.name == 'nt':
subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile)
else:
subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=er... | Enable spray to find sbt | Enable spray to find sbt
| Python | bsd-3-clause | zane-techempower/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Verber/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,ashawnbandy-te-tfb/Framewo... |
6551c882745b13d5b9be183e83f379e34b067921 | tests/test_emailharvesterws.py | tests/test_emailharvesterws.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_botanick
----------------------------------
Tests for `botanick` module.
"""
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_botanick
----------------------------------
Tests for `botanick` module.
"""
import pytest
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
print(emails_found)
| Revert "Fix a codacy issue" | Revert "Fix a codacy issue"
This reverts commit 0fe83f1bfa54eda16c42fb5d81b33215dc3ba562.
| Python | mit | avidot/Botanick |
2666eee0a59581c504b36acd618e256cf313c377 | start_server.py | start_server.py | import os
def start_server():
os.system('ssh pi@192.168.2.4 python python-libs/RaspberryDrive/driving_server.py &')
return
| import os
def start_server():
count = 0
while count < 2
send_ssh_server_start(count)
count +=1
exit()
def send_ssh_server_start(count):
try:
os.system('ssh pi@192.168.2.4 python python-libs/RaspberryDrive/driving_server.py &')
return
except:
sleep(count + 1)
| Add logic to try server 3 times, pausing a little more each time. | Add logic to try server 3 times, pausing a little more each time.
| Python | mit | jwarshaw/RaspberryDrive |
72205981af062258c4cf75c4323aa3e4d2859bb8 | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Vitaly Potyarkin'
BIO = 'Unsorted ramblings, sometimes related to programming'
SITENAME = 'Randomize'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Moscow'
DEFAULT_LANG = 'EN'
# Feed generation is usually not desir... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Vitaly Potyarkin'
BIO = 'Unsorted ramblings, sometimes related to programming'
SITENAME = 'Randomize'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Moscow'
DEFAULT_LANG = 'EN'
# Feed generation is usually not desir... | Replace default links and values | Replace default links and values
| Python | apache-2.0 | sio/potyarkin.ml,sio/potyarkin.ml |
857124a12f10e3954c114c2b6b688857b80a77a5 | Spectrum.py | Spectrum.py | #!/usr/bin/python
from __future__ import print_function, division
# Spectrum Class
# Begun August 2016
# Jason Neal
class Spectrum:
""" Spectrum class represents and manipulates astronomical spectra. """
def __init__(self, pixel=[], flux=[], wavelength=[]):
""" Create a empty spectra """
... | #!/usr/bin/python
from __future__ import print_function, division
# Spectrum Class
# Begun August 2016
# Jason Neal
class Spectrum:
""" Spectrum class represents and manipulates astronomical spectra. """
def __init__(self, pixel=[], flux=[], wavelength=[]):
""" Create a empty spectra """
... | Remove simple testing from inside class module | Remove simple testing from inside class module
| Python | mit | jason-neal/spectrum_overload,jason-neal/spectrum_overload,jason-neal/spectrum_overload |
530f67493ba0d044a0896aff39bdab2ea5f1cf15 | __init__.py | __init__.py | from openerp.osv import orm
from openerp.tools.translate import _
__all__ = ['OEMetaSL']
def get_overrides():
overrides = {}
def add_override(func):
overrides[func.func_name] = func
@add_override
def copy(cls, cr, uid, rec_id, default=None, context=None):
# Raise by default. This me... | from openerp.osv import orm
from openerp.osv import osv
from openerp.tools.translate import _
__all__ = ['OEMetaSL']
def get_overrides():
overrides = {}
def add_override(func):
overrides[func.func_name] = func
@add_override
def copy(cls, cr, uid, rec_id, default=None, context=None):
... | Add osv method from openerp | Add osv method from openerp
| Python | agpl-3.0 | xcgd/oemetasl |
709017ea46cd3784983ef0ee64cfe608aa44cf0c | tests/integration/aiohttp_utils.py | tests/integration/aiohttp_utils.py | import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == ... | import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999... | Fix aiohttp utils to pass encondig to response.json | Fix aiohttp utils to pass encondig to response.json
| Python | mit | graingert/vcrpy,graingert/vcrpy,kevin1024/vcrpy,kevin1024/vcrpy |
2a3fe3b5e08c91ab8d77569b02b36da63909f619 | pysnmp/hlapi/v1arch/asyncore/sync/__init__.py | pysnmp/hlapi/v1arch/asyncore/sync/__init__.py | #
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp.proto.rfc1902 import *
from pysnmp.smi.rfc1902 import *
from pysnmp.hlapi.v1arch.auth import *
from pysnmp.hlapi.v1arch.asyncore.transport import *
fro... | #
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp.proto.rfc1902 import *
from pysnmp.smi.rfc1902 import *
from pysnmp.hlapi.v1arch.auth import *
from pysnmp.hlapi.v1arch.asyncore.transport import *
fro... | Remove the remnants of hlapi.v1arch.asyncore.sync.compat | Remove the remnants of hlapi.v1arch.asyncore.sync.compat
| Python | bsd-2-clause | etingof/pysnmp,etingof/pysnmp |
674721b9b094fe7e63d3356cf76e7eec0cb9bb62 | employees/serializers.py | employees/serializers.py | from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last... | from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last... | Add current_month_score and last_month_score to EmployeeListSerializer | Add current_month_score and last_month_score to EmployeeListSerializer
| Python | apache-2.0 | belatrix/BackendAllStars |
25e7b4a2e297e9944b5065851c6e65eb40b11bcd | scripts/examples/OpenMV/99-Tests/unittests.py | scripts/examples/OpenMV/99-Tests/unittests.py | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = ... | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, result):
s = ... | Update unittest to ignore disabled functions. | Update unittest to ignore disabled functions.
| Python | mit | kwagyeman/openmv,kwagyeman/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv |
de228621deb5637ab0698ca23cf63ece46c5ddee | task/views.py | task/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from models import *
from serializers import *
# Create your views here.
class TaskListViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated,)
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import viewsets
from django.db.models import Q
from rest_framework.permissions import IsAuthenticated
from models import *
from serializers import *
# Create your views here.
class TaskListViewSet(viewsets.ModelViewSet):
permission... | Adjust the APIView query_set to return tasks created or assigned to the currently logged user | Adjust the APIView query_set to return tasks created or assigned to the currently logged user
| Python | apache-2.0 | toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile |
da91f170c106c46a0d858e887220bc691066cdaa | tests/dtypes_test.py | tests/dtypes_test.py | from common import *
def test_dtype(ds_local):
ds = ds_local
for name in ds.column_names:
assert ds[name].values.dtype == ds.dtype(ds[name])
def test_dtypes(ds_local):
ds = ds_local
all_dtypes = [np.float64, np.float64, np.float64, np.float64, np.int64, np.int64, 'S25', np.object]
np.testing.assert_... | from common import *
def test_dtype(ds_local):
ds = ds_local
for name in ds.column_names:
assert ds[name].values.dtype == ds.dtype(ds[name])
def test_dtypes(ds_local):
ds = ds_local
assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all()
| Update of the dtypes unit-test. | Update of the dtypes unit-test.
| Python | mit | maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex |
db2d8da9109ab4a8aa51acbd80abb2088a7fd299 | campus02/urls.py | campus02/urls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('django.contrib.auth.urls')),
url(r'^web/', include('campus02.web.urls', namespace='we... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='we... | Rearrange admin URL mount point. | Rearrange admin URL mount point.
| Python | mit | fladi/django-campus02,fladi/django-campus02 |
8226571dc97230a486a3b59c8752411e038f04ee | openprescribing/matrixstore/tests/matrixstore_factory.py | openprescribing/matrixstore/tests/matrixstore_factory.py | import mock
import sqlite3
from matrixstore.connection import MatrixStore
from matrixstore import db
from matrixstore.tests.import_test_data_fast import import_test_data_fast
def matrixstore_from_data_factory(data_factory, end_date=None, months=None):
"""
Returns a new in-memory MatrixStore instance using th... | import mock
import sqlite3
from matrixstore.connection import MatrixStore
from matrixstore import db
from matrixstore.tests.import_test_data_fast import import_test_data_fast
def matrixstore_from_data_factory(data_factory, end_date=None, months=None):
"""
Returns a new in-memory MatrixStore instance using th... | Fix MatrixStore test patching to work with LiveServerTestCase | Fix MatrixStore test patching to work with LiveServerTestCase
| Python | mit | annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing |
31ce7c5c264e7648427f73b51cd966165e63ec23 | beaver/redis_transport.py | beaver/redis_transport.py | import datetime
import redis
import urlparse
import beaver.transport
class RedisTransport(beaver.transport.Transport):
def __init__(self, file_config, beaver_config):
super(RedisTransport, self).__init__(file_config, beaver_config)
redis_url = beaver_config.get('redis_url')
_url = urlpa... | import datetime
import redis
import time
import urlparse
import beaver.transport
class RedisTransport(beaver.transport.Transport):
def __init__(self, file_config, beaver_config):
super(RedisTransport, self).__init__(file_config, beaver_config)
redis_url = beaver_config.get('redis_url')
... | Allow for initial connection lag. Helpful when waiting for an SSH proxy to connect | Allow for initial connection lag. Helpful when waiting for an SSH proxy to connect
| Python | mit | doghrim/python-beaver,Appdynamics/beaver,josegonzalez/python-beaver,doghrim/python-beaver,jlambert121/beaver,davidmoravek/python-beaver,josegonzalez/python-beaver,imacube/python-beaver,PierreF/beaver,zuazo-forks/beaver,zuazo-forks/beaver,thomasalrin/beaver,python-beaver/python-beaver,PierreF/beaver,rajmarndi/python-bea... |
597a2ec7a6ff0bae0b43a67e8be675017fd1d7f1 | falafel/mappers/tests/test_current_clocksource.py | falafel/mappers/tests/test_current_clocksource.py | from falafel.mappers.current_clocksource import CurrentClockSource
from falafel.tests import context_wrap
CLKSRC = """
tsc
"""
def test_get_current_clksr():
clksrc = CurrentClockSource(context_wrap(CLKSRC))
assert clksrc.data == "tsc"
| from falafel.mappers.current_clocksource import CurrentClockSource
from falafel.tests import context_wrap
CLKSRC = """
tsc
"""
def test_get_current_clksr():
clksrc = CurrentClockSource(context_wrap(CLKSRC))
assert clksrc.data == "tsc"
assert clksrc.is_kvm is False
assert clksrc.is_vmi_timer != clksrc... | Enhance coverage of current_closcksource to 100% | Enhance coverage of current_closcksource to 100%
| Python | apache-2.0 | RedHatInsights/insights-core,RedHatInsights/insights-core |
196fe935afd6adfec5d205e88472d7ef607b4743 | checkout.py | checkout.py | __author__ = 'RMGiroux'
import asyncio
from asyncio import subprocess
import sys
class OutputCollector:
def __init__(self, name):
self.name = name
@asyncio.coroutine
def process_line(self, stream):
while not stream.at_eof():
line = yield from stream.readline()
prin... | __author__ = 'RMGiroux'
import asyncio
from asyncio import subprocess
import sys
class OutputCollector:
def __init__(self, name):
self.name = name
@asyncio.coroutine
def process_line(self, stream):
while not stream.at_eof():
line = yield from stream.readline()
prin... | Add comment showing parallel waf invocation | Add comment showing parallel waf invocation
| Python | apache-2.0 | RMGiroux/python_experiments |
603ad671c1f6976f75065a4365589a75e1e384ee | service_and_process/serializers.py | service_and_process/serializers.py | from .models import *
from rest_framework import serializers
class MasterWorkableSerializer(serializers.ModelSerializer):
class Meta:
model = MasterWorkable
| from .models import *
from rest_framework import serializers
class MasterWorkableSerializer(serializers.ModelSerializer):
class Meta:
model = MasterWorkable
fields = '__all__'
| Add explicit fields in serializer | Add explicit fields in serializer
| Python | apache-2.0 | rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory |
f243d309e5168b5855045227c9c0a6b082bedc69 | luigi/tasks/gtrnadb/__init__.py | luigi/tasks/gtrnadb/__init__.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | Check that there are data files to import | Check that there are data files to import
It is possible for the pattern to match nothing leading to no files
being imported. This is an error case so we raise an exception if it
happens.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline |
9c7090215ecda3fd4d173c8c5f2d3e1462fbbeee | takePicture.py | takePicture.py | import picamera as p
import os
import time
os.chdir('/home/pi/Desktop')
cam = p.PiCamera()
cam.resolution = (320,240)
cam.hflip = True
cam.vflip = True
x = 0
while x < 50:
#os.unlink('greg.jpg')
img = cam.capture('gregTest.jpg')
time.sleep(.25)
#oc.rename('gregTemp.jpg', 'greg.jpg')
x +=1
exit()
| import picamera as p
import os
import time
os.chdir('/home/pi/Desktop')
cam = p.PiCamera()
cam.resolution = (320,240)
cam.hflip = True
cam.vflip = True
x = 0
while x < 50:
os.unlink('gregTest.jpg')
img = cam.capture('tempGregTest.jpg')
oc.rename('gregTempTest.jpg', 'gregTest.jpg')
time.sleep(.25)
x +=1
exit()
| Add temp file sequence to take picture file | Add temp file sequence to take picture file
| Python | mit | jwarshaw/RaspberryDrive |
9f05a8917ee6fd01a334ef2e1e57062be8ef13af | byceps/config_defaults.py | byceps/config_defaults.py | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking... | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after datab... | Enable DBMS pool pre-pinging to avoid connection errors | Enable DBMS pool pre-pinging to avoid connection errors
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
968b862f6e437b627776b9b8ccf6204434493101 | tests/test_rover_instance.py | tests/test_rover_instance.py |
from unittest import TestCase
from rover import Rover
class TestRover(TestCase):
def setUp(self):
self.rover = Rover()
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
|
from unittest import TestCase
from rover import Rover
class TestRover(TestCase):
def setUp(self):
self.rover = Rover()
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
def test_rover_position(self):
assert self.rover.position == (self.rover.x, self... | Add failing rover position reporting test | Add failing rover position reporting test
| Python | mit | authentik8/rover |
21835415f0224e08c7328151d4319ec73d67cbe1 | station.py | station.py | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = eval(input("Enter the max capacity of... | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = int(eval(input("Enter the max capacit... | Add int to input statements | Add int to input statements
Ref #23 #10
| Python | mit | ForestPride/rail-problem |
42d64b71db7a21355132d1c1573e12798e377b4c | incomplete/pythagoras.py | incomplete/pythagoras.py | import sys
def gather_squares_triangles(p1,p2,depth)
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...... | import sys
def gather_squares_triangles(p1,p2,depth)
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...... | Gather Squares & Triangles Implemented | PythagTree: Gather Squares & Triangles Implemented
| Python | mit | kpatel20538/Rosetta-Code-Python-Tasks |
3609df9044fd72008234bae9145487f315096fcd | hcalendar/__init__.py | hcalendar/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
python-hcalendar is a basic hCalendar parser
"""
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python-hcalendar is a basic hCalendar parser
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
... | Fix hcalendar module __doc__ missing | Fix hcalendar module __doc__ missing
| Python | mit | mback2k/python-hcalendar |
5688ca60985db606a3d42078a017bd851c1f01f6 | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | Cut fbcode_builder dep for thrift on krb5 | Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and... | Python | apache-2.0 | facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift |
65e041bd03863563b52496c1cec81a0c9425f4ee | geonamescache/mappers.py | geonamescache/mappers.py | # -*- coding: utf-8 -*-
from geonamescache import GeonamesCache
from . import mappings
def country(from_key='name', to_key='iso'):
gc = GeonamesCache()
dataset = gc.get_dataset_by_key(gc.get_countries(), from_key)
def mapper(key):
if 'name' == from_key and key in mappings.country_names:
... | # -*- coding: utf-8 -*-
from geonamescache import GeonamesCache
from . import mappings
def country(from_key='name', to_key='iso'):
"""Creates and returns a mapper function to access country data.
The mapper function that is returned must be called with one argument. In
the default case you call it with a... | Add documentation for country mapper | Add documentation for country mapper
| Python | mit | yaph/geonamescache,yaph/geonamescache |
2814f5b2bbd2c53c165f13009eb85cb2c5030b57 | chicago/search_indexes.py | chicago/search_indexes.py | from datetime import datetime
from councilmatic_core.haystack_indexes import BillIndex
from django.conf import settings
from haystack import indexes
import pytz
from chicago.models import ChicagoBill
app_timezone = pytz.timezone(settings.TIME_ZONE)
class ChicagoBillIndex(BillIndex, indexes.Indexable):
topics... | from datetime import datetime
from councilmatic_core.haystack_indexes import BillIndex
from django.conf import settings
from haystack import indexes
import pytz
from chicago.models import ChicagoBill
app_timezone = pytz.timezone(settings.TIME_ZONE)
class ChicagoBillIndex(BillIndex, indexes.Indexable):
topics... | Use prepared data, rather than the object last action date, to determine boost | Use prepared data, rather than the object last action date, to determine boost
| Python | mit | datamade/chi-councilmatic,datamade/chi-councilmatic,datamade/chi-councilmatic,datamade/chi-councilmatic,datamade/chi-councilmatic |
91a551c0bc29d09cd2f034741c1291bfad7346db | tensorflow/tools/docker/jupyter_notebook_config.py | tensorflow/tools/docker/jupyter_notebook_config.py | # Copyright 2015 Google Inc. 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 law or a... | # Copyright 2015 Google Inc. 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 law or a... | Move imports to beginning of code | Move imports to beginning of code
| Python | apache-2.0 | AnishShah/tensorflow,dhalleine/tensorflow,LUTAN/tensorflow,chemelnucfin/tensorflow,brchiu/tensorflow,jalexvig/tensorflow,Intel-tensorflow/tensorflow,benoitsteiner/tensorflow-xsmm,alistairlow/tensorflow,ageron/tensorflow,sandeepdsouza93/TensorFlow-15712,RapidApplicationDevelopment/tensorflow,ravindrapanda/tensorflow,rdi... |
dd51e13a2a7b4e4005127ca0e409d0882179b39f | bluebottle/mail/__init__.py | bluebottle/mail/__init__.py | from django.contrib.sites.models import Site
from django.template.loader import get_template
from django.utils import translation
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
def send_mail(template_name, subject, to, **kwargs):
if hasattr(to, 'pr... | from django.contrib.sites.models import Site
from django.template.loader import get_template
from django.utils import translation
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
from bluebottle.clients import properties
def send_mail(template_name, subj... | Use CONTACT_EMAIL als default from address | Use CONTACT_EMAIL als default from address
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle |
ab0f6115c50bea63856c1e880249ad4bdca3ce42 | src/web/urls.py | src/web/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/', auth_views.login, name='login',
kwargs={'redirect_authenticated_user': True}),
url(r'^logout/', auth_views.logout, {'next_page': '/login'}, nam... | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/', auth_views.login, name='login',
kwargs={'redirect_authenticated_user': True}),
url(r'^logout/', auth_views.logout, {'next_page': '/login'}, nam... | Add ansible namespace in root URLconf | Add ansible namespace in root URLconf
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
5bf24464b00257a9fa5f66047a2f7815c1e4f8fb | tweepy/utils.py | tweepy/utils.py | # Tweepy
# Copyright 2010-2021 Joshua Roesslein
# See LICENSE for details.
import datetime
def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list))
def parse_datetime(datetime_string):
return datetime.datetime.strptime(
datetime_string, "%Y-%m-%dT%H:%M:%S.%f%z"
)
| # Tweepy
# Copyright 2010-2021 Joshua Roesslein
# See LICENSE for details.
import datetime
def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list))
def parse_datetime(datetime_string):
return datetime.datetime.strptime(
datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ"
).re... | Fix parse_datetime to parse API datetime string format with Python 3.6 | Fix parse_datetime to parse API datetime string format with Python 3.6
The '%z' directive didn't accept 'Z' until Python 3.7
| Python | mit | svven/tweepy,tweepy/tweepy |
a0740ec8373a3a178e3e83b4ec2768621c697181 | versions/rattoolsversions.py | versions/rattoolsversions.py | #!/usr/bin/env python
#
# RatToolsDev
#
# The development versions of rattools
#
# Author P G Jones - 15/10/2012 <p.g.jones@qmul.ac.uk> : First revision
####################################################################################################
import rattools
class RatToolsDev(rattools.RatToolsDevelopment):... | #!/usr/bin/env python
#
# RatToolsDev
#
# The development versions of rattools
#
# Author P G Jones - 15/10/2012 <p.g.jones@qmul.ac.uk> : First revision
####################################################################################################
import rattools
class RatToolsDev(rattools.RatToolsDevelopment):... | Add fixed release rat-tools versions 4, 4.1, 4.2 | Add fixed release rat-tools versions 4, 4.1, 4.2
| Python | mit | mjmottram/snoing,mjmottram/snoing |
988f4aec1588f409f296e89acb47040cb2606cf8 | ocradmin/plugins/numpy_nodes.py | ocradmin/plugins/numpy_nodes.py |
import node
import manager
import stages
import numpy
class Rotate90Node(node.Node):
"""
Rotate a Numpy image by num*90 degrees.
"""
arity = 1
stage = stages.FILTER_BINARY
name = "Numpy::Rotate90"
_parameters = [{
"name": "num",
"value": 1,
}]
... |
import node
import manager
import stages
import numpy
class Rotate90Node(node.Node):
"""
Rotate a Numpy image by num*90 degrees.
"""
arity = 1
stage = stages.FILTER_BINARY
name = "Numpy::Rotate90"
_parameters = [{
"name": "num",
"value": 1,
}]
... | Add a grayscale rotation node (for testing) | Add a grayscale rotation node (for testing)
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium |
dd237d82426ebbc3d2854641e8e73e2001857b67 | damn/templatetags/damn.py | damn/templatetags/damn.py |
from django import template
from django.utils.safestring import mark_safe
from ..processors import AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] ... |
from django import template
from django.utils.safestring import mark_safe
from ..processors import AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] ... | Rename 'name' argument to 'filename' | Rename 'name' argument to 'filename'
| Python | bsd-2-clause | funkybob/django-amn |
7769e5ddd5784b7e56b75fc33f25b0f40ecaa99e | cryptex/exchange/__init__.py | cryptex/exchange/__init__.py | from cryptex.exchange.exchange import Exchange
from cryptex.exchange.cryptsy import Cryptsy
from cryptex.exchange.btce import BTCE
| from cryptex.exchange.exchange import Exchange
from cryptex.exchange.cryptsy import Cryptsy, CryptsyPublic
from cryptex.exchange.btce import BTCE, BTCEPublic
| Add public imports to exchange module | Add public imports to exchange module
| Python | mit | coink/cryptex |
88f341c6a9d079c89537feb1fb0aa8908732421a | evennia/server/migrations/0002_auto_20190128_1820.py | evennia/server/migrations/0002_auto_20190128_1820.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-28 18:20
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
from evennia.utils.utils import to_bytes
def migrate_serverconf(apps, schema_editor):
"""
Move server conf from a custom binary field into a PickleO... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-28 18:20
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
from evennia.utils.utils import to_bytes, to_str
def migrate_serverconf(apps, schema_editor):
"""
Move server conf from a custom binary field into a... | Fix migration for various situations | Fix migration for various situations
| Python | bsd-3-clause | jamesbeebop/evennia,jamesbeebop/evennia,jamesbeebop/evennia |
f3dd0c94c0c7be2a5ebc2c0df59dd9fb15969eb9 | ghpythonremote/_configure_ironpython_installation.py | ghpythonremote/_configure_ironpython_installation.py | import sys
import pip
from .helpers import get_rhino_ironpython_path
if __name__ == '__main__':
location = None
if len(sys.argv) > 1:
location = sys.argv[1]
rhino_ironpython_path = get_rhino_ironpython_path(location=location)
package_name = __package__.split('.')[0]
pip_cmd = ['install', pa... | import sys
import pip
import logging
from .helpers import get_rhino_ironpython_path
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
if __name__ == '__main__':
location = None
if len(sys.argv) > 1:
location = sys.argv[1]
rhino_ironpython_path = get_rhino_ironpython_path(... | Correct --no-binary option, incorrect formatting in pypi doc | Correct --no-binary option, incorrect formatting in pypi doc
| Python | mit | Digital-Structures/ghpythonremote,pilcru/ghpythonremote |
b9dd3a5d2f52f6cebb55b322cf4ddb2b9e1d8ccc | arches/db/install/truncate_db.py | arches/db/install/truncate_db.py | import os
import inspect
import subprocess
from django.template import Template
from django.template import Context
from django.conf import settings
from arches.management.commands import utils
def create_sqlfile(database_settings, path_to_file):
context = Context(database_settings)
postgres_version = s... | import os
import inspect
import subprocess
from django.template import Template
from django.template import Context
from django.conf import settings
from arches.management.commands import utils
def create_sqlfile(database_settings, path_to_file):
context = Context(database_settings)
postgres_version = s... | Remove reference to postgis template. Django now installs postgis when database is created. | Remove reference to postgis template. Django now installs postgis when database is created.
| Python | agpl-3.0 | archesproject/arches,cvast/arches,cvast/arches,archesproject/arches,cvast/arches,cvast/arches,archesproject/arches,archesproject/arches |
7a308233707e7e024311a3767367875921c6217b | graphiter/models.py | graphiter/models.py | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)... | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)... | Add blank=True for Page.time_until field | Add blank=True for Page.time_until field | Python | bsd-2-clause | jwineinger/django-graphiter |
fd697a0a4a4aeb3455ec7b7e8b3ed38ce0eb4502 | test/sockettest.py | test/sockettest.py | import kaa
@kaa.coroutine()
def new_client(client):
ip, port = client.address
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = tls.TLSSocket()
#remote = kaa.Socket()
yield remote.connect... | import logging
import kaa
from kaa.net.tls import TLSSocket
log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port... | Fix TLS support in socket test | Fix TLS support in socket test
| Python | lgpl-2.1 | freevo/kaa-base,freevo/kaa-base |
91c620e228ad73e2e34efbd60813ed35b3f9ef46 | tests/test_dtool_dataset_freeze.py | tests/test_dtool_dataset_freeze.py | """Test the ``dtool dataset create`` command."""
import os
import shutil
from click.testing import CliRunner
from dtoolcore import DataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
from dtool_create.dataset im... | """Test the ``dtool dataset create`` command."""
import os
import shutil
from click.testing import CliRunner
from dtoolcore import DataSet, ProtoDataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
from dtool_cre... | Fix the freeze functional test | Fix the freeze functional test
| Python | mit | jic-dtool/dtool-create |
fc9296957122fe7499711c0b0801c96e286b6725 | turnstile/utils.py | turnstile/utils.py | import sys
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition(':')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ImportError, ValueError, AttributeError) as e... | import sys
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition(':')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ImportError, ValueError, AttributeError) as e... | Add a context manager to ignore exceptions | Add a context manager to ignore exceptions
| Python | apache-2.0 | klmitch/turnstile |
d18d4f72ed24177143a9dbcf74fc1c001235ded5 | batch_effect.py | batch_effect.py | #!/usr/bin/env python
import argparse
import csv
import shutil
import subprocess
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Chain together Inkscape extensions")
parser.add_argument('--id', type=str, action='append', dest='ids', default=[],
help=... | #!/usr/bin/env python
import argparse
import csv
import shutil
import subprocess
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Chain together Inkscape extensions")
parser.add_argument('--id', type=str, action='append', dest='ids', default=[],
help=... | Clarify --id parameter help text | Clarify --id parameter help text
| Python | mit | jturner314/inkscape-batch-effect |
3672d178ac4f9a3f9308acf1e43e9eea663fe30a | OnlineParticipationDataset/pipelines.py | OnlineParticipationDataset/pipelines.py | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
class Onlineparticipationdataset... | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
path = "downloads"
class Onl... | Create path if it doesnt exists | Create path if it doesnt exists
| Python | mit | Liebeck/OnlineParticipationDatasets |
4fd6a98a887a59dabcc41361a6ba2791393d875e | test/tests/python-pip-requests-ssl/container.py | test/tests/python-pip-requests-ssl/container.py | import pip
pip.main(['install', '-q', 'requests'])
import requests
r = requests.get('https://google.com')
assert(r.status_code == 200)
| import subprocess, sys
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'requests'])
import requests
r = requests.get('https://google.com')
assert(r.status_code == 200)
| Fix "python-pip-requests-ssl" test to no longer "import pip" | Fix "python-pip-requests-ssl" test to no longer "import pip"
(https://blog.python.org/2018/04/pip-10-has-been-released.html)
> In addition, the previously announced reorganisation of pip's internals has now taken place. Unless you are the author of code that imports the pip module (or a user of such code), this chang... | Python | apache-2.0 | docker-library/official-images,docker-flink/official-images,docker-library/official-images,31z4/official-images,davidl-zend/official-images,jperrin/official-images,infosiftr/stackbrew,neo-technology/docker-official-images,31z4/official-images,dinogun/official-images,docker-flink/official-images,neo-technology/docker-of... |
e75201bb34f7e930c04e393ff630fdbc1549fd77 | core/admin/migrations/versions/8f9ea78776f4_.py | core/admin/migrations/versions/8f9ea78776f4_.py | """empty message
Revision ID: 8f9ea78776f4
Revises: 3b7eee912b41
Create Date: 2022-03-11 13:53:08.996055
"""
# revision identifiers, used by Alembic.
revision = '8f9ea78776f4'
down_revision = '3b7eee912b41'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('user', sa.Column('spam_mar... | """empty message
Revision ID: 8f9ea78776f4
Revises: 3b7eee912b41
Create Date: 2022-03-11 13:53:08.996055
"""
# revision identifiers, used by Alembic.
revision = '8f9ea78776f4'
down_revision = '3b7eee912b41'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('user', sa.Column('spam_mar... | Add default to column spam_mark_as_read | Add default to column spam_mark_as_read | Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io |
9c44a1c97b1ba60fd7340c15dd82ebe1ceb6d8c3 | icekit/project/settings/_production.py | icekit/project/settings/_production.py | from ._base import *
SITE_PUBLIC_PORT = None # Default: SITE_PORT
# DJANGO ######################################################################
CACHES['default'].update({
# 'BACKEND': 'django_redis.cache.RedisCache',
'BACKEND': 'redis_lock.django_cache.RedisCache',
'LOCATION': 'redis://redis:6379/1',
... | from ._base import *
SITE_PUBLIC_PORT = None # Default: SITE_PORT
# DJANGO ######################################################################
CACHES['default'].update({
# 'BACKEND': 'django_redis.cache.RedisCache',
'BACKEND': 'redis_lock.django_cache.RedisCache',
'LOCATION': 'redis://redis:6379/1',
... | Disable cache middleware and template loader by default. Avoid premature optimisation. | Disable cache middleware and template loader by default. Avoid premature optimisation.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
a244623642cdf26bd6615cdc7ff2540c9361d10d | tmapi/models/typed.py | tmapi/models/typed.py | from django.db import models
from construct import Construct
class Typed (Construct, models.Model):
"""Indicates that a Topic Maps construct is typed. `Association`s,
`Role`s, `Occurrence`s, and `Name`s are typed."""
type = models.ForeignKey('Topic', related_name='typed_%(class)ss')
class Meta... | from django.db import models
from tmapi.exceptions import ModelConstraintException
from construct import Construct
class Typed (Construct, models.Model):
"""Indicates that a Topic Maps construct is typed. `Association`s,
`Role`s, `Occurrence`s, and `Name`s are typed."""
type = models.ForeignKey('Topic... | Raise an exception when setting a construct's type to None. | Raise an exception when setting a construct's type to None.
| Python | apache-2.0 | ajenhl/django-tmapi |
a4931218fbb00d646dbc8de6f8861e4647ef7ab4 | lib/rapidsms/tests/test_backend_irc.py | lib/rapidsms/tests/test_backend_irc.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestLog(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = Backend(... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestBackendIRC(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = B... | Rename test class (sloppy cut n' paste job) | Rename test class (sloppy cut n' paste job)
| Python | bsd-3-clause | catalpainternational/rapidsms,caktus/rapidsms,ken-muturi/rapidsms,rapidsms/rapidsms-core-dev,catalpainternational/rapidsms,caktus/rapidsms,lsgunth/rapidsms,peterayeni/rapidsms,rapidsms/rapidsms-core-dev,lsgunth/rapidsms,dimagi/rapidsms,ken-muturi/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,ehealth... |
865651b0d23274d0dcbd9e3123ea9497a06172cf | docker_scripts/lib/common.py | docker_scripts/lib/common.py | # -*- coding: utf-8 -*-
import docker
import os
import sys
import requests
DEFAULT_TIMEOUT_SECONDS = 600
def docker_client():
# Default timeout 10 minutes
try:
timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
except ValueError as e:
print("Provided timeout value: %s cannot be parsed as i... | # -*- coding: utf-8 -*-
import docker
import os
import sys
import requests
DEFAULT_TIMEOUT_SECONDS = 600
def docker_client():
# Default timeout 10 minutes
try:
timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
except ValueError as e:
print("Provided timeout value: %s cannot be parsed as i... | Use AutoVersionClient to fix client incompatibity issues | Use AutoVersionClient to fix client incompatibity issues
Fixes #35
| Python | mit | lichia/docker-scripts,jpopelka/docker-scripts,goldmann/docker-scripts,goldmann/docker-squash,TomasTomecek/docker-scripts |
b888e6e6fac1a8dca0c8b64134de0380f9c5096b | mopidy_beets/__init__.py | mopidy_beets/__init__.py | from __future__ import unicode_literals
import os
from mopidy import ext, config
from mopidy.exceptions import ExtensionError
__version__ = '1.0.4'
class BeetsExtension(ext.Extension):
dist_name = 'Mopidy-Beets'
ext_name = 'beets'
version = __version__
def get_default_config(self):
conf_... | from __future__ import unicode_literals
import os
from mopidy import ext, config
__version__ = '1.0.4'
class BeetsExtension(ext.Extension):
dist_name = 'Mopidy-Beets'
ext_name = 'beets'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__)... | Remove env check as Mopidy checks deps automatically | ext: Remove env check as Mopidy checks deps automatically
| Python | mit | mopidy/mopidy-beets |
9d7b39708a2abd953aedf6c211fe242d86caed78 | pymacaroons/field_encryptors/secret_box_encryptor.py | pymacaroons/field_encryptors/secret_box_encryptor.py | from base64 import standard_b64encode, standard_b64decode
import nacl.bindings
import nacl.utils
from nacl.secret import SecretBox
from pymacaroons.field_encryptors.base_field_encryptor import (
BaseFieldEncryptor
)
from pymacaroons.utils import (
truncate_or_pad, convert_to_bytes, convert_to_string
)
class... | from base64 import standard_b64encode, standard_b64decode
import nacl.bindings
import nacl.utils
from nacl.secret import SecretBox
from pymacaroons.field_encryptors.base_field_encryptor import (
BaseFieldEncryptor
)
from pymacaroons.utils import (
truncate_or_pad, convert_to_bytes, convert_to_string
)
class... | Break how flake8 wants me to break | Break how flake8 wants me to break
| Python | mit | matrix-org/pymacaroons,matrix-org/pymacaroons |
158987eebbcd2d58270cf55cc42aa6e2e5738390 | pathvalidate/__init__.py | pathvalidate/__init__.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from ._common import _validate_null_string
from ._app import validate_excel_sheet_name
from ._app import sanitize_excel_sheet_name
from ._file import validate_filename
from ._file import validate_... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from ._error import NullNameError
from ._error import InvalidCharError
from ._common import _validate_null_string
from ._app import validate_excel_sheet_name
from ._app import sanitize_excel_shee... | Add imports for error classes | Add imports for error classes
| Python | mit | thombashi/pathvalidate |
b916f1e3ad294c780c782e93222f018fa57ee981 | apps/bluebottle_utils/models.py | apps/bluebottle_utils/models.py | from django.db import models
from django_countries import CountryField
class Address(models.Model):
"""
A postal address.
"""
address_line1 = models.CharField(max_length=100, blank=True)
address_line2 = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100, blank=... | from django.db import models
from django_countries import CountryField
class Address(models.Model):
"""
A postal address.
"""
address_line1 = models.CharField(max_length=100, blank=True)
address_line2 = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100, blank=... | Allow country to be empty in Address model. | Allow country to be empty in Address model.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site |
bc8e064e41d43a4579c8111f1480b55e660ca186 | pep8ify/fixes/fix_tabs.py | pep8ify/fixes/fix_tabs.py | from __future__ import unicode_literals
from lib2to3.fixer_base import BaseFix
from lib2to3.pytree import Leaf
SPACES = ' ' * 4
class FixTabs(BaseFix):
'''
For new projects, spaces-only are strongly recommended over tabs. Most
editors have features that make this easy to do.
'''
def match(self, ... | from __future__ import unicode_literals
from lib2to3.fixer_base import BaseFix
from lib2to3.pytree import Leaf
from .utils import SPACES
class FixTabs(BaseFix):
'''
For new projects, spaces-only are strongly recommended over tabs. Most
editors have features that make this easy to do.
'''
def mat... | Use globally define number of spaces. | Clean-up: Use globally define number of spaces.
| Python | apache-2.0 | spulec/pep8ify |
64533459ffa6c33d4708bbc6ff0de9f295ef771d | permissions/tests/base.py | permissions/tests/base.py | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
d... | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
d... | Add mock User and Anonymous user classes for testing | Add mock User and Anonymous user classes for testing
| Python | mit | PSU-OIT-ARC/django-perms,wylee/django-perms |
80264289fa7fc4085069df011cd8499c64767dc5 | elang/tools/pre-commit.py | elang/tools/pre-commit.py | #
# Pre-commit check
#
import pipes
import sys
def main():
git_pipe = pipes.Template()
git_pipe.prepend('git diff --cached --name-status', '.-')
diff_output = git_pipe.open('files', 'r')
lines = diff_output.readlines()
exit_code = 0
for line in lines:
line = line.rstrip()... | #
# Pre-commit check
#
import pipes
import sys
EXCLUDE_DIRS = [
'base/',
'build/',
'testing/',
'third_party/',
]
def shouldCheck(path):
for dir in EXCLUDE_DIRS:
if path.startswith(dir):
return False
return True
def main():
git_pipe = pipes.Templat... | Exclude base/, build/, third_party/ and tools/ from cpplint. | tools: Exclude base/, build/, third_party/ and tools/ from cpplint.
| Python | apache-2.0 | eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang |
cefaa6c8f0fd3c26be2bf6fba75d01b2f5095a34 | strapmin/widgets.py | strapmin/widgets.py | from django import forms
from django.forms.util import flatatt
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
class RichTextEditorWidget(forms.Textarea):
class Media:
js = ('admin/js/ckeditor/ckeditor.... | from django import forms
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
try:
from django.forms.utils import flatatt
except ImportError:
from django.forms.util import flatatt
class RichTextEditorWidget... | Fix flatatt import path for Django 1.9 | Fix flatatt import path for Django 1.9
| Python | bsd-2-clause | knyghty/strapmin,knyghty/strapmin,knyghty/strapmin |
61909686132143db127deb31d582e44f5b198729 | project/gym_app/admin.py | project/gym_app/admin.py | from django.contrib import admin
from gym_app.models import Task, Athlete, PersonalTrainer, BodyScreening, WorkoutPlan, Tracker, MailBox, Message
from django.contrib.auth.models import Permission
# Register your models here.
admin.site.register(Task)
admin.site.register(Permission)
admin.site.register(Athlete)
admin.s... | from django.contrib import admin
from gym_app.models import Task
from django.contrib.auth.models import Permission
# Register your models here.
admin.site.register(Task)
admin.site.register(Permission)
| Remove permission to edit tables | Remove permission to edit tables
| Python | mit | brunoliveira8/managyment,brunoliveira8/managyment,brunoliveira8/managyment |
752cc60f8c41d098ff8772ed400ac3ae209d9e0f | lib/exp/featx/__init__.py | lib/exp/featx/__init__.py | __all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.prepare import Prepare
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):
ss = Slider(self... | __all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):
ss = Slider(self.roo... | Use `reducer` to replace `prepare` | Use `reducer` to replace `prepare`
| Python | agpl-3.0 | speed-of-light/pyslider |
159e1e210480c0037b3a550e70b77dbfce34bbca | ptyme/ptyme.py | ptyme/ptyme.py | #!/bin/env python3
from sys import argv
def main():
parseArgs()
print("Nope.")
print(argv)
def parseArgs():
if len(argv) > 1:
time = argv[1].split('h')
print(time)
if 'm' not in time[0] and 'n' not in time[0]:
hours = time[0]
else:
house = 0
... | #!/bin/env python3
from sys import argv
def main():
parseArgs()
print("Nope.")
print(argv)
# go through via characters
def parseArgsChar():
pass()
# while this works, it only works when _h_m_s format
# might want to not do that
def parseArgs():
if len(argv) > 1:
time = argv[1].split('h')... | Update current parse, add alt parse frame | Update current parse, add alt parse frame
| Python | mit | jabocg/ptyme |
dff5a8650c5d7ed5b5bab12b36ac5d61541dbb4e | python/day3.py | python/day3.py | import sys
def read_sides(line):
return map(int, line.split())
def valid_triangle((a, b, c)):
return a + b > c and b + c > a and a + c > b
if __name__ == '__main__':
print len(filter(valid_triangle, map(read_sides, sys.stdin)))
| import sys
import itertools
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
def transpose(xs):
return zip(*xs)
def read_sides(line):
return map(int, line.split())
def valid_triangle((a, b, c)):
return a + b > c a... | Implement part 2 of day 3 Python solution. | Implement part 2 of day 3 Python solution.
| Python | mit | jonathanj/advent2016 |
65f0ef0ae523059db6ecf3856c9e2695cad81d38 | montage/__init__.py | montage/__init__.py | from commands import *
from wrappers import *
__version__ = '0.9.1'
| from commands import *
from wrappers import *
__version__ = '0.9.1'
# Check whether Montage is installed
installed = False
for dir in os.environ['PATH'].split(':'):
if os.path.exists(dir + '/mProject'):
installed = True
break
if not installed:
raise Exception("Montage commands are not in your... | Check whether Montage commands are available | Check whether Montage commands are available
| Python | bsd-3-clause | astrofrog/montage-wrapper,astrofrog/python-montage,astrofrog/montage-wrapper,jat255/montage-wrapper,vterron/montage-wrapper,astropy/montage-wrapper |
a2d77c167ea8ae3a62183a56b10cd121dc476481 | openfisca_france/conf/cache_blacklist.py | openfisca_france/conf/cache_blacklist.py | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'... | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logement_R0',
'... | Add intermediary variables in cache blacklist | Add intermediary variables in cache blacklist
| Python | agpl-3.0 | antoinearnoud/openfisca-france,antoinearnoud/openfisca-france,sgmap/openfisca-france,sgmap/openfisca-france |
f34330817414f72494aec359c169e5d6d9d1568f | examples/quotes/quotes.py | examples/quotes/quotes.py | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
my_name = input("Name: ")
nw0.advertise(my_name)
while True:
services = [(name,... | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
def main(address_pattern=None):
my_name = input("Name: ")
nw0.advertise(my_n... | Allow for a wildcard address | Allow for a wildcard address
| Python | mit | tjguk/networkzero,tjguk/networkzero,tjguk/networkzero |
6fe391b2e2f9b88a6835a6636a5d58810852ab5e | pyhole/tests/test_log.py | pyhole/tests/test_log.py | # Copyright 2011-2016 Josh Kearney
#
# 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 agre... | # Copyright 2011-2016 Josh Kearney
#
# 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 agre... | Use setup_logger properly in tests. | Use setup_logger properly in tests.
| Python | apache-2.0 | jk0/pyhole,jk0/pyhole,jk0/pyhole |
f868a9181d659c2440a50e6e325ad2ae5b99f5c8 | project_recalculate/models/resource_calendar.py | project_recalculate/models/resource_calendar.py | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_... | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_... | Define UTC as tz in get_working_days_of_date method | [FIX] Define UTC as tz in get_working_days_of_date method
| Python | agpl-3.0 | Endika/project,NeovaHealth/project-service,OCA/project-service,Antiun/project,eezee-it/project-service,Antiun/project-service,acsone/project-service,dreispt/project-service,xpansa/project-service,ddico/project,acsone/project,akretion/project-service,sergiocorato/project-service,dreispt/project |
1a830d0581f2baed76cb48eeee5f32d465737657 | src/artgraph/plugins/infobox.py | src/artgraph/plugins/infobox.py | from artgraph.node import NodeTypes
from artgraph.plugins import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
@staticmethod
def get_target_node_type():
return NodeTypes.ARTIST
def get_nodes(self):
from artgraph.node import Node, N... | from artgraph.node import NodeTypes
from artgraph.plugins import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
@staticmethod
def get_target_node_type():
return NodeTypes.ARTIST
def get_nodes(self):
from artgraph.node import Node, N... | Check if there are associated acts before querying for them | Check if there are associated acts before querying for them | Python | mit | dMaggot/ArtistGraph |
a5441719e8f12cc16189b2ca110c878decfed120 | airflow/operators/mysql_operator.py | airflow/operators/mysql_operator.py | import logging
from airflow.hooks import MySqlHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class MySqlOperator(BaseOperator):
"""
Executes sql code in a specific MySQL database
:param mysql_conn_id: reference to a specific mysql database
:type mysql_conn_id: ... | import logging
from airflow.hooks import MySqlHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class MySqlOperator(BaseOperator):
"""
Executes sql code in a specific MySQL database
:param mysql_conn_id: reference to a specific mysql database
:type mysql_conn_id: ... | Allow auto-commit option for Mysql Operator | Allow auto-commit option for Mysql Operator
| Python | apache-2.0 | jlowin/airflow,lxneng/incubator-airflow,cjqian/incubator-airflow,dhuang/incubator-airflow,gritlogic/incubator-airflow,forevernull/incubator-airflow,modsy/incubator-airflow,jesusfcr/airflow,ronfung/incubator-airflow,nathanielvarona/airflow,holygits/incubator-airflow,akosel/incubator-airflow,wxiang7/airflow,fenglu-g/incu... |
21d9b2f89a7eb9a6801a48c2586cc360e6be47c3 | LTA_to_UVFITS.py | LTA_to_UVFITS.py | def lta_to_uvfits():
lta_files = glob.glob('*.lta*')
#flag_files = glob.glob('*.FLAGS*')
for i in range(len(lta_files)):
lta_file_name = lta_files[i]
uvfits_file_name = lta_file_name +'.UVFITS'
spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name )
| def lta_to_uvfits():
lta_files = glob.glob('*.lta*')
#flag_files = glob.glob('*.FLAGS*')
for i in range(len(lta_files)):
lta_file_name = lta_files[i]
uvfits_file_name = lta_file_name +'.UVFITS'
spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name )
return lta_files
| Return LTA files to use as argument in main thread code | Return LTA files to use as argument in main thread code
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu |
dee7b02d0cdd6969b4228086ab9af77ad1da60ef | asymmetric_jwt_auth/models.py | asymmetric_jwt_auth/models.py | from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from cryptography.hazmat.primitives.serialization import load_ssh_public_key
from cryptography.hazmat.backends import default_backend
def validate_public_key(val... | from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from cryptography.hazmat.primitives.serialization import load_pem_public_key, load_ssh_public_key
from cryptography.hazmat.backends import default_backend
def va... | Allow PEM format keys through validation | Allow PEM format keys through validation
| Python | isc | crgwbr/asymmetric_jwt_auth,crgwbr/asymmetric_jwt_auth |
5aef0b64477248f6cdadfd864a6d05cbc6939f09 | trex/serializers.py | trex/serializers.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import (
HyperlinkedModelSerializer, HyperlinkedIdentityField,
)
from trex.models.project import Project, Entry
class ProjectSerializer(Hype... | Use HyperlinkedIdentityField for entries in ProjectDetailSerializer | Use HyperlinkedIdentityField for entries in ProjectDetailSerializer
| Python | mit | bjoernricks/trex,bjoernricks/trex |
90ab0bfbac851a52f0e48f5186a727692e699a6f | geodj/youtube.py | geodj/youtube.py | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'viewCount'
query.racy = 'exclude'
... | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'viewC... | Use smart_str and include artist in results | Use smart_str and include artist in results
| Python | mit | 6/GeoDJ,6/GeoDJ |
8815507f8e334238d269468e08c22f4415e58528 | spacy/lang/es/__init__.py | spacy/lang/es/__init__.py | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...language import Language
from ...lemmatizerlookup impo... | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...language import Language
from ...lemmatizerlookup impo... | Move SpanishDefaults out of Language class, for pickle | Move SpanishDefaults out of Language class, for pickle
| Python | mit | recognai/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spa... |
13da95de0f2fb17ec6cbf005be33db3b3d348831 | motivation_text/models.py | motivation_text/models.py | from django.db import models
from patient.models import Patient
from django.utils.encoding import smart_unicode
class MotivationText(models.Model):
patient = models.ForeignKey(Patient, null=False)
text = models.TextField(default='', blank=False)
time_created = models.DateTimeField(null=False, auto_now_ad... | from django.db import models
from patient.models import Patient
from django.utils.encoding import smart_unicode
class MotivationText(models.Model):
patient = models.ForeignKey(Patient, null=False)
text = models.TextField(default='', blank=False)
time_created = models.DateTimeField(null=False, auto_now_ad... | Improve unicode for motivational texts | Improve unicode for motivational texts
| Python | mit | sigurdsa/angelika-api |
f42ba1bebb0e7f92222d8a66f94e2550b4dde9e1 | helpers/custom_filters.py | helpers/custom_filters.py | import json
def strslice(s, length):
if not isinstance(s, basestring):
s = str(s)
return s[:length]
def urlencode(s):
if isinstance(s, unicode):
s = s.encode('utf-8')
import urllib
return urllib.quote(s)
def json_filter(data):
return json.dumps(data)
def datetimeformat(value,... | import json
def strslice(s, length):
if not isinstance(s, basestring):
s = str(s)
return s[:length]
def urlencode(s):
if isinstance(s, unicode):
s = s.encode('utf-8')
import urllib
return urllib.quote(s)
def json_filter(data):
return json.dumps(data)
def datetimeformat(value,... | Add a neattime custom filter to give me pretty times. | Add a neattime custom filter to give me pretty times. | Python | agpl-3.0 | watchcat/cbu-rotterdam,codeforamerica/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,watchcat/cbu-rotterdam,localprojects/Change-By-Us,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,watchcat/cbu-rotterdam,codeforeurope/Change-By-Us,codeforamerica/Change-By-Us,codeforeurope/... |
3af22fd5583ee110f731b9e1ebecba67ebee2bd4 | sendwithus/exceptions.py | sendwithus/exceptions.py | class SendwithusError(Exception):
"""Base class for Sendwithus API errors"""
class AuthenticationError(SendwithusError):
"""API Authentication Failed"""
class APIError(SendwithusError):
"""4xx - Invalid Request (Client error)"""
class ServerError(SendwithusError):
"""5xx - Failed Request (Server e... | class SendwithusError(Exception):
"""Base class for Sendwithus API errors"""
def __init__(self, content=None):
self.content = content
class AuthenticationError(SendwithusError):
"""API Authentication Failed"""
class APIError(SendwithusError):
"""4xx - Invalid Request (Client error)"""
cla... | Add a constructor to SendwithusError that stores content | Add a constructor to SendwithusError that stores content
| Python | apache-2.0 | sendwithus/sendwithus_python |
93512f1837a4e72752d4ffa07ac49e1f2cd5a7f6 | opensimplex_test.py | opensimplex_test.py | import random
import time
from PIL import Image # Depends on the Pillow lib
from opensimplex import OpenSimplexNoise
WIDTH = 512
HEIGHT = 512
FEATURE_SIZE = 24
def main():
random.seed(time.time())
seed = random.randint(0, 100000)
simplex = OpenSimplexNoise(seed)
im = Image.new('L', (WIDTH, HEIGHT))
... |
from PIL import Image # Depends on the Pillow lib
from opensimplex import OpenSimplexNoise
WIDTH = 512
HEIGHT = 512
FEATURE_SIZE = 24
def main():
simplex = OpenSimplexNoise()
im = Image.new('L', (WIDTH, HEIGHT))
for y in range(0, HEIGHT):
for x in range(0, WIDTH):
#value = simplex.n... | Use default seed for the test. | Use default seed for the test.
| Python | mit | lmas/opensimplex,antiface/opensimplex |
9249dc161e9fdd64e15a42f644232c43cb6875b2 | src/dependenpy/plugins.py | src/dependenpy/plugins.py | # -*- coding: utf-8 -*-
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DSM as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'depen... | # -*- coding: utf-8 -*-
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
i... | Update archan provider for archan 3.0 | Update archan provider for archan 3.0
| Python | isc | Pawamoy/dependenpy,Pawamoy/dependenpy |
5da820b85f9e55a54639856bdd698c35b866833c | fireplace/cards/gvg/neutral_epic.py | fireplace/cards/gvg/neutral_epic.py | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_MINION_SUMMON(self, minion):
if minion.atk == 1:
return [Buff(minion, "GVG_104a")]
| from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
| Fix Hobgoblin to trigger only on cards played | Fix Hobgoblin to trigger only on cards played
| Python | agpl-3.0 | smallnamespace/fireplace,jleclanche/fireplace,liujimj/fireplace,Meerkov/fireplace,amw2104/fireplace,butozerca/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,NightKev/fireplace,smallnamespace/fireplace,Meerkov/fireplace,liujimj/fireplace,butozerca/fireplace,Ragowit/fireplace,beheh/fireplace,oftc-ftw/fireplace,amw2104/fi... |
48b2460c718af88e8140b108d4a9acd9258ade8c | gargoyle/__init__.py | gargoyle/__init__.py | try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| __import__('pkg_resources').declare_namespace(__name__)
| Change to vanilla namespace package | Change to vanilla namespace package
| Python | apache-2.0 | disqus/gutter,disqus/gutter,kalail/gutter,kalail/gutter,kalail/gutter |
c083481eed1578551daab7ece2e34b3ff4aece82 | accelerator/migrations/0044_add_sitetree_sidenav_toggle.py | accelerator/migrations/0044_add_sitetree_sidenav_toggle.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-03-20 18:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
operations = [
migrations.Re... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-03-20 18:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0043_remove_exclude_fields'),
]
help_text = 'Show the new-style side ... | Fix style on migration - waste of time, but whatever | Fix style on migration - waste of time, but whatever
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
9cc4ce152ba8d683db1371a963dae2621f1b8fc6 | dbaas/dbaas/celeryconfig.py | dbaas/dbaas/celeryconfig.py | import os
REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379')
BROKER_URL = os.getenv(
'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT)
CELERYD_TASK_TIME_LIMIT = 10800
CELERY_TRACK_STARTED = True
CELERY_IGNORE_RESULT = False
CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheB... | import os
from django.conf import settings
REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379')
BROKER_URL = os.getenv(
'DBAAS_NOTIFICATION_BROKER_URL', 'redis://{}:{}/0'.format(settings.REDIS_HOST, REDIS_PORT))
CELERYD_TASK_TIME_LIMIT = 10800
CELERY_TRACK_STARTED = True
CELERY_IGNORE_RESULT = False
C... | Fix celery config to respect the host configured on settings | Fix celery config to respect the host configured on settings
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
a8ec60daaee52603a1c3bab879a5eee9f0fd931b | ddd/dataobjects/datatype.py | ddd/dataobjects/datatype.py | '''
Created on 24.04.2016
@author: killian
'''
from objects import dddobject,DataObject
from conversions import DddConversion
@dddobject('datatype')
class DddDatatype(DataObject):
def __init__(self,basetype='',conversion=None,unit='-',constant=False):
self.basetype=basetype
if not conversion:
... | '''
Created on 24.04.2016
@author: killian
'''
from objects import dddobject,DataObject
from conversions import DddConversion
@dddobject('datatype')
class DddDatatype(DataObject):
def __init__(self,basetype='',bitsize=8,signed=False,conversion=None,unit='-',constant=False):
self.basetype=basetype
... | Split basetype of DddDatatype into basetype,bitsize,signed | Split basetype of DddDatatype into basetype,bitsize,signed | Python | mit | toesus/ddd,Sauci/ddd,toesus/ddd,Sauci/ddd,Sauci/ddd |
6bd59ef149ec32f7d0a64ea2ad50a2729aceb6f5 | fluent_contents/models/mixins.py | fluent_contents/models/mixins.py | from django.core.cache import cache
class CachedModelMixin(object):
"""
Mixin to add cache expiration to a model.
"""
clear_cache_on_add = False
def save(self, *args, **kwargs):
is_new = not self.pk or self._state.adding
super(CachedModelMixin, self).save(*args, **kwargs)
... | from django.core.cache import cache
class CachedModelMixin(object):
"""
Mixin to add cache expiration to a model.
"""
clear_cache_on_add = False
def save(self, *args, **kwargs):
is_new = not self.pk or self._state.adding
super(CachedModelMixin, self).save(*args, **kwargs)
... | Make sure our CachedModelMixin.delete() also returns the collector results | Make sure our CachedModelMixin.delete() also returns the collector results
| Python | apache-2.0 | edoburu/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents |
a88f0ab8be669f573f2869617717653bb008e11b | sheldon/bot.py | sheldon/bot.py | # -*- coding: utf-8 -*-
"""
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
__author__ = 'Lises team'
__version__ = '0.1'
__email__ = 'zhidkovseva@gmail.com'
class Sheldon():
pass
class Plugin():
pass
class Adapter():
pass | # -*- coding: utf-8 -*-
"""
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
# Python 2 compatibility
if sys.version_info[0] == 2:
# Exceptions for bot
from exceptions import *
# Tool for loading plugins and adapters
from modules import *
# To... | Update structure of Sheldon class | Update structure of Sheldon class
| Python | mit | lises/sheldon |
caa4dcdcf7e936f352eea22513433d8f8deca2ab | sahara/tests/unit/utils/test_hashabledict.py | sahara/tests/unit/utils/test_hashabledict.py | # Copyright (c) 2013 Hortonworks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | # Copyright (c) 2013 Hortonworks, 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 ... | Improve unit test for HashableDict | Improve unit test for HashableDict
We have HashableDict introduced to network info storing, but hash
function of this implementation was never tested in unit tests.
Change-Id: Id48c9172ca63e19b397dc131d85ed631874142cd
| Python | apache-2.0 | openstack/sahara,esikachev/sahara-backup,ekasitk/sahara,henaras/sahara,egafford/sahara,tellesnobrega/sahara,ekasitk/sahara,egafford/sahara,henaras/sahara,zhangjunli177/sahara,zhangjunli177/sahara,esikachev/sahara-backup,esikachev/sahara-backup,openstack/sahara,henaras/sahara,ekasitk/sahara,crobby/sahara,crobby/sahara,c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.