commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
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 | ---
+++
@@ -1,7 +1,7 @@
import logging
import json
import re
-from datetime import datetime
+
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
@@ -12,24 +12,16 @@
def format(self, record):
"""Formats a log record and serializes to js... |
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 | ---
+++
@@ -4,8 +4,10 @@
Dogfoods the `program` module.
"""
-from ._version import __version__
-from .program import Program
+from . import __version__, Program
-
-program = Program(name="Invoke", binary='inv[oke]', version=__version__)
+program = Program(
+ name="Invoke",
+ binary='inv[oke]',
+ versio... |
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 | ---
+++
@@ -4,9 +4,22 @@
# 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):
+ sup = super(ARN, self)
+ resour... |
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 | ---
+++
@@ -2,6 +2,6 @@
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "back2back.settings")
from django.core.wsgi import get_wsgi_application
-from dj_static import Cling, MediaCling
+from dj_static import Cling
-application = Cling(MediaCling(get_wsgi_application()))
+application = Cling(get_wsgi_application... |
05c38777cb4a65199a605fbe75278a2170f84256 | debreach/compat.py | debreach/compat.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
# Django >= 1.4.5
from django.utils.encoding import force_bytes, force_text, smart_text # NOQA
from django.utils.six import string_types, text_type, binary_type # NOQA
except ImportError: # pragma: no cover
# Django < 1.4.5
fr... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
# Django >= 1.4.5
from django.utils.encoding import force_bytes, force_text, smart_text # NOQA
from django.utils.six import string_types, text_type, binary_type # NOQA
except ImportError: # pragma: no cover
# Django < 1.4.5
fr... | Fix failure on Django < 1.4.5 | Fix failure on Django < 1.4.5
| Python | bsd-2-clause | lpomfrey/django-debreach,lpomfrey/django-debreach | ---
+++
@@ -11,7 +11,7 @@
from django.utils.encoding import ( # NOQA
smart_unicode as smart_text, smart_str as force_bytes) # NOQA
force_text = smart_text
- string_types = basestring
+ string_types = (basestring,)
text_type = unicode
binary_type = str
|
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 | ---
+++
@@ -8,5 +8,5 @@
"""
API endpoint that allows BookPages to be viewed or edited.
"""
- queryset = BookPage.objects.all()
+ queryset = BookPage.objects.order_by('page_number')
serializer_class = BookPageSerializer |
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 | ---
+++
@@ -33,6 +33,8 @@
self.bot.unload_extension(m)
self.bot.load_extension(m)
+ await ctx.message.add_reaction(self.bot.emoji_rustok)
+
def setup(bot):
bot.add_cog(Owner(bot)) |
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 | ---
+++
@@ -14,10 +14,13 @@
from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32,
uint64, float32, float64)
-Array = ndarray
-Device = TypeVar('device')
-Dtype = Literal[int8, int16, int32, int64, uint8, uint16,
- uint32, uint64, float32, float64]
-SupportsDLPack = ... |
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 | ---
+++
@@ -1,5 +1,7 @@
-from rdflib import *
+from rdflib import Literal
+from rdflib.namespace import XSD
import unittest
+
class test_normalisedString(unittest.TestCase):
def test1(self):
@@ -13,10 +15,13 @@
self.assertFalse(Literal.eq(st,lit))
def test3(self):
- lit=Literal("hey\nt... |
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 | ---
+++
@@ -1,8 +1,8 @@
from django.test import TestCase
from django.test import Client
from noveltorpedo.models import *
-import unittest
from django.utils import timezone
+from django.core.management import call_command
client = Client()
@@ -15,12 +15,13 @@
self.assertContains(response, 'NovelTorp... |
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 | ---
+++
@@ -1,5 +1,5 @@
'''
- ModernGL: PyOpenGL alternative
+ ModernGL: High performance rendering for Python 3
'''
from .error import * |
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 | ---
+++
@@ -10,5 +10,5 @@
config.define_cassette_placeholder(
'<AUTH_TOKEN>',
- os.environ.get('GH_AUTH', 'xxxxxxxxxxx')
+ os.environ.get('GH_AUTH', 'x' * 20)
) |
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 | ---
+++
@@ -1,6 +1,7 @@
import pytest
import mock
import synapseclient
+import pytest
from genie import validate
center = "SAGE"
syn = mock.create_autospec(synapseclient.Synapse)
@@ -22,5 +23,11 @@
syn, filepath_list, center) == fileformat
-# def test_wrongfilename_get_filetype():
-# assert inp... |
1bb00e56897d17d9779f535dc50f602321c26eca | genes/gnu_coreutils/commands.py | genes/gnu_coreutils/commands.py | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(*args))
... | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(args))
... | Fix args to list. Args is a tuple, list takes a tuple | Fix args to list. Args is a tuple, list takes a tuple | Python | mit | hatchery/Genepool2,hatchery/genepool | ---
+++
@@ -16,12 +16,12 @@
@only_posix()
def groupadd(*args):
- run(['groupadd'] + list(*args))
+ run(['groupadd'] + list(args))
@only_posix()
def ln(*args):
- run(['ln'] + list(*args))
+ run(['ln'] + list(args))
@only_posix()
@@ -36,10 +36,10 @@
def useradd(*args):
# FIXME: this is ... |
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... | ---
+++
@@ -1,15 +1,32 @@
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 no... |
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 | ---
+++
@@ -2,7 +2,7 @@
def fixture_response(path):
- return open(os.path.join(
- os.path.dirname(__file__),
- 'fixtures',
- path)).read()
+ with open(os.path.join(os.path.dirname(__file__),
+ 'fixtures',
+ path)) as fixture:
+ ... |
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... | ---
+++
@@ -2,3 +2,8 @@
print(x[::-1])
print(x[::2])
print(x[::-2])
+
+x = list(range(9))
+print(x[::-1])
+print(x[::2])
+print(x[::-2]) |
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 | ---
+++
@@ -33,8 +33,11 @@
# XXX this won't automatically get the right thing... how can we fix it?
import utils
- def testXMLDocumentExists(self):
+ def testXmlDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
+
+ def testCsvDocumentExists(self):
+ self.assertTrue(os... |
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 | ---
+++
@@ -19,7 +19,8 @@
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
- assert i.base == base.base
+ assert i.label == base.label
+ assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab |
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 | ---
+++
@@ -1,8 +1,12 @@
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 - s... |
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 | ---
+++
@@ -5,8 +5,6 @@
class Neo4j:
def __init__(self, host, port, username=None, password=None):
- self.host = host
- self.port = port
self.username = username
self.password = password
|
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 | ---
+++
@@ -1,9 +1,9 @@
from django.core.management import call_command
-from celery import task
+from celery import shared_task
-@task
+@shared_task
def syncldap():
"""
Call the appropriate management command to synchronize the LDAP users |
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 | ---
+++
@@ -1,6 +1,7 @@
from lxml import html
from PIL import Image
import requests
+import urllib.request
def enlarge_image(image_file):
image = Image.open(image_file)
@@ -14,7 +15,26 @@
# Use Tesseract to extract text from the enlarged image. Then Return it.
-domain = 'speedtest.net'
+def fix_emails(w... |
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 | ---
+++
@@ -9,8 +9,10 @@
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
+
+from flask_images import Images, ImageSize, resized_img_src
+
flask_version = tuple(map(int, flask.__version__.split('.')))
|
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 | ---
+++
@@ -17,9 +17,6 @@
def identity_store(tmpdir):
from awsident.storage import IdentityStore
identity_store = IdentityStore(config_path=str(tmpdir))
- def fin():
- identity_store.identities.clear()
- identity_store.save_to_config()
return identity_store
@pytest.fixture
@@ -28,7... |
1da421dcb4356a4f572bc1a815ed7e87dc619f64 | vcfexplorer/frontend/views.py | vcfexplorer/frontend/views.py | """
vcfexplorer.frontend.views
VCF Explorer frontend views
"""
from flask import send_file
from . import bp
@bp.route('/', defaults={'path': ''})
@bp.route('/<path:path>')
def index(path):
return send_file('frontend/templates/index.html')
| """
vcfexplorer.frontend.views
VCF Explorer frontend views
"""
from flask import send_file
from . import bp
@bp.route('/', defaults={'path': ''})
@bp.route('<path:path>')
def index(path):
return send_file('frontend/templates/index.html')
| Add flexible routing, maybe change to stricter hardcoded ones? | Add flexible routing, maybe change to stricter hardcoded ones?
| Python | mit | CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer | ---
+++
@@ -9,6 +9,6 @@
from . import bp
@bp.route('/', defaults={'path': ''})
-@bp.route('/<path:path>')
+@bp.route('<path:path>')
def index(path):
return send_file('frontend/templates/index.html') |
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 | ---
+++
@@ -28,11 +28,11 @@
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
- self.assertEqual("templated NAME", ex.message)
+ self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("cu... |
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 | ---
+++
@@ -25,10 +25,10 @@
class GoogleVerificationView(VerificationView):
- template_name = 'google_verify_template.html'
+ template_name = 'webmaster_verification/google_verify_template.html'
provider = 'google'
class BingVerificationView(VerificationView):
- template_name = 'bing_verify_te... |
8312ba2ca414e5da8ad165ec08ff0205cd99a2c9 | oneflow/settings/snippets/00_production.py | oneflow/settings/snippets/00_production.py |
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# Do we show all 1flow AdminModels in admin ?
# Not by default, cf. https://trello.com/c/dJoV4xZy
FULL_ADMIN = False
|
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
import django.conf.urls.defaults # NOQA
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# Do we show all 1flow AdminModels in admin ?
# Not by default, cf. https://trello.com/c/dJoV4xZy
FULL_ADMIN = False
| Fix the annoying "/home/1flow/.virtualenvs/1flow/local/lib/python2.7/site-packages/django/conf/urls/defaults.py:3: DeprecationWarning: django.conf.urls.defaults is deprecated; use django.conf.urls instead DeprecationWarning)". We do not use it in our code at all, and external packages (rosetta, grappelli, etc) didn't i... | Fix the annoying "/home/1flow/.virtualenvs/1flow/local/lib/python2.7/site-packages/django/conf/urls/defaults.py:3: DeprecationWarning: django.conf.urls.defaults is deprecated; use django.conf.urls instead DeprecationWarning)". We do not use it in our code at all, and external packages (rosetta, grappelli, etc) didn't i... | Python | agpl-3.0 | WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow | ---
+++
@@ -1,3 +1,9 @@
+
+import warnings
+
+with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
+ import django.conf.urls.defaults # NOQA
DEBUG = False
TEMPLATE_DEBUG = DEBUG |
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 | ---
+++
@@ -1,3 +1,7 @@
+import collections
+import functools
+
+
def pipe(*functions):
def closure(x):
for fn in functions:
@@ -8,3 +12,34 @@
return out
return closure
+
+
+class memoize(object):
+ '''Decorator. Caches a function's return value each time it is called.
+ If called... |
63c72e9606ba9c9030ba63f25331c351873ab8b1 | node/multiply.py | node/multiply.py | #!/usr/bin/env python
from nodes import Node
class Multiply(Node):
char = "*"
args = 2
results = 1
@Node.test_func([4,5], [20])
def func(self, a,b):
"""a*b"""
return a*b | #!/usr/bin/env python
from nodes import Node
class Multiply(Node):
char = "*"
args = 2
results = 1
@Node.test_func([4,5], [20])
def func(self, a,b):
"""a*b"""
return[a*b] | Multiply now handles lists correctly | Multiply now handles lists correctly
| Python | mit | muddyfish/PYKE,muddyfish/PYKE | ---
+++
@@ -10,4 +10,4 @@
@Node.test_func([4,5], [20])
def func(self, a,b):
"""a*b"""
- return a*b
+ return[a*b] |
e0671b84c3d11b738d6fe6981d8b2fac87828558 | cupy/logic/ops.py | cupy/logic/ops.py | from cupy import core
logical_and = core.create_comparison(
'logical_and', '&&',
'''Computes the logical AND of two arrays.
.. seealso:: :data:`numpy.logical_and`
''',
require_sortable_dtype=False)
logical_or = core.create_comparison(
'logical_or', '||',
'''Computes the logical OR of tw... | from cupy import core
logical_and = core.create_comparison(
'logical_and', '&&',
'''Computes the logical AND of two arrays.
.. seealso:: :data:`numpy.logical_and`
''',
require_sortable_dtype=True)
logical_or = core.create_comparison(
'logical_or', '||',
'''Computes the logical OR of two... | Set required_sortable to True for logical operations | Set required_sortable to True for logical operations
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -7,7 +7,7 @@
.. seealso:: :data:`numpy.logical_and`
''',
- require_sortable_dtype=False)
+ require_sortable_dtype=True)
logical_or = core.create_comparison(
@@ -17,7 +17,7 @@
.. seealso:: :data:`numpy.logical_or`
''',
- require_sortable_dtype=False)
+ require_sortab... |
208a48a8af8228bffc85db601f4eb2423981a6ec | manager/commands_puzzleboard.py | manager/commands_puzzleboard.py | ''' commands for the manager cli '''
from uuid import uuid4
import requests
def command_puzzleboard_consume(**kwargs):
url = kwargs['--consume-url']
name = kwargs['--name']
size = kwargs['--size']
data = f'{{"puzzleboard": "{name}", "size": {size}, correlation-id": "{uuid4()}"}}'
print(data)
... | ''' commands for the manager cli '''
from uuid import uuid4
import requests
def command_puzzleboard_consume(**kwargs):
url = kwargs['--consume-url']
name = kwargs['--name']
size = kwargs['--size']
data = f'{{"puzzleboard": "{name}", "size": {size}, "correlation-id": "{uuid4()}"}}'
print(data)
... | Make sure API payload is well-formed JSON | Make sure API payload is well-formed JSON
| Python | mit | klmcwhirter/huntwords,klmcwhirter/huntwords,klmcwhirter/huntwords,klmcwhirter/huntwords | ---
+++
@@ -9,7 +9,7 @@
url = kwargs['--consume-url']
name = kwargs['--name']
size = kwargs['--size']
- data = f'{{"puzzleboard": "{name}", "size": {size}, correlation-id": "{uuid4()}"}}'
+ data = f'{{"puzzleboard": "{name}", "size": {size}, "correlation-id": "{uuid4()}"}}'
print(data)
... |
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 | ---
+++
@@ -10,6 +10,24 @@
raise Exception('simplejson>=2.1 with support for use_decimal required.')
+class CallbackOnUpdateDict(dict):
+ """Dict which executes a callback on every update"""
+
+ def __init__(self, *args, **kwargs):
+ self.callback = kwargs.pop('callback')
+ super(Callback... |
dae26a54aff5ada572b047869e83b098511bffbf | src/artgraph/plugins/plugin.py | src/artgraph/plugins/plugin.py | import MySQLdb
import mwparserfromhell
class Plugin():
def get_wikicode(self, title):
# TODO Make this a conf
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="BigData")
cursor = db.cursor()
cursor.execute("SELECT old_text FROM text INNER JOIN revision ON text.old_... | import MySQLdb
import mwparserfromhell
class Plugin():
def get_wikicode(self, title):
# TODO Make this a conf
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="BigData")
cursor = db.cursor()
cursor.execute("""
SELECT old_text
FROM text
INNER... | Fix SQL query to use indexes in the page table | Fix SQL query to use indexes in the page table | Python | mit | dMaggot/ArtistGraph | ---
+++
@@ -7,6 +7,10 @@
# TODO Make this a conf
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="BigData")
cursor = db.cursor()
- cursor.execute("SELECT old_text FROM text INNER JOIN revision ON text.old_id = revision.rev_text_id INNER JOIN page ON revision.rev_pag... |
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 | ---
+++
@@ -34,3 +34,7 @@
sales_channel_id = fields.Many2one('res.partner', string="Sales channel",
ondelete='set null', domain=_get_sales_channel_domain)
+
+ _sql_constraints = [
+ ('name_company_uniq', 'unique(name, company_id, sales_channel_id)', 'Tax Name m... |
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 | ---
+++
@@ -1,8 +1,9 @@
+from django.contrib.auth.forms import AuthenticationForm
from django import forms
-class LoginForm(forms.Form):
- email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
+class LoginForm(AuthenticationForm):
+ username = forms.CharField(widget=forms.EmailInp... |
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... | ---
+++
@@ -5,7 +5,7 @@
Author: Josef Perktold
"""
-from statsmodels.sandbox.stats.multicomp import MultiComparison
+from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence in... |
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 | ---
+++
@@ -12,15 +12,15 @@
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
- def handle_today(self, data, match):
- self.send(str(DDate()), data)
-
def handle_date(self, data, match):
year = int(match.groupdict()['year'])
mon... |
524076bd1e629e2c73413609c012223a80b7e8a3 | signbank/registration/admin.py | signbank/registration/admin.py | from signbank.registration.models import *
from django.contrib import admin
from django.core.urlresolvers import reverse
class UserProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'permissions', 'best_describes_you', 'australian', 'auslan_user', 'deaf', 'researcher_credentials']
readonly_fields = ['user... | from signbank.registration.models import *
from django.contrib import admin
from django.core.urlresolvers import reverse
class UserProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'permissions', 'best_describes_you', 'australian', 'auslan_user', 'deaf', 'researcher_credentials']
readonly_fields = ['user... | Use the correct user ID to show the user from the profiles view. Fixes %61. | Use the correct user ID to show the user from the profiles view. Fixes %61.
| Python | bsd-3-clause | Signbank/Auslan-signbank,Signbank/BSL-signbank,Signbank/BSL-signbank,Signbank/BSL-signbank,Signbank/BSL-signbank,Signbank/Auslan-signbank,Signbank/Auslan-signbank,Signbank/Auslan-signbank | ---
+++
@@ -8,7 +8,7 @@
list_filter = ['australian', 'auslan_user', 'deaf']
def permissions(self, obj):
- url = reverse('admin:auth_user_change', args=(obj.pk,))
+ url = reverse('admin:auth_user_change', args=(obj.user.id,))
return '<a href="%s">View user</a>' % (url)
permis... |
aa48fd54c8b4b0139f562de199a5f0c5dd4c5db8 | gitdir/__init__.py | gitdir/__init__.py | import pathlib
GITDIR = pathlib.Path('/opt/git') #TODO check permissions
| import pathlib
GITDIR = pathlib.Path(os.environ.get('GITDIR', '/opt/git')) #TODO check permissions
| Add support for GITDIR envar | Add support for GITDIR envar
| Python | mit | fenhl/gitdir | ---
+++
@@ -1,3 +1,3 @@
import pathlib
-GITDIR = pathlib.Path('/opt/git') #TODO check permissions
+GITDIR = pathlib.Path(os.environ.get('GITDIR', '/opt/git')) #TODO check permissions |
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... | ---
+++
@@ -21,6 +21,7 @@
from django import forms
from django.utils.translation import ugettext_lazy as _
+from django.core.validators import RegexValidator
class IkiwikiCreateForm(forms.Form):
@@ -29,7 +30,8 @@
label=_('Type'),
choices=[('wiki', 'Wiki'), ('blog', 'Blog')])
- name = f... |
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 | ---
+++
@@ -1,5 +1,19 @@
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:
+ ... |
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... | ---
+++
@@ -1,4 +1,6 @@
import logging
+from multiprocessing.reduction import reduce_connection
+import pickle
from mopidy import settings as raw_settings
@@ -18,6 +20,16 @@
class_object = getattr(module, class_name)
return class_object
+def pickle_connection(connection):
+ return pickle.dumps(re... |
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 | ---
+++
@@ -12,10 +12,16 @@
submission = json.loads(f.read())
submission["clinical"]["CGT Public ID"] = submission["patientId"]
-r = requests.post("http://localhost:5000/v0/submissions?publish=true",
- files=[("files[]",
- ("foundationone.json",
- ... |
abf141415fb0c1fbb62c92db3afdc430218e2520 | mzgtfs/validate.py | mzgtfs/validate.py | """Validate a GTFS file."""
import argparse
import json
import feed
import validation
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='GTFS Info and JSON export')
parser.add_argument('filename', help='GTFS File')
parser.add_argument('--debug',
help='Show helpful debugging informatio... | """Validate a GTFS file."""
import argparse
import json
import feed
import validation
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Validate a GTFS feed.')
parser.add_argument('filename', help='GTFS File')
parser.add_argument('--debug',
help='Show helpful debugging information', ... | Fix copy and paste error | Fix copy and paste error
| Python | mit | transitland/mapzen-gtfs,brechtvdv/mapzen-gtfs,brennan-v-/mapzen-gtfs | ---
+++
@@ -6,7 +6,7 @@
import validation
if __name__ == "__main__":
- parser = argparse.ArgumentParser(description='GTFS Info and JSON export')
+ parser = argparse.ArgumentParser(description='Validate a GTFS feed.')
parser.add_argument('filename', help='GTFS File')
parser.add_argument('--debug',
he... |
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 | ---
+++
@@ -8,3 +8,5 @@
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
+
+ assert len(self.klasses) > 100 |
becd5721e9d6dcd1eb762b9b9e7089e7a90fcdf9 | python3.7-alpine3.7/app/main.py | python3.7-alpine3.7/app/main.py | def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b"Hello World from a default Nginx uWSGI Python 3.6 app in a\
Docker container (default)"]
| def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b"Hello World from a default Nginx uWSGI Python 3.7 app in a\
Docker container (default)"]
| Update default Python demo app to reflect actual Python version | Update default Python demo app to reflect actual Python version
| Python | apache-2.0 | tiangolo/uwsgi-nginx-docker,tiangolo/uwsgi-nginx-docker | ---
+++
@@ -1,4 +1,4 @@
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
- return [b"Hello World from a default Nginx uWSGI Python 3.6 app in a\
+ return [b"Hello World from a default Nginx uWSGI Python 3.7 app in a\
Docker container (default)"] |
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 | ---
+++
@@ -1,8 +1,10 @@
-def print_generated_sequence(g, num, *, sep=", "):
+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(n... |
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 | ---
+++
@@ -1,3 +1,4 @@
+import os
from datetime import datetime
from flask import Flask
@@ -28,6 +29,8 @@
@app.route('/resolve', methods=['POST'])
def resolve():
+ if not os.environ.get('PRIVATE'):
+ return 'hullo'
return tasks.resolve.delay().id
@app.route('/health'... |
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 | ---
+++
@@ -5,4 +5,4 @@
sys.path.append('.')
import adapter
-adapter.main.run_tcp_server(multiple=False)
+adapter.main.run_tcp_server() |
b20d59211701cbcb4d7600bce2d64e7f0f614ec0 | tvrenamr/tests/base.py | tvrenamr/tests/base.py | from os import makedirs
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import urlopenmock
class BaseTest(object):
files = 'tests/files'
def setup(self):
# if `file` isn't there, ma... | from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import urlopenmock
class BaseTest(object):
files = 'tests/files'
def setup(self):
# if `file` isn't there, make ... | Use mkdir instead of makedirs because we don't need parent directories made | Use mkdir instead of makedirs because we don't need parent directories made
| Python | mit | ghickman/tvrenamr,wintersandroid/tvrenamr | ---
+++
@@ -1,4 +1,4 @@
-from os import makedirs
+from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
@@ -13,7 +13,7 @@
def setup(self):
# if `file` isn't there, make it
if not exists(self.files):
- makedirs(self.files)
+ m... |
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 | ---
+++
@@ -4,5 +4,6 @@
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.register(Campground, CampgroundAdmin) |
c827afe434d1d106ad7747e0c094188b8d5cc9a9 | plumeria/plugins/bing_images.py | plumeria/plugins/bing_images.py | from aiohttp import BasicAuth
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image"
api_key = config.create... | from aiohttp import BasicAuth
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image"
api_key = config.create... | Fix typo in Bing images. | Fix typo in Bing images.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria | ---
+++
@@ -12,7 +12,7 @@
comment="An API key from Bing")
-@commands.register("image", "images", ""i", category="Search")
+@commands.register("image", "images", "i", category="Search")
@rate_limit()
async def image(message):
""" |
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 | ---
+++
@@ -17,6 +17,7 @@
sys.exit(1)
conn = r.connect('localhost', int(options.port), db='materialscommons')
json_data = open(options.filename)
+ print "Loading template file: %s" % (options.filename)
data = json.load(json_data)
existing = r.table('templates').get(data['id']).run(conn... |
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 | ---
+++
@@ -34,16 +34,28 @@
def pop(self):
self._head = self._head.next
+ def size(self):
+ if not self._head:
+ return 0
+ else:
+ i = 0
+ z = 1
+ try:
+ a = self._head.next
+ except AttributeError:
+ ... |
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 | ---
+++
@@ -19,4 +19,5 @@
def from_course(self, course):
return self.get_query_set().filter(
- kq__unit__course=course).order_by('kq__unit__order')
+ kq__unit__course=course).order_by(
+ 'kq__unit__order', 'kq__order') |
6252706583be20abb3eb9f541d99a212489daf00 | addons/dataverse/settings/defaults.py | addons/dataverse/settings/defaults.py | DEFAULT_HOSTS = [
'dataverse.harvard.edu', # Harvard PRODUCTION server
'dataverse.lib.virginia.edu' # University of Virginia server
]
REQUEST_TIMEOUT = 15
| DEFAULT_HOSTS = [
'dataverse.harvard.edu', # Harvard PRODUCTION server
'dataverse.lib.virginia.edu' # University of Virginia server
]
REQUEST_TIMEOUT = 60
| Increase request timeout for dataverse | Increase request timeout for dataverse
Dataverse responses are slow at the moment, so we need to
give them more time
| Python | apache-2.0 | binoculars/osf.io,leb2dg/osf.io,baylee-d/osf.io,mfraezz/osf.io,pattisdr/osf.io,mattclark/osf.io,Johnetordoff/osf.io,adlius/osf.io,mfraezz/osf.io,sloria/osf.io,brianjgeiger/osf.io,binoculars/osf.io,mattclark/osf.io,Johnetordoff/osf.io,chennan47/osf.io,saradbowman/osf.io,adlius/osf.io,leb2dg/osf.io,CenterForOpenScience/o... | ---
+++
@@ -3,4 +3,4 @@
'dataverse.lib.virginia.edu' # University of Virginia server
]
-REQUEST_TIMEOUT = 15
+REQUEST_TIMEOUT = 60 |
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 | ---
+++
@@ -1,5 +1,3 @@
-from django.utils.decorators import classonlymethod
-from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, viewsets
@@ -22,8 +20,3 @@
def __init__(self, *args, **kwargs):
self.queryset = self.model.objects.all()
super(CommonAP... |
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 | ---
+++
@@ -15,7 +15,10 @@
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHOOK is None:
- raise SystemExit("SLACK_WEBHOOK environment variable not defined")
+ try:
+ from rnacentral_pipeline.secrets import SLACK_WEBHOOK
+ except:
+ raise SystemExit... |
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 | ---
+++
@@ -23,3 +23,5 @@
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
+ assert get_new_command(Command('git push --quiet', stderr=stderr))\
+ == "git push --set-upstream origin master --quiet" |
3dad25bd909d4396129c7fe4aa848770119f0db7 | app/util/danger.py | app/util/danger.py | from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import request as flask_request
from flask import abort
import logging
import os
def gen_auth_token(id,expiration=10000):
"""Generate auth token"""
s = Serializer(os.environ['API_KEY'],expires_in=expiration)
return s.dumps({... | from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import request as flask_request
from flask import abort
import logging
import os
def gen_auth_token(id,expiration=10000):
"""Generate auth token"""
try:
s = Serializer(os.environ['API_KEY'],expires_in=expiration)
exc... | Add exception catch in gen_auth_token and add better logging messages | Add exception catch in gen_auth_token and add better logging messages
| Python | mit | tforrest/soda-automation,tforrest/soda-automation | ---
+++
@@ -7,7 +7,12 @@
def gen_auth_token(id,expiration=10000):
"""Generate auth token"""
- s = Serializer(os.environ['API_KEY'],expires_in=expiration)
+ try:
+ s = Serializer(os.environ['API_KEY'],expires_in=expiration)
+ except KeyError:
+ logging.fatal("No API_KEY env")
+ ab... |
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... | ---
+++
@@ -5,3 +5,8 @@
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[4].text == u'?' |
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 | ---
+++
@@ -29,6 +29,7 @@
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
+ m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
|
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 | ---
+++
@@ -1,5 +1,7 @@
"""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,
@@ -12,11 +14,19 @@
... |
4f9ef0c4690a3d99e045c0ad347023dba3733bd0 | doc/filter-sectionnumbers.py | doc/filter-sectionnumbers.py | # remove section numbers for subheadings
# Based on Wagner Macedo's filter.py posted at
# https://groups.google.com/forum/#!msg/pandoc-discuss/RUC-tuu_qf0/h-H3RRVt1coJ
import pandocfilters as pf
sec = 0
def do_filter(k, v, f, m):
global sec
if sec > 3 or (k == "Header" and v[0] < 3):
return []
if ... | # remove section numbers for subheadings
# Based on Wagner Macedo's filter.py posted at
# https://groups.google.com/forum/#!msg/pandoc-discuss/RUC-tuu_qf0/h-H3RRVt1coJ
import pandocfilters as pf
sec = 0
def do_filter(k, v, f, m):
global sec
if sec > 2 or (k == "Header" and v[0] < 3):
return []
if ... | Reduce changelog excerpt for webpage and pdf | Reduce changelog excerpt for webpage and pdf
| Python | apache-2.0 | wilsonCernWq/ospray,ospray/OSPRay,ospray/OSPRay,ospray/OSPRay,wilsonCernWq/ospray,wilsonCernWq/ospray,ospray/OSPRay | ---
+++
@@ -7,7 +7,7 @@
def do_filter(k, v, f, m):
global sec
- if sec > 3 or (k == "Header" and v[0] < 3):
+ if sec > 2 or (k == "Header" and v[0] < 3):
return []
if k == "Header" and v[0] > 2:
sec += 1 |
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 | ---
+++
@@ -13,7 +13,7 @@
return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32)
-train_and_evaluate = qnd.def_train_and_evaluate()
+train_and_evaluate = qnd.def_train_and_evaluate(distributed=True)
def main(): |
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 | ---
+++
@@ -20,6 +20,7 @@
class RideRiderSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
+ signup_date = serializers.DateTimeField(required=False)
class Meta:
model = RideRiders |
76b85cd4fc848bf1b9db9d5e3a90e376400c66cb | src/pretix/urls.py | src/pretix/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
import pretix.control.urls
import pretix.presale.urls
urlpatterns = [
url(r'^control/', include(pretix.control.urls, namespace='control')),
url(r'^admin/', include(admin.site.urls)),
# The pretixpr... | import importlib
from django.apps import apps
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
import pretix.control.urls
import pretix.presale.urls
urlpatterns = [
url(r'^control/', include(pretix.control.urls, namespace='control')),
url(r'^admin/',... | Allow plugins to register URLs | Allow plugins to register URLs
| Python | apache-2.0 | lab2112/pretix,Flamacue/pretix,Unicorn-rzl/pretix,awg24/pretix,Flamacue/pretix,awg24/pretix,Unicorn-rzl/pretix,lab2112/pretix,Unicorn-rzl/pretix,akuks/pretix,akuks/pretix,lab2112/pretix,lab2112/pretix,awg24/pretix,Flamacue/pretix,akuks/pretix,awg24/pretix,akuks/pretix,Flamacue/pretix,Unicorn-rzl/pretix | ---
+++
@@ -1,3 +1,5 @@
+import importlib
+from django.apps import apps
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
@@ -19,6 +21,16 @@
url(r'^__debug__/', include(debug_toolbar.urls)),
)
+for app in apps.get_app_configs():
+ if hasa... |
0cb85aade1cfd7f264263bbe7113cb013b39cb44 | src/rolca/core/api/urls.py | src/rolca/core/api/urls.py | """.. Ignore pydocstyle D400.
=============
Core API URLs
=============
The ``routList`` is ment to be included in ``urlpatterns`` with the
following code:
.. code-block:: python
from rest_framework import routers
from rolca.core.api import urls as core_api_urls
route_lists = [
core_api_urls.r... | """.. Ignore pydocstyle D400.
=============
Core API URLs
=============
The ``routList`` is ment to be included in ``urlpatterns`` with the
following code:
.. code-block:: python
from rest_framework import routers
from rolca.core.api import urls as core_api_urls
route_lists = [
core_api_urls.r... | Rename photo endpoint to submission | Rename photo endpoint to submission
| Python | apache-2.0 | dblenkus/rolca,dblenkus/rolca,dblenkus/rolca | ---
+++
@@ -30,6 +30,6 @@
from rolca.core.api.views import ContestViewSet, SubmissionViewSet
routeList = (
- (r'photo', SubmissionViewSet),
+ (r'submission', SubmissionViewSet),
(r'contest', ContestViewSet),
) |
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 | ---
+++
@@ -23,6 +23,8 @@
ModuleName = str(src).split("from")[0].strip("(").rstrip(" ")
if loadType != 'rel':
print ModuleName + " loaded."
+ else:
+ print ModuleName + " reloaded."
func = src.Instantiate()
|
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 | ---
+++
@@ -1,2 +1,8 @@
def strtobool(x):
- return x.lower() in ("true", "yes", "1", "y")
+ try:
+ b = x.lower() in ("true", "yes", "1", "y")
+ return b
+ except AttributeError:
+ return False
+ except NameError
+ return False |
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 | ---
+++
@@ -1,11 +1,8 @@
-import numpy as np
-from numpy.testing import assert_allclose
import pytest
+from distutils.version import LooseVersion
+import matplotlib as mpl
-from astropy.io import fits
-from ..pvextractor import extract_pv_slice
-from ..geometry.path import Path
from ..gui import PVSlicer
fro... |
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 | ---
+++
@@ -18,6 +18,13 @@
def __unicode__(self):
return u"{0}:{1}".format(self.identifier, self.key)
+ @property
+ def expired(self):
+ """Returns whether or not the credentials have expired"""
+ if self.expiry < datetime.datetime.now():
+ return True
+ return False
+
class Nonce(model... |
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 | ---
+++
@@ -14,5 +14,7 @@
return self.remove_control_characters(value)
@staticmethod
- def remove_control_characters(str):
- return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
+ def remove_control_characters(input):
+ valid_chars = ['\n', '\r']
+ return "... |
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 | ---
+++
@@ -2,8 +2,18 @@
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 c... |
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 | ---
+++
@@ -3,6 +3,8 @@
from urllib.error import URLError
import sys
+
+ENORMOUS_INJECTION_HACK = False
GITHUB_USERS = [('Polymer', '0.5.2')]
@@ -23,13 +25,18 @@
if matched_assets:
print(" Matched.")
data = {'base': base_url, 'assets': {a: a for a in matched_assets}}
- print(... |
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 | ---
+++
@@ -1,3 +1,30 @@
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
-# Create your models here.
+# Extends User model. Defines sn and notifications for a User.
+class Profile(models.Model):
+ use... |
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 | ---
+++
@@ -14,7 +14,7 @@
"""
config = {}
-_default = object()
+_missing = object()
def configure(**kwargs):
@@ -22,9 +22,9 @@
config.update(kwargs)
-def get_config(key, default=_default):
+def get_config(key, default=_missing):
"""Lookup the value of a configuration key using an optional defau... |
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 | ---
+++
@@ -2,10 +2,11 @@
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
- "FromAddrMultiplexRouter", "UserGroupingRouter"]
+ "FromAddrMultiplexRouter", "UserGroupingRouter",
+ "ContentKeywordRou... |
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 | ---
+++
@@ -21,3 +21,16 @@
The tests check if a value is anywhere in the dataframe
"""
+
+
+def test_issues_first_time_opened(augur_db):
+
+ # repo_id
+ assert augur_db.issues_first_time_opened(
+ 1, repo_id=25001, period='day').isin(["2019-05-23 00:00:00+00:00"]).any
+ assert augur_db.issues_firs... |
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 | ---
+++
@@ -12,6 +12,7 @@
]
def ceg_rows(rows):
+ rows = list(rows)
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime): |
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 | ---
+++
@@ -15,3 +15,14 @@
# By default, nothing is mounted on `/`, but at least check that
# the application boots up and doesn't return a server error.
assert response.status_code == 404
+ assert response.location is None
+
+
+def test_homepage_with_root_redirect(make_site_app, site):
+ site_ap... |
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... | ---
+++
@@ -25,4 +25,7 @@
if not self.released_languages.strip(): # pylint: disable=no-member
return []
- return [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
+ languages = [lang.strip() for lang in self.released_languages.split(',')]... |
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 | ---
+++
@@ -29,6 +29,5 @@
functions = ["sum"]
not_implemented = [
- 'test_bytearray',
'test_frozenzet',
] |
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 | ---
+++
@@ -10,8 +10,11 @@
class TestInstrumentDb(ut.TestCase):
def test_paths(self):
- self.assertTrue(os.path.exists(idb.instrument_db_path()))
+ self.assertTrue(os.path.exists(idb.instrument_db_path()),
+ 'Path "{0}" not found'.format(idb.instrument_db_path()))
- ... |
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 | ---
+++
@@ -17,7 +17,11 @@
def __str__(self):
return type(self).name
- def move(self, game):
+ ##########
+ # Player #
+ ##########
+
+ def choose_move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
@@ ... |
8b19a4e275313cf2226f535d3ec10f414e0c6885 | django/__init__.py | django/__init__.py | VERSION = (1, 6, 6, 'alpha', 0)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
| VERSION = (1, 6, 6, 'final', 0)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
| Update version number for security release. | [1.6.x] Update version number for security release.
| Python | bsd-3-clause | felixjimenez/django,django-nonrel/django,felixjimenez/django,redhat-openstack/django,felixjimenez/django,redhat-openstack/django,redhat-openstack/django,django-nonrel/django,django-nonrel/django,redhat-openstack/django,django-nonrel/django,felixjimenez/django | ---
+++
@@ -1,4 +1,4 @@
-VERSION = (1, 6, 6, 'alpha', 0)
+VERSION = (1, 6, 6, 'final', 0)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff. |
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 | ---
+++
@@ -9,8 +9,9 @@
v_code = CharField(max_length=64, min_length=1)
def clean(self):
+ super(AddAPIForm, self).clean()
self._clean()
- return super(AddAPIForm, self).clean()
+ return self.cleaned_data
def _clean(self):
"""Check the access mask and characte... |
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 | ---
+++
@@ -6,37 +6,49 @@
import yaml
-DESC = "Prints version and model type from model.npz file."
+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)
- model = np.load(args.model)
- if S2... |
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 | ---
+++
@@ -8,7 +8,8 @@
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
- oanda = oandapy.API(environment="practice", access_token=oanda_token)
+ oanda_environment = os.environ.get('OANDA_ENVIRONMENT', 'practice')
+ oanda = ... |
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 | ---
+++
@@ -11,7 +11,8 @@
def main(data_path, index_path, report_each=10000):
print('Looking for data in "{}"...'.format(data_path))
paths = sorted(glob.glob('{}/**/*.sqlite3'.format(data_path)))
- print('Processing {} databases...'.format(len(paths)))
+ total = len(paths)
+ print('Processing {} d... |
2e6e7d8ec05f2a760f12f2547730c4707a07ebfa | utils/swift_build_support/tests/test_xcrun.py | utils/swift_build_support/tests/test_xcrun.py | # test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for ... | # test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for ... | Fix typo XCRun -> xcrun | [gardening][build-script] Fix typo XCRun -> xcrun | Python | apache-2.0 | nathawes/swift,xedin/swift,apple/swift,aschwaighofer/swift,practicalswift/swift,glessard/swift,uasys/swift,rudkx/swift,huonw/swift,roambotics/swift,Jnosh/swift,bitjammer/swift,shahmishal/swift,lorentey/swift,modocache/swift,manavgabhawala/swift,KrishMunot/swift,devincoughlin/swift,nathawes/swift,atrick/swift,zisko/swif... | ---
+++
@@ -17,7 +17,7 @@
class FindTestCase(unittest.TestCase):
def setUp(self):
if platform.system() != 'Darwin':
- self.skipTest('XCRun tests should only be run on OS X')
+ self.skipTest('xcrun tests should only be run on OS X')
def test_when_tool_not_found_returns_none(... |
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 | ---
+++
@@ -10,13 +10,13 @@
# WITHOUT ANY WARRANTY. See the LICENSE file for more details.
#
-from enum import auto, Enum
+from enum import Enum
__all__ = [
'MentionType',
]
class MentionType(Enum):
- USER = auto()
- ROLE = auto()
- CHANNEL = auto()
+ USER = 0
+ ROLE = 1
+ CHANNEL = ... |
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 | ---
+++
@@ -15,11 +15,15 @@
def frame_period_sec(self):
return self._frame_period_sec
+ @property
+ def finished(self):
+ raise NotImplementedError('Animation must implement finished property')
+
def begin(self):
pass
def next_frame(self):
- pass
+ raise... |
c81a94568f12fca42c1cce1237c128c3123f6f73 | gunicorn_config.py | gunicorn_config.py | bind = ':5000'
workers = 2
errorlog = '/var/log/hgprofiler_gunicorn_error.log'
loglevel = 'info'
accesslog = '/var/log/hgprofiler_gunicorn_access.log'
| bind = ':5000'
workers = 4
errorlog = '/var/log/hgprofiler_gunicorn_error.log'
loglevel = 'info'
accesslog = '/var/log/hgprofiler_gunicorn_access.log'
| Set gunicorn workers to 4 | Set gunicorn workers to 4
| Python | apache-2.0 | TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler | ---
+++
@@ -1,5 +1,5 @@
bind = ':5000'
-workers = 2
+workers = 4
errorlog = '/var/log/hgprofiler_gunicorn_error.log'
loglevel = 'info'
accesslog = '/var/log/hgprofiler_gunicorn_access.log' |
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... | ---
+++
@@ -1,10 +1,8 @@
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
-from profiles.views import (ProfilesList,
- ProfileEdit,
-)
+from .views import ProfilesList, ProfileEdit
urlpatterns = patterns("",
url(r'^list/$', Profiles... |
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... | ---
+++
@@ -1,8 +1,13 @@
-from seleniumbase import BaseCase
+"""
+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(BaseCase):
+class MyTestClass(unittes... |
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 | ---
+++
@@ -24,3 +24,11 @@
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
+
+# error handling
+
+def test_same_enitities_should_throw_error():
+ pass
+
+def test_same_params_should_throw_error():
+ pass |
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 | ---
+++
@@ -10,20 +10,26 @@
def get(self):
queryset = Project.query.order_by(Project.name.asc())
- # queryset = Build.query.options(
- # joinedload(Build.project),
- # joinedload(Build.author),
- # ).order_by(Build.date_created.desc(), Build.date_started.desc())
- ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.