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 |
|---|---|---|---|---|---|---|---|---|---|---|
c827ba1ec1846847e44416c6ec5a74418558657c | soundmeter/settings.py | soundmeter/settings.py | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigPa... | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigPa... | Modify exception handling to local config names | Modify exception handling to local config names
| Python | bsd-2-clause | shichao-an/soundmeter | ---
+++
@@ -19,10 +19,13 @@
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
- if name in ['audio_segment_length']:
+ elif name in ['audio_segment_length']:
items[name] = float(items[name])... |
e9aef2b63b1a6036703aa73bc0a6c30bb9425eb6 | io_helpers.py | io_helpers.py | import subprocess
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)... | import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(object):
def __init__(self, button_gpio, callback):
self._button_gpio = button_gpio
self._callback = callback
GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def is_pressed(self):
... | Add LED and Button classes | Add LED and Button classes
| Python | mit | jessstringham/raspberrypi | ---
+++
@@ -1,4 +1,38 @@
import subprocess
+
+import RPi.GPIO as GPIO
+
+
+GPIO.setmode(GPIO.BOARD)
+
+
+class Button(object):
+
+ def __init__(self, button_gpio, callback):
+ self._button_gpio = button_gpio
+ self._callback = callback
+ GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPI... |
0337d51dc2c65c376f30046a0869c6fabf012cd0 | webfinger/__init__.py | webfinger/__init__.py | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.o... | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFi... | Improve docs and import WebFingerBuilder | Improve docs and import WebFingerBuilder
| Python | bsd-3-clause | Elizafox/python-webfinger | ---
+++
@@ -2,15 +2,29 @@
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
+
+This package provides a few tools for using WebFinger, including:
+ - requests-based webfinger client (webfinger.client.requests.WebFingerClient)
+ - aiohttp-based... |
0656b4c1be9820f3cd096359cd8817153f2e0b81 | freelancefinder/remotes/tests/test_tasks.py | freelancefinder/remotes/tests/test_tasks.py | """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
... | """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
... | Test broken harvest doesn't break everything. | Test broken harvest doesn't break everything.
| Python | bsd-3-clause | ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder | ---
+++
@@ -29,3 +29,14 @@
assert pre_posts != post_posts
assert post_posts > 0
+
+
+def test_broken_harvest(mocker):
+ """Verify that broken harvest doesn't throw."""
+ mocker.patch('feedparser.parse', side_effect=lambda x: 'broken')
+ Source.objects.all().delete()
+ Source.objects.create(cod... |
460580ff585fa76cebc5e2e9cb1d49550db9f68d | components/item_lock.py | components/item_lock.py | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self... | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
... | Set timestamp on item lock operation | Set timestamp on item lock operation
| Python | agpl-3.0 | akintolga/superdesk,superdesk/superdesk-ntb,verifiedpixel/superdesk,Aca-jov/superdesk,amagdas/superdesk,hlmnrmr/superdesk,verifiedpixel/superdesk,pavlovicnemanja/superdesk,ioanpocol/superdesk-ntb,liveblog/superdesk,marwoodandrew/superdesk-aap,sivakuna-aap/superdesk,mugurrus/superdesk,akintolga/superdesk-aap,pavlovicnem... | ---
+++
@@ -1,6 +1,7 @@
from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
+from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
@@ -16,7 +17,7 @@
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
... |
089e4f59fdf73d1a4e8d03ac07f475b2ffe62e30 | docs/css_diagram_role.py | docs/css_diagram_role.py | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('... | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-t... | Change URL used for CSS diagrams | Change URL used for CSS diagrams
| Python | bsd-3-clause | SimonSapin/tinycss2 | ---
+++
@@ -8,7 +8,7 @@
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
- ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
+ ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block... |
78c4e61684baaae3487641a2c1813bbd664822a1 | kolibri/__init__.py | kolibri/__init__.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (... | Bump to next dev cycle | Bump to next dev cycle
| Python | mit | lyw07/kolibri,jonboiser/kolibri,indirectlylit/kolibri,learningequality/kolibri,DXCanas/kolibri,benjaoming/kolibri,learningequality/kolibri,learningequality/kolibri,lyw07/kolibri,benjaoming/kolibri,indirectlylit/kolibri,DXCanas/kolibri,mrpau/kolibri,mrpau/kolibri,mrpau/kolibri,benjaoming/kolibri,benjaoming/kolibri,lyw07... | ---
+++
@@ -6,7 +6,7 @@
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
-VERSION = (0, 9, 0, 'final', 0)
+VERSION = (0, 9, 1, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.o... |
becc9ff7e1d260f9a4f47a36a0e6403e71f9f0b0 | contentcuration/contentcuration/utils/messages.py | contentcuration/contentcuration/utils/messages.py | import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
locale_path = os.path.join(path, locale)
return... | import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESS... | Remove no longer needed local variable. | Remove no longer needed local variable.
| Python | mit | DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation | ---
+++
@@ -10,8 +10,7 @@
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
- locale_path = os.path.join(path, locale)
- return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
+ return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "conte... |
1c40e03b487ae3dcef9a683de960f9895936d370 | haas/utils.py | haas/utils.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
L... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import h... | Use importlib instead of __import__ | Use importlib instead of __import__
| Python | bsd-3-clause | itziakos/haas,itziakos/haas,sjagoe/haas,scalative/haas,sjagoe/haas,scalative/haas | ---
+++
@@ -6,9 +6,10 @@
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
+import importlib
+import logging
+
import haas
-import logging
-import sys
LEVELS = {
@@ -39,5 +40,4 @@
"""Import a module and return the imported mod... |
7e4fc8857284c539ce91dd53f11b460a6c9b1633 | scrapi/settings/local-dist.py | scrapi/settings/local-dist.py | RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
| RAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
| Fix local dist to see if that fixes things | Fix local dist to see if that fixes things
| Python | apache-2.0 | erinspace/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi | ---
+++
@@ -1,2 +1,3 @@
-RAW_PROCESSING = ['cassandra']
-NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
+RAW_PROCESSING = ['postgres']
+NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
+RESPONSE_PROCESSOR = 'postgres' |
5303e99508a5c64d3a40cbfd6b6e4c29c74c647f | h2o-py/tests/testdir_misc/pyunit_space_headers.py | h2o-py/tests/testdir_misc/pyunit_space_headers.py | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start stati... | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start stati... | Update pyunit to compare a list value instead of a scalar | Update pyunit to compare a list value instead of a scalar
| Python | apache-2.0 | h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-3,spennihana/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,spennihana/h2o-3,mathemage/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,spenniha... | ---
+++
@@ -19,7 +19,7 @@
h2o_median = f["start station id"].median()
- assert h2o_median == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
+ assert h2o_median[0] == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
... |
d293aedf296f4b63cb11ece1c00778981afef20c | pycat/cli.py | pycat/cli.py | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to... | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to... | Print out nicer error messages on connection errors | Print out nicer error messages on connection errors
| Python | mit | prophile/pycat | ---
+++
@@ -30,3 +30,5 @@
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
+ except ConnectionError as e:
+ print(str(e), file=sys.stderr) |
5b43264321e4649312050264524a6df7682a6641 | mfr/ext/md/tests/test_md.py | mfr/ext/md/tests/test_md.py | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em... | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).co... | Update md test for render fix | Update md test for render fix
| Python | apache-2.0 | CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,Johnetordoff/modular-file-renderer,AddisonSchiller/modular-file-renderer,mfraezz/modular-file-renderer,rdhyee/modular-file-renderer,icereval/modular-file-renderer,TomBaxter/modular-file-renderer,Johnetordoff/modular-file-renderer,rdhyee/modular-fi... | ---
+++
@@ -4,15 +4,15 @@
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
- assert render.render_html(fakefile) == '<h1>foo</h1>'
+ assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
- assert rende... |
01385f012f984d8a04d3cd9c71ca3cf582a9bf5d | package_name/module.py | package_name/module.py | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is p... | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is p... | Change comment Google -> numpy docstring format | DOC: Change comment Google -> numpy docstring format
| Python | mit | scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-continuous-integration | ---
+++
@@ -21,7 +21,7 @@
Note
----
- This is a sample function, using a Google docstring format.
+ This is a sample function, using a numpy docstring format.
Note
---- |
76e5d94e12717db685b0c0c66e893d7e4365a57b | examples/connect.py | examples/connect.py | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 ag... | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 ag... | Update the script to accept arguments | Update the script to accept arguments
| Python | apache-2.0 | graphite-server/psphere,jkinred/psphere | ---
+++
@@ -13,20 +13,39 @@
# License for the specific language governing permissions and limitations
# under the License.
+from psphere import config
from psphere.client import Client
-from psphere.scripting import BaseScript
-class Connect(BaseScript):
- def connect(self):
- """A simple connection ... |
756e11445b3f1ba52f3c3be7029fd172d6527722 | run_tests.py | run_tests.py | import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPa... | import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', sub... | Fix the python script that runs the tests. | Fix the python script that runs the tests.
| Python | agpl-3.0 | ROBO3D/CuraEngine,electrocbd/CuraEngine,derekhe/CuraEngine,alephobjects/CuraEngine,Jwis921/PersonalCuraEngine,pratikshashroff/pcura,Jwis921/PersonalCuraEngine,totalretribution/CuraEngine,Skeen/CuraJS-Engine,uus169/CuraEngine,pratikshashroff/pcura,Jwis921/PersonalCuraEngine,patrick3coffee/CuraTinyG,be3d/CuraEngine,phony... | ---
+++
@@ -3,14 +3,14 @@
import subprocess
def main():
- executableName = 'CuraEngine'
+ executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
- ret = subprocess.call([e... |
02fbf47a49cb66391dcb22b1a7ba7a38be210ffe | ooi/config.py | ooi/config.py | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# 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 requ... | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# 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 requ... | Switch to using oslo_* instead of oslo.* | Switch to using oslo_* instead of oslo.*
Change-Id: Ibb578a945f6cb655a35acb744837a14b43117333
| Python | apache-2.0 | openstack/ooi,alvarolopez/ooi,stackforge/ooi,orviz/ooi | ---
+++
@@ -15,7 +15,7 @@
# under the License.
-from oslo.config import cfg
+from oslo_config import cfg
def parse_args(argv, default_config_files=None): |
a9bdfe489e79aec7f3b422854c58d4fe893f2b95 | duplicate_lines.py | duplicate_lines.py | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.in... | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up... | Add ability to perform 'duplicate up'. | Add ability to perform 'duplicate up'.
| Python | mit | shagabutdinov/sublime-duplicate-lines-enhanced | ---
+++
@@ -1,14 +1,8 @@
import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
- def run(self, edit):
+ def run(self, edit, **args):
for region in self.view.sel():
- if region.empty():
- line = self.view.line(region)
- line_... |
d80a21abcc56192d57c987cf4b8e2057e1d4ffcd | nethud/nh_client.py | nethud/nh_client.py | """
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('a... | """
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connection... | Make all the things unicode. | Make all the things unicode.
| Python | mit | ryansb/netHUD | ---
+++
@@ -1,6 +1,7 @@
"""
An example client. Run simpleserv.py first before running this.
"""
+from __future__ import unicode_literals
import json
@@ -26,7 +27,7 @@
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
- self.transpo... |
57f72a0f64ccc7713a38a03d016e05ec8c528b1d | framework/sentry/__init__.py | framework/sentry/__init__.py | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# ... | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# ... | Add session info to extra data | Add session info to extra data
| Python | apache-2.0 | crcresearch/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,TomBaxter/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,mfraezz/osf.io,icereval/osf.io,binoculars/osf.io,leb2dg/osf.io,baylee-d/osf.io,mfraezz/osf.io,laurenrevere/osf.io,chennan47/osf.io,caneruguz/osf.io,felliott/osf.io,mattclark/osf.io,ad... | ---
+++
@@ -35,11 +35,16 @@
})
-def log_message(message, extra={}):
+def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
+ extra = {
+ 'session': get_sessi... |
5853a5767c2b73d14fd1cd0b8843bda38de5b4c2 | InvenTree/part/views.py | InvenTree/part/views.py | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
querys... | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
querys... | Fix for part category API | Fix for part category API
| Python | mit | SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree | ---
+++
@@ -39,4 +39,4 @@
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
- serializer_class = PartCategoryBriefSerializer
+ serializer_class = PartCategoryDetailSerializer |
c66a2933cca12fa27b688f60b3eb70b07bcce4e5 | src/ggrc/migrations/utils.py | src/ggrc/migrations/utils.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import alias... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import alias... | Verify that new attribute doesn't already exist in database | Verify that new attribute doesn't already exist in database
| Python | apache-2.0 | prasannav7/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-co... | ---
+++
@@ -8,13 +8,19 @@
from sqlalchemy.orm import aliased
-def resolve_duplicates(model, attr):
+def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
... |
52a6b421f4a9b0c9956ffec8f684609d43260a85 | login/tests.py | login/tests.py | from django.test import TestCase
# Create your tests here.
| from django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.g... | Add test cases for login process | Add test cases for login process
| Python | agpl-3.0 | verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool | ---
+++
@@ -1,3 +1,60 @@
-from django.test import TestCase
+from django.contrib.auth.models import User
+from django.test import TestCase, Client
-# Create your tests here.
+
+class LoginTestCase(TestCase):
+
+ def setUp(self):
+ User.objects.create_user(
+ username='user',
+ passwor... |
0431011632b9852f644f33803cffbd4f7ace0887 | gamecraft/settings_heroku.py | gamecraft/settings_heroku.py | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redi... | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redi... | Add redirect middleware to heroku configs | Add redirect middleware to heroku configs
| Python | mit | micktwomey/gamecraft-mk-iii,micktwomey/gamecraft-mk-iii,micktwomey/gamecraft-mk-iii,micktwomey/gamecraft-mk-iii | ---
+++
@@ -40,4 +40,5 @@
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
+ 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
) |
a6c06c61e9fa11c6b441fdf2a5075ca35015d7e0 | tests/test_windows.py | tests/test_windows.py | import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
| import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
| Test that asserts odd numbered windows dont work | Test that asserts odd numbered windows dont work
| Python | mit | audiolabs/mdct | ---
+++
@@ -4,3 +4,6 @@
def test_kbd():
mdct.windows.kaiser_derived(50)
+
+ with pytest.raises(ValueError):
+ mdct.windows.kaiser_derived(51) |
342512a12868bc7dadbaf3c85b5aedd86bb990e7 | gunicorn/workers/__init__.py | gunicorn/workers/__init__.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "guni... | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "guni... | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.
| Python | mit | GitHublong/gunicorn,elelianghh/gunicorn,ephes/gunicorn,malept/gunicorn,malept/gunicorn,tempbottle/gunicorn,malept/gunicorn,ccl0326/gunicorn,keakon/gunicorn,mvaled/gunicorn,tejasmanohar/gunicorn,mvaled/gunicorn,WSDC-NITWarangal/gunicorn,gtrdotmcs/gunicorn,mvaled/gunicorn,z-fork/gunicorn,prezi/gunicorn,zhoucen/gunicorn,p... | ---
+++
@@ -12,7 +12,9 @@
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
- "tornado": "gunicorn.workers.gtornado.TornadoWorker"}
+ "tornado": "gunicorn.workers.gtornad... |
5daef3041ced3e8a3fc8e9d7d64ab43607bb24ae | allauth/socialaccount/providers/feedly/views.py | allauth/socialaccount/providers/feedly/views.py | from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
... | from __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2Call... | Add option FEEDLY_HOST for feedly.com provider | Add option FEEDLY_HOST for feedly.com provider | Python | mit | wli/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,spool/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,AltSchool/django-allauth,joshowen/django-allauth,lukeburden/django-allauth,bittner/django-allauth,jwhitlock/django-allauth,jwhitlock/... | ---
+++
@@ -1,6 +1,7 @@
from __future__ import unicode_literals
import requests
+from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
... |
1633fe8e8e3d97273256fd64cac0447737ef1594 | jsonrpcclient/__init__.py | jsonrpcclient/__init__.py | """__init__.py"""
from jsonrpcclient.request import Request
| """__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| Add NullHandler to logger to quiet Python 2.7 | Add NullHandler to logger to quiet Python 2.7
| Python | mit | bcb/jsonrpcclient | ---
+++
@@ -1,2 +1,6 @@
"""__init__.py"""
+
+import logging
+logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
+
from jsonrpcclient.request import Request |
1f6cac883995cfaf4d1b19c6c13f3fc13e9ddc7a | tools/scyllatop/views/base.py | tools/scyllatop/views/base.py | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
... | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
... | Use 'erase' to clear the screen | tools/scyllatop: Use 'erase' to clear the screen
The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.
Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com>
| Python | agpl-3.0 | raphaelsc/scylla,avikivity/scylla,scylladb/scylla,duarten/scylla,avikivity/scylla,scylladb/scylla,kjniemi/scylla,kjniemi/scylla,duarten/scylla,duarten/scylla,scylladb/scylla,kjniemi/scylla,raphaelsc/scylla,scylladb/scylla,avikivity/scylla,raphaelsc/scylla | ---
+++
@@ -30,7 +30,7 @@
curses.doupdate()
def clearScreen(self):
- self._window.clear()
+ self._window.erase()
self._window.move(0, 0)
def writeLine(self, thing, line): |
f2afbc2d7b47e6e28f6924b9761390c34b04ea49 | trunk/editor/test_opensave.py | trunk/editor/test_opensave.py | #!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(des... | #!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(... | Use one of the stock examples for the open/save test | Use one of the stock examples for the open/save test
| Python | mit | develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/env python
+import os
import unittest
from xml.etree import ElementTree
@@ -7,10 +8,14 @@
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
+ test_output = "a.rooms"
def test1(self):
- source = "world1.rooms"
- dest = 'a.rooms'... |
3b539cedd12948fde71cad29a4eee517d4adff1e | bot.py | bot.py | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter... | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter... | Put back to 12 hours. | Put back to 12 hours.
| Python | mit | gregsabo/only_keep_one,gregsabo/only_keep_one | ---
+++
@@ -31,5 +31,4 @@
tweet = crawl()
if tweet:
twitter.tweet(tweet)
- time.sleep(60)
- #time.sleep(43200) # 12 hours
+ time.sleep(43200) # 12 hours |
91b1ac2aee1a6d98b45aba26d4ab80feae505705 | new.py | new.py | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(b... | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(b... | Use split_up in both places | Use split_up in both places
| Python | mit | thefotes/DoItDoneIt | ---
+++
@@ -14,7 +14,7 @@
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
- file_name = os.path.splitext(base)[0]
+ file_name = split_up[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
... |
633e3672c3f6f0200e45167ad5dc7608ef7f9e93 | run.py | run.py | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension... | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os... | Use Heroku post & open interface | Use Heroku post & open interface
| Python | bsd-3-clause | vanesa/kid-o,vanesa/kid-o,vanesa/kid-o,vanesa/kid-o | ---
+++
@@ -10,10 +10,11 @@
# debug = True as DebugToolbarExtension is invoked
- app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
- app.run()
+ PORT = int(os.environ.get("PORT", 5000))
+
+ app.run(debug=True, host="0.0.0.0", port=PORT) |
6cf782dc1b0d0cee2d234b36791be0deb64cd1de | run.py | run.py | import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.env... | import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args ... | Read env variables with dotenv | Read env variables with dotenv
| Python | mit | Wisheri/Nordea-to-YNAB | ---
+++
@@ -3,6 +3,7 @@
import sys
from src.main import run
import logging
+from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
@@ -10,6 +11,7 @@
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
+ load_dotenv(find_dot... |
67b2729c1c2a7027be7ad7a9d641609e94769671 | quickstart/python/autopilot/create-hello-world-samples/create_hello_world_samples.6.x.py | quickstart/python/autopilot/create-hello-world-samples/create_hello_world_samples.6.x.py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
... | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
... | Update to use unique_name for task update | Update to use unique_name for task update | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | ---
+++
@@ -14,11 +14,10 @@
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
-# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
... |
6de7d5059d6d5fd2569f108e83fff0ae979aad89 | train_twitter_data.py | train_twitter_data.py | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = cou... | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but a... | Make vectorizer Ignore decode errors | Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.
| Python | apache-2.0 | ngrudzinski/sentiment_analysis_437 | ---
+++
@@ -6,6 +6,7 @@
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
-count_vect = CountVectorizer()
+#Ignoring decode errors may harm our results, but at least it works now
+count_vect = CountVectorizer(decode_error='ign... |
c1cd227e564ff1caf868068a182bf258aac47728 | python/testData/inspections/PyTypeCheckerInspection/MapArgumentsInOppositeOrderPy2.py | python/testData/inspections/PyTypeCheckerInspection/MapArgumentsInOppositeOrderPy2.py | map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
| map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
| Fix test data after syncing with typeshed | Fix test data after syncing with typeshed
| Python | apache-2.0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/int... | ---
+++
@@ -1 +1 @@
-map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
+map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning... |
40fd8c680f335ebd1bc217f35a47f169c336530c | pyosf/tools.py | pyosf/tools.py | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from... | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_li... | Fix compatibility with Py3 (generators no longer have next()) | Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too
| Python | mit | psychopy/pyosf | ---
+++
@@ -12,7 +12,7 @@
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
- return (item for item in in_list if item[key] == val).next()
+ return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key): |
3d91c12d3382226263ea3d660b48f1ef1125d099 | tests/basics/ordereddict1.py | tests/basics/ordereddict1.py | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(... | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b... | Add further tests for OrderedDict. | tests/basics: Add further tests for OrderedDict.
| Python | mit | pfalcon/micropython,kerneltask/micropython,torwag/micropython,selste/micropython,torwag/micropython,TDAbboud/micropython,blazewicz/micropython,bvernoux/micropython,TDAbboud/micropython,lowRISC/micropython,cwyark/micropython,oopy/micropython,infinnovation/micropython,dmazzella/micropython,MrSurly/micropython-esp32,MrSur... | ---
+++
@@ -9,8 +9,19 @@
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
+print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
+print(len(d))
print(list(d.keys()))
print(list(d.values()))
+
+# access remaining elements after deleting
+print(d[10], d[1])
+
+# add an elemen... |
9b02a09be67c8ec3d3b4b652d98f2cd5c3fdc863 | app/timetables/admin.py | app/timetables/admin.py | from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
| from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| Add Timetables Admin model to Django Admin Interface | Add Timetables Admin model to Django Admin Interface
| Python | mit | teamtaverna/core | ---
+++
@@ -1,7 +1,6 @@
from django.contrib import admin
-from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
-
+from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
@@ -9,3 +8,4 @@
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish... |
ff4e769102295280b9e5ad703c5b676f399df894 | test/test_basic.py | test/test_basic.py | import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
| import unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_respon... | Add a basic unit test | Add a basic unit test
| Python | mit | jwergieluk/openfigi,jwergieluk/openfigi | ---
+++
@@ -1,10 +1,19 @@
import unittest
+import openfigi
class MyTestCase(unittest.TestCase):
- def test_something(self):
- self.assertEqual(True, False)
+ def test_wkn_ticker_anonymous(self):
+ """Get an ETF by WKN and check if response makes sense"""
+ ofg = openfigi.OpenFigi()
+ ... |
23e57facea49ebc093d1da7a9ae6857cd2c8dad7 | warehouse/defaults.py | warehouse/defaults.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... | Add an explicit default for REDIS_URI | Add an explicit default for REDIS_URI
| Python | bsd-2-clause | davidfischer/warehouse | ---
+++
@@ -8,6 +8,9 @@
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
+
+# The URI for our Redis database.
+REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem" |
443fe88d5a548033321232b866388ca92f8ef3d7 | server/lib/python/cartodb_services/cartodb_services/refactor/tools/redis_mock.py | server/lib/python/cartodb_services/cartodb_services/refactor/tools/redis_mock.py | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass
| Add newline to end fle | Add newline to end fle | Python | bsd-3-clause | CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api | |
494e7ff2e249a8202c8a71172be7f1870f56f9c3 | mcavatar/views/public/__init__.py | mcavatar/views/public/__init__.py | from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
| from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
| Remove blueprint specific template directories. | Remove blueprint specific template directories.
| Python | mit | joealcorn/MCAvatar | ---
+++
@@ -1,6 +1,6 @@
from flask import Blueprint
-public = Blueprint('public', __name__, template_folder='templates')
+public = Blueprint('public', __name__)
@public.route('/') |
22483d9ca6e393635ffdf371c35026f0e8ec429c | gyp/find.py | gyp/find.py | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ pyt... | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ pyt... | Sort build files for consistent link order. | Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of fi... | Python | bsd-3-clause | rubenvb/skia,ominux/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,vanish87/skia,tmpvar/skia.cc,pcwalton/skia,vanish87/skia,qrealka/skia-hc,ominux/skia,shahrzadmn/skia,google/skia,pcwalton/skia,nvoron23/skia,vanish87/skia,noselhq/skia,tmpvar/skia.cc,van... | ---
+++
@@ -17,6 +17,7 @@
import sys
for d, kids, files in os.walk(sys.argv[1]):
+ files.sort()
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths. |
ddfeb1e9ef60e1913bf702e58cf4696cf7c98c6d | logicmind/token_parser.py | logicmind/token_parser.py | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are nee... | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are nee... | Allow more representations when parsing | [logicmind] Allow more representations when parsing
| Python | mit | LonamiWebs/Py-Utils | ---
+++
@@ -21,29 +21,30 @@
for s in ')]}':
string = string.replace(s, ' ) ')
+ # Get all operators so we can iterate over them
+ operators = [Not, Then, Iff, Or, And]
+
# Get all the tokens
words = string.split()
+ # Store the found nested expressions ... |
a959468bf210869a3d770d58f2ebd3fe70c640ab | imagr_site/urls.py | imagr_site/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^imagr/', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| Change root site to just / not imagr/ | Change root site to just / not imagr/
| Python | mit | markableidinger/django_imagr | ---
+++
@@ -2,7 +2,7 @@
from django.contrib import admin
urlpatterns = patterns('',
- url(r'^imagr/', include('imagr.urls', namespace='imagr')),
+ url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.defau... |
54902242c1e194f36ecc028c0c56c9a99e61eb6a | axes/management/commands/axes_reset.py | axes/management/commands/axes_reset.py | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
... | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
... | Fix bug when using the optional IP parameter | Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'. | Python | mit | django-pci/django-axes,jazzband/django-axes | ---
+++
@@ -13,7 +13,7 @@
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
- for ip in kwargs['ip']:
+ for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset() |
5167ec5f2ba30e649e6fd9b2994995a6022bfda3 | client.py | client.py | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group... | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", his... | Send command in the child process | Send command in the child process
| Python | mit | elimohl/histsync,oxyzero/histsync,eleweek/histsync,elimohl/histsync,elimohl/histsync,oxyzero/histsync,eleweek/histsync,eleweek/histsync,elimohl/histsync,oxyzero/histsync,eleweek/histsync,oxyzero/histsync | ---
+++
@@ -1,12 +1,16 @@
#!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
+import os
+import sys
+
+shell_pid = os.getppid()
+
+if os.fork() != 0:
+ sys.exit()
import requests
-import sys
-import os
import re
-
assert len(sys.argv) == 2
... |
1e1cd9f4b18195f46507b426526a6643a9c24db3 | api/__init__.py | api/__init__.py | from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
... | Add script to populate Base Tags on app startup | Add script to populate Base Tags on app startup
| Python | mit | haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server | ---
+++
@@ -0,0 +1,60 @@
+from api.models import BaseTag
+
+TAGS = {
+ 'fairness': {
+ 'color': '#bcf0ff',
+ 'description': 'Fairness is ideas of justice, rights, and autonomy.',
+ },
+ 'cheating': {
+ 'color': '#feffbc',
+ 'description': 'Cheating is acting dishonestly or unfairly in order to gain an ... | |
ada0aadf9558caba7cb94125f8a8104d2fde968c | tempora/utc.py | tempora/utc.py | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6,... | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtime... | Add test demonstrating aware comparisons | Add test demonstrating aware comparisons
| Python | mit | jaraco/tempora | ---
+++
@@ -11,6 +11,9 @@
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
+True
+
+>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo |
49113dcbcd6cd509b1d69075f78738f4ee9e9bb6 | tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset.py | tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset.py | # Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`. | Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`.
Currently the usage for `RepresentativeDataset` is an iterator instead of a callable.
This fix changes the type signature accordingly.
PiperOrigin-RevId: 457393586
| Python | apache-2.0 | tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimize... | ---
+++
@@ -14,7 +14,7 @@
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
-from typing import Callable, Iterable, Mapping, Tuple, Union
+from typing import Iterable, Mapping, Tuple, Union
from tensorflow... |
03f4ccf4168cdd39d3b8516346a31c4c3ac0ba49 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| Fix bug where n is the square of a prime | Fix bug where n is the square of a prime
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -6,5 +6,5 @@
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
- not_prime.update(range(i*i, n, i))
+ not_prime.update(range(i*i, n+1, i))
return prime |
78ecac7c97445fd24a9d00f5fea671aab99d4c3b | monitor-notifier-slack.py | monitor-notifier-slack.py | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(p... | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(p... | Improve message posted to slack | Improve message posted to slack
| Python | mit | observer-hackaton/monitor-notifier-slack | ---
+++
@@ -16,8 +16,11 @@
def callback(ch, method, properties, body):
payload = {}
- payload["text"] = body
req = json.loads(body)
+ check_type = req["monitor"]["result"]["check"]["type"]
+ host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
+ time = req["monitor"]["res... |
37dc483fd381aa14eddddb13c991bbf647bb747b | data/global-configuration/packs/core-functions/module/node.py | data/global-configuration/packs/core-functions/module/node.py | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... | Declare the is_in_defined_group function, even if it is an alias of the is_in_group | Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group
| Python | mit | naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/kunai,naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/opsbro,naparuba/kunai,naparuba/opsbro | ---
+++
@@ -19,3 +19,20 @@
</code>
"""
return gossiper.is_in_group(group)
+
+
+@export_evaluater_function(function_group=FUNCTION_GROUP)
+def is_in_defined_group(group):
+ """**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery Fal... |
174eb11bf4bdd65e269f0792ddcb1e589bca8b0d | boto3/compat.py | boto3/compat.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | Handle the case where OSError is not because file does not exist | Handle the case where OSError is not because file does not exist
| Python | apache-2.0 | boto/boto3 | ---
+++
@@ -12,14 +12,20 @@
# language governing permissions and limitations under the License.
import sys
import os
+import errno
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
- except OSError:
- p... |
e8c1ba2c63a1ea66aa2c08e606ac0614e6854565 | interrupt.py | interrupt.py | import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
| import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
| Handle sigterm as well as sigint. | Handle sigterm as well as sigint.
| Python | mit | rickbassham/videoencode,rickbassham/videoencode | ---
+++
@@ -10,5 +10,6 @@
e.set()
signal.signal(signal.SIGINT, signal_handler)
+ signal.signal(signal.SIGTERM, signal_handler)
return e |
441cccc340afeb205da75762ce6e145215a858b3 | src/zephyr/delayed_stream.py | src/zephyr/delayed_stream.py |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callb... |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
... | Split delay configuration into default_delay and specific_delays | Split delay configuration into default_delay and specific_delays | Python | bsd-2-clause | jpaalasm/zephyr-bt | ---
+++
@@ -7,11 +7,12 @@
import zephyr
class DelayedRealTimeStream(threading.Thread):
- def __init__(self, signal_collector, callbacks, delay):
+ def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = sig... |
1fc1e160143b5a35741cf3fce9ced827a433d640 | tests/test__pycompat.py | tests/test__pycompat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, ... | Add a test for izip | Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`.
| Python | bsd-3-clause | jakirkham/dask-distance | ---
+++
@@ -13,3 +13,11 @@
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
+
+
+def test_izip():
+ r = dask_distance._pycompat.izip([1, 2, 3], ["a", "b", "c"])
+
+ assert not isinstance(r, list)
+
+ assert list(r) == [(1, 'a'), (2, 'b'), (3, 'c')] |
2f0f560808e07c31ffb88e4b8c9d272536f58e5c | api/commands.py | api/commands.py | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.o... | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.o... | Add command to send messages via GCM | Add command to send messages via GCM
| Python | mit | jchmura/suchary-django,jchmura/suchary-django,jchmura/suchary-django | ---
+++
@@ -41,3 +41,12 @@
'key': key
}
send(data)
+
+
+def send_message(title, body):
+ data = {
+ 'type': 'message',
+ 'title': title,
+ 'text': body
+ }
+ send(data) |
343e3bd0e16df1106d82fa6087a7247dc67bb52b | oslo_concurrency/_i18n.py | oslo_concurrency/_i18n.py | # Copyright 2014 Mirantis Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | # Copyright 2014 Mirantis Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | Drop use of namespaced oslo.i18n | Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0
| Python | apache-2.0 | JioCloud/oslo.concurrency,openstack/oslo.concurrency,varunarya10/oslo.concurrency | ---
+++
@@ -14,9 +14,9 @@
# License for the specific language governing permissions and limitations
# under the License.
-from oslo import i18n
+import oslo_i18n
-_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
+_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# Th... |
05c6920ff6f2d9b617346d4cca59622fb14a8f2e | picoCTF-web/api/tests/conftest.py | picoCTF-web/api/tests/conftest.py | """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb inst... | """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb inst... | Clear db if not empty | Clear db if not empty
| Python | mit | picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF | ---
+++
@@ -17,7 +17,8 @@
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
- assert len(client.collection_names()) == 0, "Mongo db: {} is not empty.".format(mongo_db_name)
+ if len(client.collection_names()) != 0:
+ client.connection.drop_database(mongo_db_name)
#Set debug clie... |
d14c0aeba5304ba66649c9d6a0a9d144a9ef1e43 | api/teams/admin.py | api/teams/admin.py | from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'... | from django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
... | Allow team num players column to be ordered | Allow team num players column to be ordered
| Python | mit | prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes | ---
+++
@@ -1,4 +1,5 @@
from django.contrib import admin
+from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
@@ -18,11 +19,14 @@
def get_queryset(self, request):
queryset = super().get_queryset(request)
- return queryset.prefetch_related(... |
a69bd95c2e732f22aac555884904bbe7d9d0a1b9 | src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py | src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFix... | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument... | Fix Command compatibility with Django>= 1.8 | Fix Command compatibility with Django>= 1.8
| Python | mit | Peter-Slump/django-factory-boy-fixtures,Peter-Slump/django-dynamic-fixtures | ---
+++
@@ -8,9 +8,20 @@
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
+ def add_arguments(self, parser):
+ parser.add_argument('app_label', type=str)
+ parser.add_argument('fixture_name', default=None, nargs='?', type=str)
+
def ... |
30ebc069634673c6a3b52c7f4285c2ce3c88472a | app/users/models.py | app/users/models.py | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = d... | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password ... | Rename User model to AppUser | Rename User model to AppUser
| Python | mit | projectweekend/Flask-PostgreSQL-API-Seed | ---
+++
@@ -8,7 +8,7 @@
return datetime.now() + timedelta(days=1)
-class User(db.Model):
+class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
@@ -32,13 +32,13 @@
class PasswordReset(db.Model):
id = db.Column(db.Integer(), ... |
2ec685b6d7469fb69e34702caa706e20f7c7e75c | jinja2_templating_for_squirrel/__init__.py | jinja2_templating_for_squirrel/__init__.py | import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(pat... | import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
args = helpers.get_args()
if args.action != "generate":
return context
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
... | Fix that Jinja2 templating is initiated when not needed | Fix that Jinja2 templating is initiated when not needed
| Python | mit | daGrevis/squirrel | ---
+++
@@ -7,11 +7,15 @@
logger = helpers.get_logger(__name__)
-
conf = helpers.get_conf()
def jinja2_templating(context):
+ args = helpers.get_args()
+
+ if args.action != "generate":
+ return context
+
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_en... |
c6229fc20f8bb37d185f90b032c0dc3817834256 | linguist/mixins.py | linguist/mixins.py | # -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value... | # -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
... | Add identifier property to mixin. | Add identifier property to mixin.
| Python | mit | ulule/django-linguist | ---
+++
@@ -1,12 +1,16 @@
# -*- coding: utf-8 -*-
from .models import Translation
-from .utils import get_cache_key
+from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
+
+ @property
+ def identifier(self):
+ ... |
8b5cfb11235d419d729a69a638a39489322fe547 | api/provider.py | api/provider.py | """
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""... | """
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProv... | Fix problem where Provider DoesNotExist. | Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | ---
+++
@@ -2,14 +2,16 @@
atmosphere service provider rest api.
"""
-
+from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
+from core.models... |
a512af54d5c843aa8f232a73dcfe79870341a8db | ppadb/command/transport_async/__init__.py | ppadb/command/transport_async/__init__.py | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=t... | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=t... | Check the length of the screencap before indexing into it | Check the length of the screencap before indexing into it
| Python | mit | Swind/pure-python-adb,Swind/pure-python-adb | ---
+++
@@ -34,7 +34,7 @@
await conn.send(cmd)
result = await conn.read_all()
- if result[5] == 0x0d:
+ if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result |
92a5d02b3e052fb0536e51aba043ff2f026c6484 | appengine_config.py | appengine_config.py | import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_develo... | import logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_sho... | Disable GAE mini profiler by default | Disable GAE mini profiler by default
| Python | mit | bbondy/brianbondy.gae,bbondy/brianbondy.gae,bbondy/brianbondy.gae,bbondy/brianbondy.gae | ---
+++
@@ -1,9 +1,10 @@
import logging
def appstats_should_record(env):
- from gae_mini_profiler.config import should_profile
- if should_profile():
- return True
+ #from gae_mini_profiler.config import should_profile
+ #if should_profile():
+ # return True
+ return False
def gae_mini_profiler_s... |
3e42ee0d9bd712b0e757af66279eaff838b0f004 | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| Replace string "view" argument to url() function with callable. | Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider | ---
+++
@@ -1,9 +1,11 @@
from django.conf.urls import url
+from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
+
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
- url('^accounts/login/$', 'django.contrib.auth.views.login'),
+ url('^... |
e3e2b9b632a765927250782bab574767464b93b5 | software/clients/python_client/src/load_test.py | software/clients/python_client/src/load_test.py | import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(bu... | import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(bu... | Change output format of python load tester. | Change output format of python load tester.
| Python | mit | chadharrington/all_spark_cube,chadharrington/all_spark_cube,chadharrington/all_spark_cube,chadharrington/all_spark_cube | ---
+++
@@ -16,7 +16,7 @@
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
- print '%d frames in %.2f secs. %.2f fps.' % (
+ print '"%d frames in %.2f secs. (%.2f fps)' % (
reps, duration, reps / float(duration))
|
d70f19106a7dc63182a3a0ea4fe6702eedc23322 | mlog/db.py | mlog/db.py | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TE... | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TE... | Add index to the message_id column | Add index to the message_id column
| Python | agpl-3.0 | fajran/mlog | ---
+++
@@ -20,3 +20,8 @@
`references` TEXT
)''')
+ c.execute(
+ '''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
+ ON email_log (message_id)
+ ''')
+ |
81cf2085bb43742b722e833f8cec6e65e2906ec0 | pyes/tests/errors.py | pyes/tests/errors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(Error... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(Error... | Test that various exceptions are correctly converted | Test that various exceptions are correctly converted
| Python | bsd-3-clause | jayzeng/pyes,Fiedzia/pyes,HackLinux/pyes,mavarick/pyes,haiwen/pyes,aparo/pyes,haiwen/pyes,aparo/pyes,aparo/pyes,jayzeng/pyes,Fiedzia/pyes,mavarick/pyes,mavarick/pyes,HackLinux/pyes,mouadino/pyes,rookdev/pyes,haiwen/pyes,rookdev/pyes,mouadino/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes | ---
+++
@@ -12,19 +12,44 @@
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
- """
-
- Test errors thrown when creating or deleting.
+ """Test errors thrown when creating or deleting indexes.
"""
try:
self.conn.delete_index("... |
4604cf73a45e8bcecf38238366cfdac37cdb7897 | pyfr/readers/base.py | pyfr/readers/base.py | # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _op... | # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
... | Fix a bug in the mesh optimizer. | Fix a bug in the mesh optimizer.
| Python | bsd-3-clause | iyer-arvind/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,tjcorona/PyFR | ---
+++
@@ -2,7 +2,6 @@
import re
import uuid
-import itertools as it
from abc import ABCMeta, abstractmethod
@@ -22,7 +21,7 @@
def _optimize(self, mesh):
# Sort interior interfaces
- for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
+ for f in filter(lambda f: re.ma... |
3a7428723c66010dec1d246beb63be371428d3fe | qipipe/staging/staging_helpers.py | qipipe/staging/staging_helpers.py | """Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@retu... | """Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@... | Raise error if no match. | Raise error if no match.
| Python | bsd-2-clause | ohsu-qin/qipipe | ---
+++
@@ -1,11 +1,12 @@
"""Pipeline utility functions."""
import re
+from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
-def match_session_hierarchy(path):
+def match_series_hierarchy(path):
"""
Matches ... |
6dfcee473ef860fe9abb4971baabf62f9f51e314 | inpassing/util.py | inpassing/util.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
... | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
... | Add daystate_dict function to serialize daystates to dictionaries | Add daystate_dict function to serialize daystates to dictionaries
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend | ---
+++
@@ -36,3 +36,11 @@
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
+
+def daystate_dict(daystate):
+ return {
+ 'id': daystate.id,
+ 'org_id': daystate.org_id,
+ 'identifier': daystate.identifer,
+ 'greetin... |
3c90d8a317e3d5b001a9aa141cc86826bdefb3fa | autoscaler/tasks.py | autoscaler/tasks.py | import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/15'))... | import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/5')),... | Make autoscaler run every 5 minutes. | Make autoscaler run every 5 minutes.
| Python | apache-2.0 | ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server | ---
+++
@@ -11,7 +11,7 @@
app = Celery()
-@periodic_task(run_every=(crontab(minute='*/15')), options={"expires": 120})
+@periodic_task(run_every=(crontab(minute='*/5')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler() |
71df45002746b162e04a125403cad390accb949e | backend/main.py | backend/main.py | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()... | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()... | Add proper authentication for db (without actual key). | Add proper authentication for db (without actual key).
| Python | apache-2.0 | google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz | ---
+++
@@ -12,8 +12,13 @@
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
+# Fill out with value from https://firebase.corp.google.com/project/trogdors-29fa4/settings/database
+FIREBASE_SECRET = ""
+FIREBASE_EMAIL = ""
+
app = Flask(__name__)
-firebase ... |
0aa6a648fff39b013f9b644d9a894db39706df43 | amplpy/amplpython/__init__.py | amplpy/amplpython/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeo... | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
... | Fix 'ModuleNotFoundError: No module named amplpython' | Fix 'ModuleNotFoundError: No module named amplpython'
| Python | bsd-3-clause | ampl/amplpy,ampl/amplpy,ampl/amplpy | ---
+++
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
-
import os
+import sys
import ctypes
import platform
@@ -18,5 +17,6 @@
except:
pass
-from .amplpython import *
-from .amplpython import _READTABLE, _WRITETABLE
+sys.path.append(os.path.dirname(__file__))
+fr... |
895ca15591938f07f1e913b08726f991c2d9e964 | libs/googleapis.py | libs/googleapis.py | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | Fix url shortening for small domains | Fix url shortening for small domains
| Python | mit | sevazhidkov/leonard | ---
+++
@@ -19,4 +19,6 @@
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
- return response['id']
+ if 'id' in response:
+ return response['id']
+ return url |
c9dfb5b59d5f51200df938f3da176a577842a390 | openquake/engine/tests/export/core_test.py | openquake/engine/tests/export/core_test.py |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake is distr... |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake is distr... | Fix a broken export test | Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 1... | Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine | ---
+++
@@ -26,7 +26,7 @@
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
- return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
+ return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.Tes... |
7b50adc607f0e0e970c6f5793eadd9fb42027d0a | Tools/scripts/setup.py | Tools/scripts/setup.py | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
... | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
... | Install pygettext (once the scriptsinstall target is working again). | Install pygettext (once the scriptsinstall target is working again).
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -11,6 +11,7 @@
'ftpmirror.py',
'h2py.py',
'lfcr.py',
+ '../i18n/pygettext.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py', |
e43c1335bb48e8ba3321ddd9471ac04fd75a4250 | broker/ivorn_db.py | broker/ivorn_db.py | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root)... | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lo... | Use a separate lock per ivorn database | Use a separate lock per ivorn database
| Python | bsd-2-clause | jdswinbank/Comet,jdswinbank/Comet | ---
+++
@@ -5,20 +5,19 @@
import os
import anydbm
import datetime
-from contextlib import closing
from threading import Lock
+from collections import defaultdict
class IVORN_DB(object):
- # Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
... |
cb71bc8767fbc07a27df4049b95c7dacf5975c9d | pinax/app_name/tests/urls.py | pinax/app_name/tests/urls.py | try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
| from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
| Fix django 1.9 warning and drop support django < 1.7 | Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of dja... | Python | mit | pinax/pinax-starter-app | ---
+++
@@ -1,10 +1,6 @@
-try:
- from django.conf.urls import patterns, include
-except ImportError:
- from django.conf.urls.defaults import patterns, include
+from django.conf.urls import include
-urlpatterns = patterns(
- "",
+urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
-)
+] |
09ae343b2abe0a0a325437396c995abe5aa560b4 | shuup/api/mixins.py | shuup/api/mixins.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_fra... | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_fra... | Add Searchable Mixin for API | Add Searchable Mixin for API
| Python | agpl-3.0 | shoopio/shoop,shoopio/shoop,shoopio/shoop | ---
+++
@@ -7,6 +7,7 @@
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
+from rest_framework.filters import SearchFilter
from rest_framework.response import Response
@@ -31,3 +32,11 @@
ref_obj = exc.p... |
d6fc8cc0e0d50b23ba0d7ca6195bc530b2f8d1b9 | shapely/tests/test_unary_union.py | shapely/tests/test_unary_union.py | from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result ... | from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result ... | Fix halton sequence generator for Python 3 | Fix halton sequence generator for Python 3
| Python | bsd-3-clause | abali96/Shapely,jdmcbr/Shapely,jdmcbr/Shapely,abali96/Shapely,mouadino/Shapely,mouadino/Shapely,mindw/shapely,mindw/shapely | ---
+++
@@ -11,7 +11,7 @@
i = index
while i > 0:
result += f * (i % base)
- i = i/base
+ i = i//base
f = f/base
return result
i = 1 |
28bacd5c3318aff52c0758ad97909ff08c7bfffb | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Add spaces to increase readability. | Add spaces to increase readability.
"OSF-4419"
| Python | apache-2.0 | asanfilippo7/osf.io,saradbowman/osf.io,acshi/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,mattclark/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,abought/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,pattisdr/osf.io,njantrania/osf.io,samchrisinger/osf.io,jnayak1/osf.io,cwisecarver/o... | ---
+++
@@ -16,6 +16,7 @@
if response:
message = response.data
+
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
@@ -26,9 +27,11 @@
errors.append({'source': {'pointer': '/data/attri... |
511aab30006a5fb4c7ff52bc2cd1a1e42551fad1 | bmi_ilamb/config.py | bmi_ilamb/config.py | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(file... | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(s... | Allow confrontations to be passed to ilamb-run | Allow confrontations to be passed to ilamb-run
| Python | mit | permamodel/bmi-ilamb | ---
+++
@@ -7,6 +7,7 @@
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
+confrontations_key = 'confrontations'
class Configuration(object):
@@ -31,10 +32,16 @@
if models is not None:
self._config[models_key] = ' '.join(models)
+ def _deserialize_con... |
f40dd24af6788e7de7d06254850b83edb179b423 | bootcamp/lesson4.py | bootcamp/lesson4.py | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module retu... | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def pl... | Revert "Added solutions for lesson 4" | Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.
| Python | mit | infoscout/python-bootcamp-pv | ---
+++
@@ -8,14 +8,16 @@
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
- return datetime.datetime(2015, 06, 01)
+ # Write code here
+ pass
# Question 2
# ----------
# Using the math module return ... |
2de0f6d241ccf40f6dd7298db46320c09e7b6967 | bot/project_info.py | bot/project_info.py | # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPL 3.0'
license_ur... | # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPLv3.0+'
license_u... | Update license_name to point to AGPLv3+ | Update license_name to point to AGPLv3+
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -10,5 +10,5 @@
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
-license_name = 'GNU AGPL 3.0'
+license_name = 'GNU AGPLv3.0+'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html' |
805f77ac20952c6015a26403041b9b7b3a543ab4 | danceschool/core/migrations/0041_invoiceitem_calculate_taxrate.py | danceschool/core/migrations/0041_invoiceitem_calculate_taxrate.py | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nulla... | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nulla... | Fix division by zero error when calculating tax rate on migration. | Fix division by zero error when calculating tax rate on migration.
| Python | bsd-3-clause | django-danceschool/django-danceschool,django-danceschool/django-danceschool,django-danceschool/django-danceschool | ---
+++
@@ -12,8 +12,10 @@
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
+ to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
+ to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = Invoic... |
e1d61d945300dde9cb5ac07228b7892b224a984c | tests/commands/load/test_load_cnv_report_cmd.py | tests/commands/load/test_load_cnv_report_cmd.py | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | Fix code style issues with Black | Fix code style issues with Black
| Python | bsd-3-clause | Clinical-Genomics/scout,Clinical-Genomics/scout,Clinical-Genomics/scout | ---
+++
@@ -15,7 +15,10 @@
assert runner
# Test CLI function
- result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
+ result = runner.invoke(
+ cli,
+ ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
+ )
assert "saved rep... |
e9df4858631d9efdcb6a5b960c25f64cae875661 | blog/models.py | blog/models.py | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField... | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL conf... | Add options to Post model fields. | Ch03: Add options to Post model fields. [skip ci]
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -9,8 +9,15 @@
class Post(models.Model):
title = models.CharField(max_length=63)
- slug = models.SlugField()
+ slug = models.SlugField(
+ max_length=63,
+ help_text='A label for URL config',
+ unique_for_month='pub_date')
text = models.TextField()
- pub_date = mode... |
d45391429f01d5d4ea22e28bef39a2bb419df04f | djangae/apps.py | djangae/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_c... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_c... | Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes | Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes
| Python | bsd-3-clause | potatolondon/djangae,grzes/djangae,kirberich/djangae,kirberich/djangae,kirberich/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae | ---
+++
@@ -15,10 +15,18 @@
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
- if 'django.contrib.contenttypes' in settings.INSTALLED_APPS and (
- not 'djangae.contrib.contenttypes' in settings.INSTALLED_APP... |
762d87014d87d986aa83703f216e5cd2b52ce2f3 | brink/utils.py | brink/utils.py | import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = ... | import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = ... | Make get_app_models only import models from the specified module, and not imported ones | Make get_app_models only import models from the specified module, and not imported ones
| Python | bsd-3-clause | brinkframework/brink | ---
+++
@@ -20,6 +20,9 @@
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
- module = importlib.import_module("%s.models" % app)
+ module_name = "%s.models" % app
+ module = importlib.import_module(module_name)
return [model for _, model in module... |
f213984ad3dfd8922578346baeeb97d60fab742a | cinje/inline/use.py | cinje/inline/use.py | # encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" inst... | # encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" ... | Handle buffering and Python 3 "yield from" optimization. | Handle buffering and Python 3 "yield from" optimization.
| Python | mit | marrow/cinje | ---
+++
@@ -1,6 +1,6 @@
# encoding: utf-8
-from ..util import pypy, ensure_buffer
+from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
@@ -36,6 +36,17 @@
for i in ensure_buffer(context):
yield i
- yield declaration.clone(line=PREFIX + name.rstrip() + "(" + ar... |
45086d11fcdc071427e8c5a2ac909dceac2b43ec | tests/test_auditory.py | tests/test_auditory.py | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | Add test, which fails, of the gammatone filtering. | Add test, which fails, of the gammatone filtering.
| Python | bsd-3-clause | achabotl/pambox | ---
+++
@@ -18,3 +18,17 @@
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
+
+
+# We use a different implementation than the Matlab one and the delay
+# are different.
+@pytest.mark.xfail
+def test_gammatone_filtering():
+ mat = sio.loadmat('./test_files/test_gammatone_filter... |
08e2099f173bce115ba93c2b960bb1f09ef11269 | models.py | models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try... | Fix critical stupid copypaste error | Fix critical stupid copypaste error
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel,kirelagin/django-orderedmodel | ---
+++
@@ -12,7 +12,7 @@
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
- self.order = self.max_order + 1
+ self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
@@ -29... |
a58a1f511e0dfb54ca5168180e9f191340f7afde | osgtest/tests/test_11_condor_cron.py | osgtest/tests/test_11_condor_cron.py | import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.ru... | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state... | Update 11_condor_cron to use OkSkip functionality | Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test | ---
+++
@@ -1,20 +1,18 @@
import os
-import osgtest.library.core as core
+from osgtest.library import core, osgunittest
import unittest
-class TestStartCondorCron(unittest.TestCase):
+class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.