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 |
|---|---|---|---|---|---|---|---|---|---|
36bde060bbdb4cf9d0396719b8b82952a73bf2b5 | bucky/collector.py | bucky/collector.py |
import time
import multiprocessing
try:
from setproctitle import setproctitle
except ImportError:
def setproctitle(title):
pass
class StatsCollector(multiprocessing.Process):
def __init__(self, queue):
super(StatsCollector, self).__init__()
self.queue = queue
def close(sel... |
import time
import multiprocessing
try:
from setproctitle import setproctitle
except ImportError:
def setproctitle(title):
pass
class StatsCollector(multiprocessing.Process):
def __init__(self, queue):
super(StatsCollector, self).__init__()
self.queue = queue
def close(sel... | Change the back-off algo for failures | Change the back-off algo for failures
| Python | apache-2.0 | jsiembida/bucky3 |
9f005120c6d408e8cf3097dd74d5dada24305c88 | src/jsonlogger.py | src/jsonlogger.py | import logging
import json
import re
from datetime import datetime
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
def parse(self):
standard_formatters = re.compile(r'\((.*?)\)', re.IGNORECASE)
return standard_formatters.findall(self._... | import logging
import json
import re
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
def parse(self):
standard_formatters = re.compile(r'\((.*?)\)', re.IGNORECASE)
return standard_formatters.findall(self._fmt)
def format(self, re... | Use the same logic to format message and asctime than the standard library. | Use the same logic to format message and asctime than the standard library.
This way we producte better message text on some circumstances when not logging
a string and use the date formater from the base class that uses the date format
configured from a file or a dict.
| Python | bsd-2-clause | madzak/python-json-logger,bbc/python-json-logger |
937fd7c07dfe98a086a9af07f0f7b316a6f2f6d8 | invoke/main.py | invoke/main.py | """
Invoke's own 'binary' entrypoint.
Dogfoods the `program` module.
"""
from ._version import __version__
from .program import Program
program = Program(name="Invoke", binary='inv[oke]', version=__version__)
| """
Invoke's own 'binary' entrypoint.
Dogfoods the `program` module.
"""
from . import __version__, Program
program = Program(
name="Invoke",
binary='inv[oke]',
version=__version__,
)
| Clean up binstub a bit | Clean up binstub a bit
| Python | bsd-2-clause | frol/invoke,frol/invoke,pyinvoke/invoke,mkusz/invoke,mattrobenolt/invoke,pfmoore/invoke,pyinvoke/invoke,mkusz/invoke,mattrobenolt/invoke,pfmoore/invoke |
0b1587a484bd63632dbddfe5f0a4fe3c898e4fb0 | awacs/dynamodb.py | awacs/dynamodb.py | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from aws import Action
service_name = 'Amazon DynamoDB'
prefix = 'dynamodb'
BatchGetItem = Action(prefix, 'BatchGetItem')
CreateTable = Action(prefix, 'CreateTable')
DeleteItem = Action(prefix, 'DeleteI... | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from aws import Action
from aws import ARN as BASE_ARN
service_name = 'Amazon DynamoDB'
prefix = 'dynamodb'
class ARN(BASE_ARN):
def __init__(self, region, account, table=None, index=None):
... | Add logic for DynamoDB ARNs | Add logic for DynamoDB ARNs
See:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/UsingIAMWithDDB.html
I also decided not to name the ARN object 'DynamoDB_ARN' or anything
like that, and instead went with just 'ARN' since the class is already
stored in the dynamodb module. Kind of waffling on whether ... | Python | bsd-2-clause | craigbruce/awacs,cloudtools/awacs |
f996755665c9e55af5139a473b859aa0eb507515 | back2back/wsgi.py | back2back/wsgi.py | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "back2back.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling
application = Cling(MediaCling(get_wsgi_application()))
| import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "back2back.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
| Remove MediaCling as there isn't any. | Remove MediaCling as there isn't any.
| Python | bsd-2-clause | mjtamlyn/back2back,mjtamlyn/back2back,mjtamlyn/back2back,mjtamlyn/back2back |
3e98ed8801d380b6ab40156b1f20a1f9fe23a755 | books/views.py | books/views.py | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.all()
serializer_class = BookPageSeri... | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.order_by('page_number')
serializer_cl... | Order book pages by page number. | Order book pages by page number.
| Python | mit | Pepedou/Famas |
fe7ab3060c43d509f995cc64998139a623b21a4a | bot/cogs/owner.py | bot/cogs/owner.py | import discord
from discord.ext import commands
class Owner:
"""Admin-only commands that make the bot dynamic."""
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.is_owner()
async def close(self, ctx: commands.Context):
"""Closes the bot safely. Can only be u... | import discord
from discord.ext import commands
class Owner:
"""Admin-only commands that make the bot dynamic."""
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.is_owner()
async def close(self, ctx: commands.Context):
"""Closes the bot safely. Can only be u... | Add OK reaction to reload command | Add OK reaction to reload command
| Python | mit | ivandardi/RustbotPython,ivandardi/RustbotPython |
a703bed82bb2cfcf8b18b5e651bd2e992a590696 | numpy/_array_api/_types.py | numpy/_array_api/_types.py | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPac... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPac... | Use better type definitions for the array API custom types | Use better type definitions for the array API custom types
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
f26a59aae33fd1afef919427e0c36e744cb904fc | test/test_normalizedString.py | test/test_normalizedString.py | from rdflib import *
import unittest
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBe... | from rdflib import Literal
from rdflib.namespace import XSD
import unittest
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def ... | Add a new test to test all chars that are getting replaced | Add a new test to test all chars that are getting replaced
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib |
543fc894120db6e8d854e746d631c87cc53f622b | website/noveltorpedo/tests.py | website/noveltorpedo/tests.py | from django.test import TestCase
from django.test import Client
from noveltorpedo.models import *
import unittest
from django.utils import timezone
client = Client()
class SearchTests(TestCase):
def test_that_the_front_page_loads_properly(self):
response = client.get('/')
self.assertEqual(respon... | from django.test import TestCase
from django.test import Client
from noveltorpedo.models import *
from django.utils import timezone
from django.core.management import call_command
client = Client()
class SearchTests(TestCase):
def test_that_the_front_page_loads_properly(self):
response = client.get('/')... | Rebuild index and test variety of queries | Rebuild index and test variety of queries
| Python | mit | NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo |
80524970b9e802787918af9ce6d25110be825df4 | moderngl/__init__.py | moderngl/__init__.py | '''
ModernGL: PyOpenGL alternative
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import *
from .scope impo... | '''
ModernGL: High performance rendering for Python 3
'''
from .error import *
from .buffer import *
from .compute_shader import *
from .conditional_render import *
from .context import *
from .framebuffer import *
from .program import *
from .program_members import *
from .query import *
from .renderbuffer import... | Update module level description of moderngl | Update module level description of moderngl
| Python | mit | cprogrammer1994/ModernGL,cprogrammer1994/ModernGL,cprogrammer1994/ModernGL |
cb557823258fe61c2e86db30a7bfe8d0de120f15 | tests/conftest.py | tests/conftest.py | import betamax
import os
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'once'
if os.environ.get('TRAVIS_GH3'):
record_mode = 'never'
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
... | import betamax
import os
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'once'
if os.environ.get('TRAVIS_GH3'):
record_mode = 'never'
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
... | Update the default value for the placeholder | Update the default value for the placeholder
If I decide to start matching on headers this will be necessary
| Python | bsd-3-clause | krxsky/github3.py,ueg1990/github3.py,agamdua/github3.py,sigmavirus24/github3.py,wbrefvem/github3.py,h4ck3rm1k3/github3.py,balloob/github3.py,degustaf/github3.py,christophelec/github3.py,jim-minter/github3.py,itsmemattchung/github3.py,icio/github3.py |
e4d5fa8c70dd283d4511f155da5be5835b1836f7 | tests/unit/test_validate.py | tests/unit/test_validate.py | import pytest
import mock
import synapseclient
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data_clinical_supp... | import pytest
import mock
import synapseclient
import pytest
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
(["data_CNA_SAGE.txt"], "cna"),
(["data_clinical_supp_SAGE.txt"], "clinical"),
(["data... | Add in unit tests for validate.py | Add in unit tests for validate.py
| Python | mit | thomasyu888/Genie,thomasyu888/Genie,thomasyu888/Genie,thomasyu888/Genie |
96365d3467e1b0a9520eaff8086224d2d181b03b | mopidy/mixers/osa.py | mopidy/mixers/osa.py | from subprocess import Popen, PIPE
from mopidy.mixers import BaseMixer
class OsaMixer(BaseMixer):
def _get_volume(self):
try:
return int(Popen(
['osascript', '-e', 'output volume of (get volume settings)'],
stdout=PIPE).communicate()[0])
except ValueErro... | from subprocess import Popen, PIPE
import time
from mopidy.mixers import BaseMixer
CACHE_TTL = 30
class OsaMixer(BaseMixer):
_cache = None
_last_update = None
def _valid_cache(self):
return (self._cache is not None
and self._last_update is not None
and (int(time.time() - ... | Add caching of OsaMixer volume | Add caching of OsaMixer volume
If volume is just managed through Mopidy it is always correct. If another
application changes the volume, Mopidy will be correct within 30 seconds.
| Python | apache-2.0 | tkem/mopidy,quartz55/mopidy,tkem/mopidy,pacificIT/mopidy,bacontext/mopidy,mokieyue/mopidy,vrs01/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,priestd09/mopidy,bencevans/mopidy,swak/mopidy,jmarsik/mopidy,jodal/mopidy,ali/mopidy,jodal/mopidy,adamcik/mopidy,rawdlite/mopidy,diandiankan/mopidy,adamcik/mopidy,SuperStarPL/mopidy,aba... |
0180aead701820d2de140791c3e271b4b8a7d231 | tests/__init__.py | tests/__init__.py | import os
def fixture_response(path):
return open(os.path.join(
os.path.dirname(__file__),
'fixtures',
path)).read()
| import os
def fixture_response(path):
with open(os.path.join(os.path.dirname(__file__),
'fixtures',
path)) as fixture:
return fixture.read()
| Fix file handlers being left open for fixtures | Fix file handlers being left open for fixtures
| Python | mit | accepton/accepton-python |
d07bf029b7ba9b5ef1f494d119a2eca004c1818a | tests/basics/list_slice_3arg.py | tests/basics/list_slice_3arg.py | x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
| x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
x = list(range(9))
print(x[::-1])
print(x[::2])
print(x[::-2])
| Add small testcase for 3-arg slices. | tests: Add small testcase for 3-arg slices.
| Python | mit | neilh10/micropython,danicampora/micropython,tuc-osg/micropython,noahchense/micropython,ahotam/micropython,alex-march/micropython,SungEun-Steve-Kim/test-mp,suda/micropython,SungEun-Steve-Kim/test-mp,noahwilliamsson/micropython,neilh10/micropython,aethaniel/micropython,noahwilliamsson/micropython,chrisdearman/micropython... |
2a43183f5d2c14bacb92fe563d3c2ddf61b116da | tests/testMain.py | tests/testMain.py | import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Insta... | import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Insta... | Make naming consistent with our standard (camelcase always, even with acronymn) | Make naming consistent with our standard (camelcase always, even with acronymn)
| Python | mpl-2.0 | EsriOceans/btm |
457d8002a3758cc8f28ba195a21afc4e0d33965a | tests/vec_test.py | tests/vec_test.py | """Tests for vectors."""
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify... | """Tests for vectors."""
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify... | Update tests for vectors for the new protocol | Update tests for vectors for the new protocol
Now the tests for vectors are updated for the new non backward
compatible change for the concepts of label and base.
| Python | mit | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge |
df00a5319028e53826c1a4fd29ed39bb671b4911 | tutorials/urls.py | tutorials/urls.py | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
] | from django.conf.urls import include, url
from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url... | Add markdownx url, Add add-tutrorial url | Add markdownx url, Add add-tutrorial url
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
3bce013c51c454721de3a868ea6d8e8c6d335112 | cycli/neo4j.py | cycli/neo4j.py | import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
self.host = host
self.port = port
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=po... | import requests
from py2neo import Graph, authenticate
class Neo4j:
def __init__(self, host, port, username=None, password=None):
self.username = username
self.password = password
self.host_port = "{host}:{port}".format(host=host, port=port)
self.url = "http://{host_port}/db/data... | Remove host and port attributes from Neo4j | Remove host and port attributes from Neo4j
| Python | mit | nicolewhite/cycli,nicolewhite/cycli |
70c9deb44cbbce13fbe094640786398cb4683b08 | ldap_sync/tasks.py | ldap_sync/tasks.py | from django.core.management import call_command
from celery import task
@task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
| from django.core.management import call_command
from celery import shared_task
@shared_task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users
with the local database.
"""
call_command('syncldap')
| Change Celery task to shared task | Change Celery task to shared task
| Python | bsd-3-clause | alexsilva/django-ldap-sync,jbittel/django-ldap-sync,PGower/django-ldap3-sync,alexsilva/django-ldap-sync |
026fade3f064f0185fa3a6f2075d43353e041970 | whois-scraper.py | whois-scraper.py | from lxml import html
from PIL import Image
import requests
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(image_file)
# Use Tess... | from lxml import html
from PIL import Image
import requests
import urllib.request
def enlarge_image(image_file):
image = Image.open(image_file)
enlarged_size = map(lambda x: x*2, image.size)
enlarged_image = image.resize(enlarged_size)
return enlarged_image
def extract_text(image_file):
image = enlarge_image(im... | Add functions to scrape whois data and fix the e-mails in it | Add functions to scrape whois data and fix the e-mails in it
- Add function scrape_whois which scrapes the raw whois information for a given domain from http://www.whois.com/whois.
- Add function fix_emails. http://www.whois.com hides the username-part of the contact e-mails from the whois info by displaying it as an ... | Python | mit | SkullTech/whois-scraper |
b89f6981d4f55790aa919f36e02a6312bd5f1583 | tests/__init__.py | tests/__init__.py | import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
from flask.ext.images import Images, ImageSize, resized_img_src
import flask
flask_... | import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
import flask
from flask_images import Images, ImageSize, resized_img_src
flask_ve... | Stop using `flask.ext.*` in tests. | Stop using `flask.ext.*` in tests.
| Python | bsd-3-clause | mikeboers/Flask-Images |
211972701d8dbd39e42ec5a8d10b9c56be858d3e | tests/conftest.py | tests/conftest.py | import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
... | import string
import pytest
@pytest.fixture
def identity_fixures():
l = []
for i, c in enumerate(string.ascii_uppercase):
l.append(dict(
name='identity_{0}'.format(i),
access_key_id='someaccesskey_{0}'.format(c),
secret_access_key='notasecret_{0}_{1}'.format(i, c),
... | Remove fixture teardown since nothing should be saved (tmpdir) | Remove fixture teardown since nothing should be saved (tmpdir)
| Python | mit | nocarryr/AWS-Identity-Manager |
debdc71a1c22412c46d8bf74315a5467c1e228ee | magnum/tests/unit/common/test_exception.py | magnum/tests/unit/common/test_exception.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Stop using deprecated 'message' attribute in Exception | Stop using deprecated 'message' attribute in Exception
The 'message' attribute has been deprecated and removed
from Python3.
For more details, please check:
https://www.python.org/dev/peps/pep-0352/
Change-Id: Id952e4f59a911df7ccc1d64e7a8a2d5e9ee353dd
| Python | apache-2.0 | ArchiFleKs/magnum,ArchiFleKs/magnum,openstack/magnum,openstack/magnum |
021cf436c23c5c705d0e3c5b6383e25811ade669 | webmaster_verification/views.py | webmaster_verification/views.py | import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for t... | import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for t... | Use the new template path | Use the new template path
| Python | bsd-3-clause | nkuttler/django-webmaster-verification,nkuttler/django-webmaster-verification |
4d1b96792f73777adaa0a79341901ca82f57839b | use/functional.py | use/functional.py | def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
| import collections
import functools
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
class memoize(object):
'''Decorator. Caches a function's return va... | Add a simple memoize function | Add a simple memoize function
| Python | mit | log0ymxm/corgi |
3f2b4236bdb5199d4830a893c7b511f7875dc501 | plata/utils.py | plata/utils.py | from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
class JSONFieldDescriptor(object):
def __init__(self, field)... | from decimal import Decimal
import simplejson
from django.core.serializers.json import DjangoJSONEncoder
try:
simplejson.dumps([42], use_decimal=True)
except TypeError:
raise Exception('simplejson>=2.1 with support for use_decimal required.')
class CallbackOnUpdateDict(dict):
"""Dict which executes a c... | Make working with JSONDataDescriptor easier | Make working with JSONDataDescriptor easier
| Python | bsd-3-clause | allink/plata,armicron/plata,armicron/plata,armicron/plata,stefanklug/plata |
131f266e73139f1148ee3e9fcce8db40842afb88 | sale_channel/models/account.py | sale_channel/models/account.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Sales Channels
# Copyright (C) 2016 June
# 1200 Web Development
# http://1200wd.com/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affer... | # -*- coding: utf-8 -*-
##############################################################################
#
# Sales Channels
# Copyright (C) 2016 June
# 1200 Web Development
# http://1200wd.com/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affer... | Add constraint, tax name must be unique for each company and sales channel | [IMP] Add constraint, tax name must be unique for each company and sales channel
| Python | agpl-3.0 | 1200wd/1200wd_addons,1200wd/1200wd_addons |
999d243fbc9908255ae292186bf8b17eb67e42e8 | planner/forms.py | planner/forms.py | from django import forms
class LoginForm(forms.Form):
email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(... | from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
... | Fix LoginForm to be conformant to builtin AuthenticationForm | Fix LoginForm to be conformant to builtin AuthenticationForm
| Python | mit | livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride |
e1240aa33b286ba52507128458fc6d6b3b68dfb3 | statsmodels/stats/multicomp.py | statsmodels/stats/multicomp.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 18:27:25 2012
Author: Josef Perktold
"""
from statsmodels.sandbox.stats.multicomp import MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around ... | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 18:27:25 2012
Author: Josef Perktold
"""
from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapp... | Put back an import that my IDE incorrectly flagged as unused | Put back an import that my IDE incorrectly flagged as unused
| Python | bsd-3-clause | gef756/statsmodels,detrout/debian-statsmodels,detrout/debian-statsmodels,bzero/statsmodels,YihaoLu/statsmodels,wzbozon/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,musically-ut/statsmodels,josef-pkt/statsmodels,cbmoore/statsmodels,rgommers/statsmodels,hlin117/statsmodels,ChadFulton/statsmodels,edhuckle/statsmod... |
eb785ce7485c438cfcaf6bb48d8cf8a840970bd4 | src/tenyksddate/main.py | src/tenyksddate/main.py | import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian... | import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian... | Change method order to match filters | Change method order to match filters
| Python | mit | kyleterry/tenyks-contrib,cblgh/tenyks-contrib,colby/tenyks-contrib |
68046b638b5d2a9d9a0c9c588a6c2b833442e01b | plinth/modules/ikiwiki/forms.py | plinth/modules/ikiwiki/forms.py | #
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | #
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Allow only alphanumerics in wiki/blog name | ikiwiki: Allow only alphanumerics in wiki/blog name
| Python | agpl-3.0 | harry-7/Plinth,kkampardi/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,vignanl/Plinth,vignanl/Plinth,kkampardi/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,freedomboxtwh/Plinth,freedomboxtwh/Plinth,harry-7/Plinth,freedomboxtwh/Plinth,harry-7/Plinth,harry-7/Plin... |
2aed2eb4a1db5fba9d161a679c147f2260fb0780 | msg/serializers.py | msg/serializers.py | from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class ... | from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UnixEpochDateField(serializers.DateTimeField):
def to_native(self, value):
""" Return epoch time for a datetime object or ``None``"""
import time
try:
return int(time.mktime(value.tim... | Add epoch conversion to timestamp | Add epoch conversion to timestamp | Python | mit | orisi/fastcast |
65fcfbfae9ef1a68d324aea932f983f7edd00cdf | mopidy/__init__.py | mopidy/__init__.py | import logging
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rindex('.')]
class_name = name[name.rindex('.') + 1:]
logger.info('... | import logging
from multiprocessing.reduction import reduce_connection
import pickle
from mopidy import settings as raw_settings
logger = logging.getLogger('mopidy')
def get_version():
return u'0.1.dev'
def get_mpd_protocol_version():
return u'0.16.0'
def get_class(name):
module_name = name[:name.rinde... | Add util functions for pickling and unpickling multiprocessing.Connection | Add util functions for pickling and unpickling multiprocessing.Connection
| Python | apache-2.0 | SuperStarPL/mopidy,pacificIT/mopidy,swak/mopidy,hkariti/mopidy,dbrgn/mopidy,jmarsik/mopidy,diandiankan/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,quartz55/mopidy,ali/mopidy,pacificIT/mopidy,adamcik/mopidy,rawdlite/mopidy,swak/mopidy,dbrgn/mopidy,jodal/mopidy,hkariti/mopidy,priestd09/mopidy,dbrgn/mopidy,jmarsik/mopidy,q... |
a8bd6e86583b72211f028ecb51df2ee27550b258 | submit.py | submit.py | import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) a... | import json
import requests
import argparse
parser = argparse.ArgumentParser(
description="Upload submission from submit.cancergenetrust.org")
parser.add_argument('file', nargs='?', default="submission.json",
help="Path to json file to submit")
args = parser.parse_args()
with open(args.file) a... | Handle only clinical, no genomic, submission | Handle only clinical, no genomic, submission
| Python | apache-2.0 | ga4gh/CGT,ga4gh/CGT,ga4gh/CGT |
81904effd492e2b2cea64dc98b29033261ae8b62 | tests/generator_test.py | tests/generator_test.py | from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
| from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class GeneratorTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
assert len(self.klass... | Check that we are creating Test Classes | Check that we are creating Test Classes
| Python | mit | talkiq/gaend,samedhi/gaend,talkiq/gaend,samedhi/gaend |
bc36a19d3bb1c07cbe2a44de88f227ef71c50b8c | notebooks/utils.py | notebooks/utils.py | def print_generated_sequence(g, num, *, sep=", "):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("Generated sequence:{}{}".format(sep_initial, s... | def print_generated_sequence(g, num, *, sep=", ", seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `g`.
"""
if seed:
g.reset(seed)
elems = [str(next(g)) for _ in range(num)]
sep_initial = "\n" if sep == "\n" else " "
print("G... | Allow passing seed directly to helper function | Allow passing seed directly to helper function
| Python | mit | maxalbert/tohu |
44223235e5b8b0c49df564ae190927905de1f9a4 | plenario/worker.py | plenario/worker.py | from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return tasks.upda... | import os
from datetime import datetime
from flask import Flask
import plenario.tasks as tasks
def create_worker():
app = Flask(__name__)
app.config.from_object('plenario.settings')
app.url_map.strict_slashes = False
@app.route('/update/weather', methods=['POST'])
def weather():
return ... | Add temporary check to block production resolve | Add temporary check to block production resolve
| Python | mit | UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario |
2ec93f385e9eea63d42e17a2a777b459edf93816 | tools/debug_adapter.py | tools/debug_adapter.py | #!/usr/bin/python
import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server(multiple=False)
| #!/usr/bin/python
import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| Update code for changed function. | Update code for changed function.
| Python | mit | vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb |
143b74a2c6f99d2d92ac85310351327ffb630c1e | uscampgrounds/admin.py | uscampgrounds/admin.py | from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
admin.site.register(Campground, CampgroundAd... | from django.contrib.gis import admin
from uscampgrounds.models import *
class CampgroundAdmin(admin.OSMGeoAdmin):
list_display = ('name', 'campground_code', 'campground_type', 'phone', 'sites', 'elevation', 'hookups', 'amenities')
list_filter = ('campground_type',)
search_fields = ('name',)
admin.site.reg... | Allow searching campgrounds by name for convenience. | Allow searching campgrounds by name for convenience.
| Python | bsd-3-clause | adamfast/geodjango-uscampgrounds,adamfast/geodjango-uscampgrounds |
d9024e4db0489b141fec9b96913c94a5d583f086 | backend/scripts/mktemplate.py | backend/scripts/mktemplate.py | #!/usr/bin/env python
import json
import rethinkdb as r
import sys
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
parser.add_option("-f", "--file", dest="filename",
... | #!/usr/bin/env python
import json
import rethinkdb as r
import sys
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
parser.add_option("-f", "--file", dest="filename",
... | Update script to show which file it is loading. | Update script to show which file it is loading.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
8e8d80e744c99ab1c5552057899bf5470d751a29 | linked_list.py | linked_list.py | #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
de... | #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
de... | Add semi-working size() function v1 | Nick: Add semi-working size() function v1
| Python | mit | constanthatz/data-structures |
64ae41be94374b0dae33d37ea1e2f20b233dd809 | moocng/peerreview/managers.py | moocng/peerreview/managers.py | # Copyright 2013 Rooter Analysis S.L.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # Copyright 2013 Rooter Analysis S.L.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Sort by kq too when returning peer review assignments | Sort by kq too when returning peer review assignments
| Python | apache-2.0 | OpenMOOC/moocng,OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng |
3dd5cd27963a0cfeb446a36fcd50c05e7c715eb3 | cyder/api/v1/endpoints/api.py | cyder/api/v1/endpoints/api.py | from django.utils.decorators import classonlymethod
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.Mod... | from rest_framework import serializers, viewsets
NestedAVFields = ['id', 'attribute', 'value']
class CommonAPISerializer(serializers.ModelSerializer):
pass
class CommonAPINestedAVSerializer(serializers.ModelSerializer):
attribute = serializers.SlugRelatedField(slug_field='name')
class CommonAPIMeta:
... | Fix earlier folly (commented and useless code) | Fix earlier folly (commented and useless code)
| Python | bsd-3-clause | akeym/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,murrown/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,zeeman/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,akeym/cyder,zeeman/cyder |
fd5cad381e8b821bfabbefc9deb4b8a4531844f6 | rnacentral_pipeline/rnacentral/notify/slack.py | rnacentral_pipeline/rnacentral/notify/slack.py | """
Send a notification to slack.
NB: The webhook should be configured in the nextflow profile
"""
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHO... | """
Send a notification to slack.
NB: The webhook should be configured in the nextflow profile
"""
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHO... | Add a secrets file in rnac notify | Add a secrets file in rnac notify
Nextflow doesn't propagate environment variables from the profile into
the event handler closures. This is the simplest workaround for that.
secrets.py should be on the cluster and symlinked into
rnacentral_pipeline
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline |
5df350254e966007f80f7a14fde29a8c93316bb3 | tests/rules/test_git_push.py | tests/rules/test_git_push.py | import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
... | import pytest
from thefuck.rules.git_push import match, get_new_command
from tests.utils import Command
@pytest.fixture
def stderr():
return '''fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin master
'''
... | Check arguments are preserved in git_push | Check arguments are preserved in git_push
| Python | mit | scorphus/thefuck,mlk/thefuck,Clpsplug/thefuck,SimenB/thefuck,nvbn/thefuck,Clpsplug/thefuck,SimenB/thefuck,mlk/thefuck,nvbn/thefuck,scorphus/thefuck |
c09a8ce5bb47db4ea4381925ec07199415ae5c39 | spacy/tests/integration/test_load_languages.py | spacy/tests/integration/test_load_languages.py | # encoding: utf8
from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
| # encoding: utf8
from __future__ import unicode_literals
from ...fr import French
def test_load_french():
nlp = French()
doc = nlp(u'Parlez-vous français?')
assert doc[0].text == u'Parlez'
assert doc[1].text == u'-'
assert doc[2].text == u'vouz'
assert doc[3].text == u'français'
assert doc[... | Add test for french tokenizer | Add test for french tokenizer
| Python | mit | raphael0202/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,banglakit/spaCy,recognai/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,recognai/spaCy,banglakit/sp... |
bd89dc8f6812ff824417875c9375499f331bf5e4 | scripts/maf_limit_to_species.py | scripts/maf_limit_to_species.py | #!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys... | #!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys... | Remove all-gap columns after removing rows of the alignment | Remove all-gap columns after removing rows of the alignment
| Python | mit | uhjish/bx-python,uhjish/bx-python,uhjish/bx-python |
b718c1d817e767c336654001f3aaea5d7327625a | wsgi_intercept/requests_intercept.py | wsgi_intercept/requests_intercept.py | """Intercept HTTP connections that use `requests <http://docs.python-requests.org/en/latest/>`_.
"""
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib3.connection... | """Intercept HTTP connections that use `requests <http://docs.python-requests.org/en/latest/>`_.
"""
import sys
from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket
from requests.packages.urllib3.connectionpool import (HTTPConnectionPool,
HTTPSConnectionPool)
from requests.packages.urllib... | Deal with request's urllib3 being annoying about 'strict' | Deal with request's urllib3 being annoying about 'strict'
These changes are required to get tests to pass in python3.4 (and
presumably others).
This is entirely code from @sashahart, who had done the work earlier
to deal with with some Debian related issues uncovered by @thomasgoirand.
These changes will probably me... | Python | mit | sileht/python3-wsgi-intercept,cdent/wsgi-intercept |
2843052a222541e3b7ce45fa633f5df61b10a809 | test/oracle.py | test/oracle.py | import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
train_and_evaluate = qnd.def_train_and_evaluate()
... | import qnd
import tensorflow as tf
def model_fn(x, y):
return (y,
0.0,
tf.contrib.framework.get_or_create_global_step().assign_add())
def input_fn(q):
shape = (100,)
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
train_and_evaluate = qnd.def_train_and_evaluate(dis... | Use distributed flag for xfail test | Use distributed flag for xfail test
| Python | unlicense | raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd |
bf7b8df92fb1cc16fccefe201eefc0ed853eac5d | server/api/serializers/rides.py | server/api/serializers/rides.py | import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.api.serializers.chapters import ChapterSerializer
from .riders import RiderSerializer
from server.core.models.rides import Ride, RideRiders
class RideSerial... | import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.api.serializers.chapters import ChapterSerializer
from .riders import RiderSerializer
from server.core.models.rides import Ride, RideRiders
class RideSerial... | Make sure that the registration serialiser doesn't require the signup date. | Make sure that the registration serialiser doesn't require the signup date.
Signed-off-by: Michael Willmott <4063ad43ea4e0ae77bf35022808393a246bdfa61@gmail.com>
| Python | mit | Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,mwillmott/techbikers,Techbikers/techbikers |
788dd6f62899fb16aa983c17bc1a5e6eea5317b0 | FunctionHandler.py | FunctionHandler.py | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.module... | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.module... | Clean up debug printing further | Clean up debug printing further
| Python | mit | HubbeKing/Hubbot_Twisted |
0bb777c0c77e5b7cac8d48f79f78d3a7cf944943 | backend/uclapi/uclapi/utils.py | backend/uclapi/uclapi/utils.py | def strtobool(x):
return x.lower() in ("true", "yes", "1", "y") | def strtobool(x):
try:
b = x.lower() in ("true", "yes", "1", "y")
return b
except AttributeError:
return False
except NameError
return False | Add some failsafes to strtobool | Add some failsafes to strtobool
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi |
1f914a04adb4ad7d39ca7104e2ea36acc76b18bd | pvextractor/tests/test_gui.py | pvextractor/tests/test_gui.py | import numpy as np
from numpy.testing import assert_allclose
import pytest
from astropy.io import fits
from ..pvextractor import extract_pv_slice
from ..geometry.path import Path
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5O... | import pytest
from distutils.version import LooseVersion
import matplotlib as mpl
from ..gui import PVSlicer
from .test_slicer import make_test_hdu
try:
import PyQt5
PYQT5OK = True
except ImportError:
PYQT5OK = False
if LooseVersion(mpl.__version__) < LooseVersion('2'):
MPLOK = True
else:
MPLO... | Use LooseVersion to compare version numbers | Use LooseVersion to compare version numbers
| Python | bsd-3-clause | radio-astro-tools/pvextractor,keflavich/pvextractor |
0cc4e839d5d7725aba289047cefe77cd89d24593 | auth_mac/models.py | auth_mac/models.py | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentia... | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentia... | Add a model property to tell if credentials have expired | Add a model property to tell if credentials have expired
| Python | mit | ndevenish/auth_mac |
87c861f6ed0e73e21983edc3add35954b9f0def5 | apps/configuration/fields.py | apps/configuration/fields.py | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.rem... | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.rem... | Allow linebreaks textareas (should be valid in XML) | Allow linebreaks textareas (should be valid in XML)
| Python | apache-2.0 | CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat |
b61679efce39841120fcdb921acefbc729f4c4fd | tests/test_kmeans.py | tests/test_kmeans.py | import numpy as np
import milk.unsupervised
def test_kmeans():
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or correct <= 2
| import numpy as np
import milk.unsupervised
def test_kmeans():
np.random.seed(132)
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
centroids, _ = milk.unsupervised.kmeans(features,2)
positions = [0]*20 + [1]*20
correct = (centroids == positions).sum()
assert correct >= 38 or ... | Make sure results make sense | Make sure results make sense
| Python | mit | luispedro/milk,pombredanne/milk,luispedro/milk,pombredanne/milk,luispedro/milk,pombredanne/milk |
e676877492057d7b370431f6896154702c8459f1 | webshack/auto_inject.py | webshack/auto_inject.py | from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
"{}.js".format(package... | from urllib.parse import urljoin
from urllib.request import urlopen
from urllib.error import URLError
import sys
ENORMOUS_INJECTION_HACK = False
GITHUB_USERS = [('Polymer', '0.5.2')]
def resolve_missing_user(user, branch, package):
assets = ["{}.html".format(package),
"{}.css".format(package),
... | Add a hack to auto-inject new deps | Add a hack to auto-inject new deps
| Python | mit | prophile/webshack |
0e53ae11cb1cc53979edb1f17162e8b1d89ad809 | user/models.py | user/models.py | from django.db import models
# Create your models here.
| from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Extends User model. Defines sn and notifications for a User.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
sn... | Define initial schema for user and email notifications | Define initial schema for user and email notifications
| Python | apache-2.0 | ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints |
172feb5997a826181a0ec381c171a0a2cc854e4c | yolapy/configuration.py | yolapy/configuration.py | """Configuration.
Yolapy.configuration provides a key-value store used by the Yola client.
Data is stored here in the module, benefits include:
* Configuration is decoupled from application logic.
* When instantiating multiple service models, each contains its own client.
This module allows for configuration t... | """Configuration.
Yolapy.configuration provides a key-value store used by the Yola client.
Data is stored here in the module, benefits include:
* Configuration is decoupled from application logic.
* When instantiating multiple service models, each contains its own client.
This module allows for configuration t... | Improve varname for missing config | Improve varname for missing config
| Python | mit | yola/yolapy |
b96cb194c8edd54fda9868d69fda515ac8beb29f | vumi/dispatchers/__init__.py | vumi/dispatchers/__init__.py | """The vumi.dispatchers API."""
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
"FromAddrMultiplexRouter", "UserGroupingRouter"]
from vumi.dispatchers.base import (BaseDispatchWorker, BaseDispatchRouter,
... | """The vumi.dispatchers API."""
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
"FromAddrMultiplexRouter", "UserGroupingRouter",
"ContentKeywordRouter"]
from vumi.dispatchers.base import (BaseDispatchWorker, ... | Add ContentKeywordRouter to vumi.dispatchers API. | Add ContentKeywordRouter to vumi.dispatchers API.
| Python | bsd-3-clause | harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix |
041e1545c99681c8cf9e43d364877d1ff43342d0 | augur/datasources/augur_db/test_augur_db.py | augur/datasources/augur_db/test_augur_db.py | import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >... | import os
import pytest
@pytest.fixture(scope="module")
def augur_db():
import augur
augur_app = augur.Application()
return augur_app['augur_db']()
# def test_repoid(augur_db):
# assert ghtorrent.repoid('rails', 'rails') >= 1000
# def test_userid(augur_db):
# assert ghtorrent.userid('howderek') >... | Add Unit test for new contributors of issues | Add Unit test for new contributors of issues
Signed-off-by: Bingwen Ma <27def536c643ce1f88ca2c07ff6169767bd9a90f@gmail.com>
| Python | mit | OSSHealth/ghdata,OSSHealth/ghdata,OSSHealth/ghdata |
cd1c3645d733ab16355fe516bb2e505f87d49ace | backdrop/contrib/evl_upload.py | backdrop/contrib/evl_upload.py | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"age... | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"age... | Convert rows to list in EVL CEG parser | Convert rows to list in EVL CEG parser
It needs to access cells directly
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop |
7a04bb7692b4838e0abe9ba586fc4748ed9cd5d4 | tests/integration/blueprints/site/test_homepage.py | tests/integration/blueprints/site/test_homepage.py | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, ... | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from tests.helpers import http_client
def test_homepage(site_app, site):
with http_client(site_app) as client:
response = client.get('/')
# By default, nothing is mounted on `/`, ... | Test custom root path redirect | Test custom root path redirect
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
cdfb5c0c074e9143eeb84d914225dbcfb63151ba | common/djangoapps/dark_lang/models.py | common/djangoapps/dark_lang/models.py | """
Models for the dark-launching languages
"""
from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A... | """
Models for the dark-launching languages
"""
from django.db import models
from config_models.models import ConfigurationModel
class DarkLangConfig(ConfigurationModel):
"""
Configuration for the dark_lang django app
"""
released_languages = models.TextField(
blank=True,
help_text="A... | Put language modal in alphabetical order LMS-2302 | Put language modal in alphabetical order LMS-2302
| Python | agpl-3.0 | Softmotions/edx-platform,rismalrv/edx-platform,ovnicraft/edx-platform,jbzdak/edx-platform,nttks/jenkins-test,philanthropy-u/edx-platform,dkarakats/edx-platform,AkA84/edx-platform,kursitet/edx-platform,eestay/edx-platform,atsolakid/edx-platform,kxliugang/edx-platform,zadgroup/edx-platform,B-MOOC/edx-platform,romain-li/e... |
14b9ef43fd244d4709d14478ec0714325ca37cdb | tests/builtins/test_sum.py | tests/builtins/test_sum.py | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, ... | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, ... | Fix unexpected success on sum(bytearray()) | Fix unexpected success on sum(bytearray())
| Python | bsd-3-clause | cflee/voc,cflee/voc,freakboy3742/voc,freakboy3742/voc |
9ff92d0a437e5af08fbf996ed0e3362cbd9cf2c9 | tests/instrumentdb_test.py | tests/instrumentdb_test.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
self.assertTrue(os.path.exists(idb.instrument_db_path()))
self.a... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'Test the functions in the instrumentdb module.'
import os.path
import unittest as ut
import stripeline.instrumentdb as idb
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
self.assertTrue(os.path.exists(idb.instrument_db_path()),
... | Print more helpful messages when tests fail | Print more helpful messages when tests fail
| Python | mit | ziotom78/stripeline,ziotom78/stripeline |
7966f771c4b5450625d5247c6bf5369901457d9a | capstone/player/monte_carlo.py | capstone/player/monte_carlo.py | import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
r... | import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
r... | Move MonteCarlo move to choose_move | Move MonteCarlo move to choose_move
| Python | mit | davidrobles/mlnd-capstone-code |
d0db4010ca9c6d2a6cbc27ae0029dd1ccfc6de42 | evexml/forms.py | evexml/forms.py | from django import forms
from django.forms.fields import IntegerField, CharField
import evelink.account
class AddAPIForm(forms.Form):
key_id = IntegerField()
v_code = CharField(max_length=64, min_length=1)
def clean(self):
self._clean()
return super(AddAPIForm, self).clean()
def _cl... | from django import forms
from django.forms.fields import IntegerField, CharField
import evelink.account
class AddAPIForm(forms.Form):
key_id = IntegerField()
v_code = CharField(max_length=64, min_length=1)
def clean(self):
super(AddAPIForm, self).clean()
self._clean()
return self... | Swap order of clean calls | Swap order of clean calls
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
ba0ea7491fab383992013a8379592657eedfe1ce | scripts/contrib/model_info.py | scripts/contrib/model_info.py | #!/usr/bin/env python3
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints version and model type from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if S2S_SPECIAL_NODE not in model:
print("No special Ma... | #!/usr/bin/env python3
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints keys and values from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if args.special:
if S2S_SPECIAL_NODE not in model:
... | Add printing value for any key from model.npz | Add printing value for any key from model.npz
| Python | mit | emjotde/amunmt,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunmt,amunmt/marian,emjotde/amunn,amunmt/marian,emjotde/amunn,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,emjotde/Marian,marian-nmt/marian-train,emjotde/Marian,amunmt/marian |
48e405f0f2027c82403c96b58023f1308c3f7c14 | model/orderbook.py | model/orderbook.py | # -*- encoding:utf8 -*-
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda = oandapy.API(environment="practice", access_token=oanda_token)
orders = oanda.get_o... | # -*- encoding:utf8 -*-
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda_environment = os.environ.get('OANDA_ENVIRONMENT', 'practice')
oanda = oandapy.API(en... | Add oanda environment selector from runtime environments. | Add oanda environment selector from runtime environments.
| Python | mit | supistar/OandaOrderbook,supistar/OandaOrderbook,supistar/OandaOrderbook |
082f366402ca2084542a6306624f1f467297ebae | bin/task_usage_index.py | bin/task_usage_index.py | #!/usr/bin/env python3
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import glob, json
import numpy as np
import task_usage
def main(data_path, index_path, report_each=10000):
print('Looking for data in "{}"...'.format(data_path))
paths = sorted(glob.glob('{}/**/*.sqli... | #!/usr/bin/env python3
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import glob, json
import numpy as np
import task_usage
def main(data_path, index_path, report_each=10000):
print('Looking for data in "{}"...'.format(data_path))
paths = sorted(glob.glob('{}/**/*.sqli... | Print the percentage from the task-usage-index script | Print the percentage from the task-usage-index script
| Python | mit | learning-on-chip/google-cluster-prediction |
0fe990cf476dcd0cdea56c39de1dad6003d81851 | statbot/mention.py | statbot/mention.py | #
# mention.py
#
# statbot - Store Discord records for later analysis
# Copyright (c) 2017 Ammon Smith
#
# statbot is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it will be useful, but
# WITHOUT ANY... | #
# mention.py
#
# statbot - Store Discord records for later analysis
# Copyright (c) 2017 Ammon Smith
#
# statbot is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it will be useful, but
# WITHOUT ANY... | Change MentionType to use fixed enum values. | Change MentionType to use fixed enum values.
| Python | mit | strinking/statbot,strinking/statbot |
06c2fe1bd836f4adfcff4eb35cc29203e10a729d | blinkytape/animation.py | blinkytape/animation.py | # TBD: Some animations mutate a pattern: shift it, fade it, etc.
# Not all animations need a pattern
# I need a rainbow pattern for fun
# TBD: How do you do random pixels? is it a pattern that is permuted by the
# animation? YES; patterns are static, animations do things with patterns,
# rotate them, scramble them, sc... | # TBD: Some animations mutate a pattern: shift it, fade it, etc.
# Not all animations need a pattern
# I need a rainbow pattern for fun
# TBD: How do you do random pixels? is it a pattern that is permuted by the
# animation? YES; patterns are static, animations do things with patterns,
# rotate them, scramble them, sc... | Add abstract method exceptions to make Animation inheritance easier | Add abstract method exceptions to make Animation inheritance easier
| Python | mit | jonspeicher/blinkyfun |
f2d34fa3153448ab6a893fba45ae48b52d7759db | chipy_org/apps/profiles/urls.py | chipy_org/apps/profiles/urls.py | from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from profiles.views import (ProfilesList,
ProfileEdit,
)
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
url(r'^edit/$', ProfileEdit.as_view(), name='ed... | from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from .views import ProfilesList, ProfileEdit
urlpatterns = patterns("",
url(r'^list/$', ProfilesList.as_view(), name='list'),
url(r'^edit/$', login_required(ProfileEdit).as_view(), name='edit'),
)
| Add login required for profile edit | Add login required for profile edit
| Python | mit | agfor/chipy.org,brianray/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,chicagopython/chipy.or... |
3f236d74615dced53c57628ae1b5f2c74f9e1de5 | examples/rate_limiting_test.py | examples/rate_limiting_test.py | from seleniumbase import BaseCase
from seleniumbase.common import decorators
class MyTestClass(BaseCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print(item)
def test_rate_limited_printing(self):
print("\nRunning rate-limited print tes... | """
This test demonstrates the use of the "rate_limited" decorator.
You can use this decorator on any method to rate-limit it.
"""
import unittest
from seleniumbase.common import decorators
class MyTestClass(unittest.TestCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(... | Update the rate_limited decorator test | Update the rate_limited decorator test
| Python | mit | seleniumbase/SeleniumBase,possoumous/Watchers,possoumous/Watchers,mdmintz/SeleniumBase,possoumous/Watchers,ktp420/SeleniumBase,seleniumbase/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/seleniumspot,ktp420/SeleniumBa... |
2a23e72f7ad01976bcd80aa91f89882e2a37cbf6 | test/test_model.py | test/test_model.py | # coding: utf-8
import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).bu... | # coding: utf-8
import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).bu... | Test blueprints for corner cases | Test blueprints for corner cases
| Python | mit | ahitrin/carlo |
b6fc4a8db76b3aad100c6e40ab1b0fb9977dfd0d | changes/api/project_index.py | changes/api/project_index.py | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Project, Build
class ProjectIndexAPIView(APIView):
def get(self):
queryset = Project.query.order_by(Project.name.asc())
# quer... | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Project, Build
class ProjectIndexAPIView(APIView):
def get(self):
queryset = Project.query.order_by(Project.name.asc())
projec... | Add recentBuilds and stream to project index | Add recentBuilds and stream to project index
| Python | apache-2.0 | wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,dropbox/changes |
4b56e0da85cec4aa89b8105c3a7ca416a2f7919e | wdim/client/blob.py | wdim/client/blob.py | import json
import hashlib
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.H... | import json
import hashlib
from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data: Dic... | Allow Blob to be accessed with __getitem__ | Allow Blob to be accessed with __getitem__
| Python | mit | chrisseto/Still |
a78445cfada5cc1f77a7887dc5241071bef69989 | compass/tests/test_models.py | compass/tests/test_models.py | from django.test import TestCase
from compass.models import (Category,
Book)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestC... | from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestC... | Test correct heading returned in search results | Test correct heading returned in search results
| Python | mit | andela-osule/bookworm,andela-osule/bookworm |
eaa2ef92eba11d44bf5159342e314b932d79f58d | fedora/__init__.py | fedora/__init__.py | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | Undo the webtest import... it's causing runtime failiure and unittests are currently broken anyway. | Undo the webtest import... it's causing runtime failiure and unittests are
currently broken anyway.
| Python | lgpl-2.1 | fedora-infra/python-fedora |
662287761b8549a86d3fb8c05ec37d47491da120 | flatblocks/urls.py | flatblocks/urls.py | from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
]
| from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path(
r"^edit/(?P<pk>\d+)/$",
staff_member_required(edit),
name="flatblocks-edit",
),
]
| Use raw string notation for regular expression. | Use raw string notation for regular expression.
| Python | bsd-3-clause | funkybob/django-flatblocks,funkybob/django-flatblocks |
1cc6ec9f328d3ce045a4a1a50138b11c0b23cc3a | pyfr/ctypesutil.py | pyfr/ctypesutil.py | # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
... | # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath =... | Enable library paths to be explicitly specified. | Enable library paths to be explicitly specified.
All shared libraries loaded through the load_library function
can bow be specified explicitly through a suitable environmental
variable
PYFR_<LIB>_LIBRARY_PATH=/path/to/lib.here
where <LIB> corresponds to the name of the library, e.g. METIS.
| Python | bsd-3-clause | BrianVermeire/PyFR |
8237291e194aa900857fe382d0b8cefb7806c331 | ocradmin/ocrmodels/models.py | ocradmin/ocrmodels/models.py | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=... | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=... | Improve unicode method. Whitespace cleanup | Improve unicode method. Whitespace cleanup
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium |
7a99695c7612609de294a6905820fad3e41afc43 | marketpulse/devices/models.py | marketpulse/devices/models.py | from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
| from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
class Meta:
orderi... | Order devices by manufacturer and model. | Order devices by manufacturer and model.
| Python | mpl-2.0 | johngian/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,mozilla/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse |
a760beb8d66222b456b160344eb0b4b7fccbf84a | Lib/test/test_linuxaudiodev.py | Lib/test/test_linuxaudiodev.py | from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.ENODEV):
rais... | from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.EN... | Raise TestSkipped, not ImportError. Honesty's the best policy. | Raise TestSkipped, not ImportError.
Honesty's the best policy.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
70db9410173183c83d80ca23e56ceb0d627fcbae | scripts/indices.py | scripts/indices.py | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('external_accounts', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCE... | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['storedfilenode'].create_index([
('tags', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('external_accounts', ASCENDING),
])
db['user']... | Add index on file tags field | Add index on file tags field
| Python | apache-2.0 | baylee-d/osf.io,abought/osf.io,Johnetordoff/osf.io,felliott/osf.io,alexschiller/osf.io,mluo613/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,aaxelb/osf.io,wearpants/osf.io,hmoco/osf.io,mfraezz/osf.io,caseyrollins/osf.io,leb2dg/osf.io,emetsger/osf.io,caneruguz/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,bayle... |
ecbabd56f6afc4474402d3293bf11e3b6eb2e8f4 | server/__init__.py | server/__init__.py | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsR... | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsR... | Switch to generating REST end points from docker image | Switch to generating REST end points from docker image
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK |
56dc9af410907780faba79699d274bef96a18675 | functionaltests/common/base.py | functionaltests/common/base.py | """
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... | """
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... | Remove unnecessary __init__ from functionaltests | Remove unnecessary __init__ from functionaltests
The __init__ just passes the same arguments, so it is not necessary
to implement it. This patch removes it for the cleanup.
Change-Id: Ib465356c47d06bfc66bef69126b089be24d19474
| Python | apache-2.0 | openstack/designate,openstack/designate,openstack/designate |
40ca8cde872704438fecd22ae98bc7db610de1f9 | services/flickr.py | services/flickr.py | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | Rewrite Flickr to use the new scope selection system | Rewrite Flickr to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org |
267b0634546c55ebb42d6b1b9c3deca9d7408cc2 | run_tests.py | run_tests.py | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation
TEST_PATH Path to pac... | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path,... | Fix test runner to accept 1 arg | Fix test runner to accept 1 arg
| Python | mit | the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopr... |
def9d7037a3c629f63e1a0d8c1721501abc110cd | linguee_api/downloaders/httpx_downloader.py | linguee_api/downloaders/httpx_downloader.py | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
... | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned... | Update the 503 error message. | Update the 503 error message.
| Python | mit | imankulov/linguee-api |
ffa00eaea02cda8258bf42d4fa733fb8693e2f0c | chemtrails/apps.py | chemtrails/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(s... | # -*- coding: utf-8 -*-
import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
... | Read Neo4j config from ENV if present | Read Neo4j config from ENV if present
| Python | mit | inonit/django-chemtrails,inonit/django-chemtrails,inonit/django-chemtrails |
7a688f0712ff323668955a21ea335f3308fcc840 | wurstmineberg.45s.py | wurstmineberg.45s.py | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for w... | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for w... | Add “Start Minecraft” menu item | Add “Start Minecraft” menu item
From https://github.com/matryer/bitbar-plugins/blob/master/Games/minecraftplayers.1m.py
| Python | mit | wurstmineberg/bitbar-server-status |
d4db750d2ff2e18c9fced49fffe7a3073880078b | InvenTree/common/apps.py | InvenTree/common/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
pass
| # -*- coding: utf-8 -*-
import logging
from django.apps import AppConfig
logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.clear_restart_flag()
def clear_restart_flag(self):
"""
Clear the SERVER_RESTART_REQUI... | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree |
ae918211a85654d7eaa848cbd09f717d0339f844 | database_email_backend/backend.py | database_email_backend/backend.py | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
retur... | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
retur... | Convert everything to unicode strings before inserting to DB | Convert everything to unicode strings before inserting to DB | Python | mit | machtfit/django-database-email-backend,machtfit/django-database-email-backend,jbinary/django-database-email-backend,stefanfoulis/django-database-email-backend,jbinary/django-database-email-backend |
b4c97d3b7b914c193c018a1d808f0815778996b4 | keystone/common/sql/data_migration_repo/versions/002_password_created_at_not_nullable.py | keystone/common/sql/data_migration_repo/versions/002_password_created_at_not_nullable.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Remove comment from previous migration | Remove comment from previous migration
The migration was using a comment from the first one.
Change-Id: I25dc9ca79f30f156bfc4296c44e141991119635e
| Python | apache-2.0 | ilay09/keystone,rajalokan/keystone,mahak/keystone,openstack/keystone,ilay09/keystone,openstack/keystone,mahak/keystone,mahak/keystone,openstack/keystone,rajalokan/keystone,rajalokan/keystone,ilay09/keystone |
cd0b6af73dd49b4da851a75232b5829b91b9030c | genome_designer/conf/demo_settings.py | genome_designer/conf/demo_settings.py | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
... | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
... | Allow refresh materialized view in DEMO_MODE. | Allow refresh materialized view in DEMO_MODE.
| Python | mit | woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,churchlab/millstone,churchlab/millstone |
e073e020d46953e15f0fb30d2947028c42261fc1 | cropimg/widgets.py | cropimg/widgets.py | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no f... | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None, renderer=None, **kwargs):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueEr... | Make sure that the admin widget also supports Django 2 | Make sure that the admin widget also supports Django 2
| Python | mit | rewardz/cropimg-django,rewardz/cropimg-django,rewardz/cropimg-django |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.