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 |
|---|---|---|---|---|---|---|---|---|---|---|
f2bf249f4ea954b318819bd5976584eedba35517 | pytablereader/__init__.py | pytablereader/__init__.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from tabledata import DataError, InvalidHeaderNameError, InvalidTableNameError
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._constant impo... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from tabledata import DataError, InvalidHeaderNameError, InvalidTableNameError
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._constant impo... | Hide logger from outside of the package | Hide logger from outside of the package
| Python | mit | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader | ---
+++
@@ -10,7 +10,7 @@
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._constant import PatternMatch
-from ._logger import logger, set_log_level, set_logger
+from ._logger import set_log_level, set_logger
from .csv.core import CsvTableFileLoader, CsvTableTextLoade... |
57f3bec127148c80a9304194e5c3c8a3d3f3bae2 | tests/scoring_engine/web/views/test_scoreboard.py | tests/scoring_engine/web/views/test_scoreboard.py | from tests.scoring_engine.web.web_test import WebTest
class TestScoreboard(WebTest):
def test_home(self):
# todo fix this up!!!!
# resp = self.client.get('/scoreboard')
# assert resp.status_code == 200
# lazy AF
assert 1 == 1
| from tests.scoring_engine.web.web_test import WebTest
from tests.scoring_engine.helpers import populate_sample_data
class TestScoreboard(WebTest):
def test_scoreboard(self):
populate_sample_data(self.session)
resp = self.client.get('/scoreboard')
assert resp.status_code == 200
ass... | Add tests for scoreboard view | Add tests for scoreboard view
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | ---
+++
@@ -1,11 +1,18 @@
from tests.scoring_engine.web.web_test import WebTest
+from tests.scoring_engine.helpers import populate_sample_data
class TestScoreboard(WebTest):
- def test_home(self):
- # todo fix this up!!!!
- # resp = self.client.get('/scoreboard')
- # assert resp.status... |
ebac72a3753205d3e45041c6db636a378187e3cf | pylua/tests/test_compiled.py | pylua/tests/test_compiled.py | import os
import subprocess
from pylua.tests.helpers import test_file
class TestCompiled(object):
"""
Tests compiled binary
"""
def test_addition(self, capsys):
f = test_file(src="""
-- short add
x = 10
y = 5
z = y + y + x
print(z)
... | import os
import subprocess
from pylua.tests.helpers import test_file
class TestCompiled(object):
"""
Tests compiled binary
"""
PYLUA_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), ('../../bin/pylua'))
def test_addition(self, capsys):
f = test_file(src="""
--... | Use absolute path for lua binary in tests | Use absolute path for lua binary in tests
| Python | bsd-3-clause | fhahn/luna,fhahn/luna | ---
+++
@@ -8,6 +8,8 @@
"""
Tests compiled binary
"""
+
+ PYLUA_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), ('../../bin/pylua'))
def test_addition(self, capsys):
f = test_file(src="""
@@ -25,5 +27,5 @@
--print(lx+1234567890)
""", suffix=".... |
5577b2a20a98aa232f5591a46269e5ee6c88070d | MyMoment.py | MyMoment.py | import datetime
#Humanize time in milliseconds
#Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time
def HTM(aa):
a = int(aa)
b = int(datetime.datetime.now().strftime("%s"))
c = b - a
days = c // 86400
hours = c // 3600 % 24
minu... | import datetime
from time import gmtime, strftime
import pytz
#Humanize time in milliseconds
#Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time
#http://www.epochconverter.com/
#1/6/2015, 8:19:34 AM PST -> 23 hours ago
#print HTM(1420561174000/1000)
... | Add functions to generate timestamp for logfiles & filenames; use localtimezone | Add functions to generate timestamp for logfiles & filenames; use localtimezone
| Python | mit | harishvc/githubanalytics,harishvc/githubanalytics,harishvc/githubanalytics | ---
+++
@@ -1,7 +1,13 @@
import datetime
+from time import gmtime, strftime
+import pytz
#Humanize time in milliseconds
#Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time
+#http://www.epochconverter.com/
+#1/6/2015, 8:19:34 AM PST -> 23 hours ... |
5cf17b6a46a3d4bbf4cecb65e4b9ef43066869d9 | feincms/templatetags/applicationcontent_tags.py | feincms/templatetags/applicationcontent_tags.py | from django import template
# backwards compatibility import
from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment
register = template.Library()
register.tag(fragment)
register.tag(get_fragment)
register.filter(has_fragment)
@register.simple_tag
def feincms_render_region_appcontent(pa... | from django import template
# backwards compatibility import
from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment
register = template.Library()
register.tag(fragment)
register.tag(get_fragment)
register.filter(has_fragment)
@register.simple_tag
def feincms_render_region_appcontent(pa... | Use all_of_type instead of isinstance check in feincms_render_region_appcontent | Use all_of_type instead of isinstance check in feincms_render_region_appcontent
| Python | bsd-3-clause | feincms/feincms,joshuajonah/feincms,feincms/feincms,matthiask/feincms2-content,matthiask/django-content-editor,michaelkuty/feincms,mjl/feincms,matthiask/feincms2-content,mjl/feincms,matthiask/django-content-editor,matthiask/django-content-editor,michaelkuty/feincms,nickburlett/feincms,matthiask/django-content-editor,jo... | ---
+++
@@ -28,4 +28,4 @@
from feincms.templatetags.feincms_tags import _render_content
return u''.join(_render_content(content, request=request) for content in\
- getattr(page.content, region) if isinstance(content, ApplicationContent))
+ page.content.all_of_type(ApplicationContent) if cont... |
b457eac63690deba408c4b5bdc1db179347f43da | postgres/fields/uuid_field.py | postgres/fields/uuid_field.py | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(mode... | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(mode... | Make UUIDField have a fixed max-length | Make UUIDField have a fixed max-length
| Python | bsd-3-clause | wlanslovenija/django-postgres | ---
+++
@@ -25,6 +25,10 @@
'invalid': _("'%(value)s' is not a valid UUID."),
}
+ def __init__(self, **kwargs):
+ kwargs['max_length'] = 36
+ super(UUIDField, self).__init__(**kwargs)
+
def get_internal_type(self):
return 'UUIDField'
@@ -32,6 +36,9 @@
return 'u... |
89fe38163426efe02da92974bac369538ab5532f | elmextensions/__init__.py | elmextensions/__init__.py | from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
| from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .fontselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
__copyright__ = "Copyright 2015-2017 Jeff Hoogland"
__license__... | Access to module level information | Access to module level information | Python | bsd-3-clause | JeffHoogland/python-elm-extensions | ---
+++
@@ -2,7 +2,15 @@
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
+from .fontselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
+
+__copyright__ = "Copyright 2015-2017 Jeff Hoogland"
... |
f517442097b6ae12eb13b16f2fa6ca40a00b9998 | __init__.py | __init__.py | from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
| from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
from .features import Feature_Type_Choices
| Move Feature_Type_Choices to toplevel name sapce | Move Feature_Type_Choices to toplevel name sapce
| Python | mit | benjiec/giraffe-features | ---
+++
@@ -1,2 +1,3 @@
from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
+from .features import Feature_Type_Choices |
0830f131b50d9679e6b2097febc7913bc09e5132 | mopidy_scrobbler/__init__.py | mopidy_scrobbler/__init__.py | import pathlib
from mopidy import config, ext
__version__ = "1.2.1"
class Extension(ext.Extension):
dist_name = "Mopidy-Scrobbler"
ext_name = "scrobbler"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_s... | import pathlib
import pkg_resources
from mopidy import config, ext
__version__ = pkg_resources.get_distribution("Mopidy-Scrobbler").version
class Extension(ext.Extension):
dist_name = "Mopidy-Scrobbler"
ext_name = "scrobbler"
version = __version__
def get_default_config(self):
return conf... | Use pkg_resources to read version | Use pkg_resources to read version
| Python | apache-2.0 | mopidy/mopidy-scrobbler | ---
+++
@@ -1,8 +1,10 @@
import pathlib
+
+import pkg_resources
from mopidy import config, ext
-__version__ = "1.2.1"
+__version__ = pkg_resources.get_distribution("Mopidy-Scrobbler").version
class Extension(ext.Extension): |
48ffd37eb826edb78750652628145a924053b204 | website/wsgi.py | website/wsgi.py | """
WSGI config for classicalguitar project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "classicalguitar.settings")
fr... | """
WSGI config for website project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")
from django.core.w... | Correct some remaining classical guitar refs | Correct some remaining classical guitar refs
| Python | bsd-3-clause | chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org | ---
+++
@@ -1,5 +1,5 @@
"""
-WSGI config for classicalguitar project.
+WSGI config for website project.
It exposes the WSGI callable as a module-level variable named ``application``.
@@ -8,7 +8,7 @@
"""
import os
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "classicalguitar.settings")
+os.environ.setdef... |
5a8788222d9a5765bf66a2c93eed25ca7879c856 | __init__.py | __init__.py | import inspect
import sys
if sys.version_info[0] == 2:
from .python2 import httplib2
else:
from .python3 import httplib2
globals().update(inspect.getmembers(httplib2))
| import os
import sys
path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0])
sys.path.insert(0, path)
del sys.modules['httplib2']
import httplib2
| Rewrite python version dependent import | Rewrite python version dependent import
The top level of this external includes a __init__.py so that
it may be imported with only 'externals' in sys.path.
However it copies the contents of the python version dependent httplib2
code, resulting in module level variables appearing in two different
namespaces. As a res... | Python | mit | jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2,jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2 | ---
+++
@@ -1,7 +1,7 @@
-import inspect
+import os
import sys
-if sys.version_info[0] == 2:
- from .python2 import httplib2
-else:
- from .python3 import httplib2
-globals().update(inspect.getmembers(httplib2))
+
+path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0])
+sys.path.insert(0... |
2b2e0b180393af779c7d303a1a3162febe098639 | permuta/misc/union_find.py | permuta/misc/union_find.py |
class UnionFind(object):
def __init__(self, n):
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
if self.p[x] < 0:
return x
self.p[x] = self.find(self.p[x])
return self.p[x]
def size(self, x):
return -self.p[self.find... |
class UnionFind(object):
"""A collection of distjoint sets."""
def __init__(self, n = 0):
"""Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
"""Return the identifier of a representative element f... | Document UnionFind and implement add function | Document UnionFind and implement add function
| Python | bsd-3-clause | PermutaTriangle/Permuta | ---
+++
@@ -1,19 +1,28 @@
class UnionFind(object):
- def __init__(self, n):
+ """A collection of distjoint sets."""
+
+ def __init__(self, n = 0):
+ """Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, ... |
40e96e99dc8538ae3b5e5a95d9c6d81ec656ad6c | dash2012/auth/views.py | dash2012/auth/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(... | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(... | Fix erros msg in login view | Fix erros msg in login view
| Python | bsd-3-clause | losmiserables/djangodash2012,losmiserables/djangodash2012 | ---
+++
@@ -18,9 +18,17 @@
if not Cloud.objects.filter(account=user).exists():
return HttpResponseRedirect(reverse('connect-view'))
+ # If we have at least one cloud, put its data in the user session.
+ r.session['clouds'] = {}
+
+ connected_clouds = Cl... |
01c5b53ba16a95ab77918d30dfa3a63f2ef2707f | var/spack/repos/builtin/packages/libxcb/package.py | var/spack/repos/builtin/packages/libxcb/package.py | from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "... | from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "htt... | Make libxcb compile with gcc 4.9. | Make libxcb compile with gcc 4.9.
| Python | lgpl-2.1 | krafczyk/spack,krafczyk/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,iulian787/spack,EmreAtes/spack,lgarren/spack,EmreAtes/spack,matthiasdiener/spack,lgarren/spack,TheTimmy/spack,LLNL/spack,mfherbst/spack,lgarren/spack,iulian787/spack,skosukhin/spack,LLNL/spack,LLNL/spack,mfherbst/spack,skosukhin/spack,matthias... | ---
+++
@@ -1,9 +1,9 @@
from spack import *
class Libxcb(Package):
- """The X protocol C-language Binding (XCB) is a replacement
- for Xlib featuring a small footprint, latency hiding, direct
- access to the protocol, improved threading support, and
+ """The X protocol C-language Binding (XCB) is a... |
79e68ca4b377f479d7eb557879b3450134efaf16 | ydf/yaml_ext.py | ydf/yaml_ext.py | """
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
__all__ = ['load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round trip YAML ... | """
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
__all__ = ['load', 'load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round tr... | Add YAML load for single document. | Add YAML load for single document.
| Python | apache-2.0 | ahawker/ydf | ---
+++
@@ -11,7 +11,7 @@
from ruamel.yaml import resolver
-__all__ = ['load_all', 'load_all_gen']
+__all__ = ['load', 'load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
@@ -28,6 +28,16 @@
def construct_ordered_mapping(loader, node):
loader.flatten_mapping(node)
... |
42f5b2c53474f20fbffbc0b8cdaa4e5b47a4751d | app/wsgi.py | app/wsgi.py | # TODO, figure out how to load gevent monkey patch cleanly in production
try:
from gevent.monkey import patch_all
patch_all()
except ImportError:
print "unable to apply gevent monkey.patch_all"
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.environ.get('S... | # TODO, figure out how to load gevent monkey patch cleanly in production
# try:
# from gevent.monkey import patch_all
# patch_all()
# except ImportError:
# print "unable to apply gevent monkey.patch_all"
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.envi... | Comment out gevent until we need it | Comment out gevent until we need it
| Python | mit | spacedogXYZ/email-validator,spacedogXYZ/email-validator,spacedogXYZ/email-validator | ---
+++
@@ -1,9 +1,9 @@
# TODO, figure out how to load gevent monkey patch cleanly in production
-try:
- from gevent.monkey import patch_all
- patch_all()
-except ImportError:
- print "unable to apply gevent monkey.patch_all"
+# try:
+# from gevent.monkey import patch_all
+# patch_all()
+# except Im... |
785236ca766d832d859c2933389e23fd3d1bea20 | djangocms_table/cms_plugins.py | djangocms_table/cms_plugins.py | from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from django.utils import simplejson
from djangocms_table.utils import static_url... | import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from djangocms_table.utils import static_url
from django.http import... | Fix another simplejson deprecation warning | Fix another simplejson deprecation warning
| Python | bsd-3-clause | freelancersunion/djangocms-table,freelancersunion/djangocms-table,freelancersunion/djangocms-table,divio/djangocms-table,divio/djangocms-table,divio/djangocms-table | ---
+++
@@ -1,10 +1,10 @@
+import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
-from django.utils import simplej... |
17d54738a57a355fef3e83484162af13ecd2ea63 | localore/localore_admin/migrations/0003_auto_20160316_1646.py | localore/localore_admin/migrations/0003_auto_20160316_1646.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('localore_admin', '0002_auto_20160316_1444'),
]
run_before = [
('home', '0002_create_homepage'),
]
operations = [
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('localore_admin', '0002_auto_20160316_1444'),
]
run_before = [
('home', '0002_create_homepage'),
('people', '0006_aut... | Fix (?) another custom image model migration error | Fix (?) another custom image model migration error
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore | ---
+++
@@ -12,6 +12,7 @@
run_before = [
('home', '0002_create_homepage'),
+ ('people', '0006_auto_20160318_1718'),
]
operations = [ |
6b3f568a6615e9439fc0df0eac68838b6cbda0d9 | anti-XSS.py | anti-XSS.py | #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
... | #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report im... | Add initialization before get url | Add initialization before get url
| Python | mit | lewangbtcc/anti-XSS,lewangbtcc/anti-XSS | ---
+++
@@ -5,6 +5,8 @@
'''
import sys
+
+from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
@@ -20,7 +22,8 @@
(options, args) = parser.parse_args()
if options.startUrl:
- rootLink = Link(options.startUrl, options.startUrl)
+ url = initiali... |
19d99f6040d1474feee0f2fb0bda7cb14fbf407c | nose2/tests/unit/test_config.py | nose2/tests/unit/test_config.py | from nose2 import config
from nose2.compat import unittest
class TestConfigSession(unittest.TestCase):
def test_can_create_session(self):
config.Session()
class TestConfig(unittest.TestCase):
def setUp(self):
self.conf = config.Config([
('a', ' 1 '), ('b', ' x\n y '), ('c',... | from nose2 import config
from nose2.compat import unittest
class TestConfigSession(unittest.TestCase):
def test_can_create_session(self):
config.Session()
def test_load_plugins_from_module_can_load_plugins(self):
class fakemod:
pass
f = fakemod()
class A(events.Plu... | Add test for as_list bugfix | Add test for as_list bugfix
| Python | bsd-2-clause | ojengwa/nose2,little-dude/nose2,leth/nose2,leth/nose2,ptthiem/nose2,ptthiem/nose2,ezigman/nose2,ojengwa/nose2,ezigman/nose2,little-dude/nose2 | ---
+++
@@ -6,11 +6,25 @@
def test_can_create_session(self):
config.Session()
+ def test_load_plugins_from_module_can_load_plugins(self):
+ class fakemod:
+ pass
+ f = fakemod()
+ class A(events.Plugin):
+ pass
+ f.A = A
+ session = config.Se... |
a3df62c7da4aa29ab9977a0307e0634fd43e37e8 | pywebfaction/exceptions.py | pywebfaction/exceptions.py | import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswi... | import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswi... | Make code immune to bad fault messages | Make code immune to bad fault messages
| Python | bsd-3-clause | dominicrodger/pywebfaction,dominicrodger/pywebfaction | ---
+++
@@ -33,8 +33,12 @@
class WebFactionFault(Exception):
- def __init__(self, underlying_fault):
- self.underlying_fault = underlying_fault
- exc_type, exc_message = underlying_fault.faultString.split(':', 1)
- self.exception_type = _parse_exc_type(exc_type)
- self.exception_me... |
9f345963d1c8dc25818d2cf6716d40e6c90cb615 | sentry/client/handlers.py | sentry/client/handlers.py | import logging
import sys
class SentryHandler(logging.Handler):
def emit(self, record):
from sentry.client.models import get_client
from sentry.client.middleware import SentryLogMiddleware
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMidd... | import logging
import sys
class SentryHandler(logging.Handler):
def emit(self, record):
from sentry.client.models import get_client
from sentry.client.middleware import SentryLogMiddleware
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMidd... | Format records before referencing the message attribute | Format records before referencing the message attribute
| Python | bsd-3-clause | pauloschilling/sentry,ngonzalvez/sentry,gencer/sentry,camilonova/sentry,NickPresta/sentry,Natim/sentry,dbravender/raven-python,fuziontech/sentry,korealerts1/sentry,jmagnusson/raven-python,imankulov/sentry,felixbuenemann/sentry,songyi199111/sentry,jokey2k/sentry,SilentCircle/sentry,zenefits/sentry,jean/sentry,jbarbuto/r... | ---
+++
@@ -9,13 +9,14 @@
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMiddleware.thread, 'request', None)
+ self.format(record)
+
# Avoid typical config issues by overriding loggers behavior
if record.name == 'sentry.errors':
... |
e7e21188daba6efe02d44c2cef9c1b48c45c0636 | readthedocs/donate/urls.py | readthedocs/donate/urls.py | from django.conf.urls import url, patterns, include
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.DonateListView.as_view(), name='donate'),
url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'),
url(r'^contribute/thanks$', views.DonateSuccessView.as_view(), nam... | from django.conf.urls import url, patterns, include
from .views import DonateCreateView
from .views import DonateListView
from .views import DonateSuccessView
urlpatterns = patterns(
'',
url(r'^$', DonateListView.as_view(), name='donate'),
url(r'^contribute/$', DonateCreateView.as_view(), name='donate_ad... | Resolve linting messages in readthedocs.donate.* | Resolve linting messages in readthedocs.donate.*
| Python | mit | mhils/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,istresearch/readthedocs.org,wanghaven/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,hach-que/readthedocs.org,mhils/readthedocs.org,kenwang76/readthedocs.org,kenwang76/readt... | ---
+++
@@ -1,11 +1,13 @@
from django.conf.urls import url, patterns, include
-from . import views
+from .views import DonateCreateView
+from .views import DonateListView
+from .views import DonateSuccessView
urlpatterns = patterns(
'',
- url(r'^$', views.DonateListView.as_view(), name='donate'),
- ... |
650e0497c99500810f0fd1fc205e975892b26ff2 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -16,6 +16,8 @@
dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/'))
print dbs
+dbs = dbs.split('(')[0]
+print dbs
# dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news'... |
a4eb952cc2e583d3b7786f5dea101d1e013c8159 | services/controllers/utils.py | services/controllers/utils.py | def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| def lerp(a, b, t):
return (1.0 - t) * a + t * b
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| Add function for linear interpolation (lerp) | Add function for linear interpolation (lerp)
| Python | bsd-3-clause | gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2 | ---
+++
@@ -1,3 +1,7 @@
+def lerp(a, b, t):
+ return (1.0 - t) * a + t * b
+
+
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min |
a509cd74d1e49dd9f9585b8e4c43e88aaf2bc19d | tests/stonemason/service/tileserver/test_tileserver.py | tests/stonemason/service/tileserver/test_tileserver.py | # -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
... | # -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
... | Update tests for the test app | TEST: Update tests for the test app
| Python | mit | Kotaimen/stonemason,Kotaimen/stonemason | ---
+++
@@ -14,9 +14,9 @@
class TestExample(unittest.TestCase):
def setUp(self):
- os.environ['EXAMPLE_APP_ENV'] = 'dev'
+ os.environ['EXAMPLE_APP_MODE'] = 'development'
- app = AppBuilder().build()
+ app = AppBuilder().build(config='settings.py')
self.client = app.test_... |
7b66af8bea8e6c25e3c2f88efc22875504e8f87a | openstates/events.py | openstates/events.py | from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.e... | from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.e... | Add more keys in; validation | Add more keys in; validation
| Python | bsd-3-clause | openstates/billy,sunlightlabs/billy,sunlightlabs/billy,openstates/billy,sunlightlabs/billy,openstates/billy | ---
+++
@@ -12,10 +12,26 @@
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.events = self.api(method)
for event in self.events:
- e = Event(name=event['description'],
- location=event['location'],
- start_time=dpars... |
14bd2c0732b5871ac43991a237a8f12a334e982d | sirius/LI_V00/__init__.py | sirius/LI_V00/__init__.py | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice... | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice... | Add parameters of initial beam distribution at LI | Add parameters of initial beam distribution at LI
| Python | mit | lnls-fac/sirius | ---
+++
@@ -13,4 +13,5 @@
default_optics_mode = _lattice._default_optics_mode.label
lattice_version = 'LI_V00'
family_data = _lattice._family_data
-emittance = _lattice._emittance
+emittance = _lattice._emittance
+global_coupling = 1.0 # "round" beam |
c3ead28e278e2b4e3d44071fb891fa54de46b237 | shopping_app/utils/helpers.py | shopping_app/utils/helpers.py | import os
import random
import string
from datetime import date, datetime
def random_name():
return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)])
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datet... | import os
import random
import string
from datetime import date, datetime
def random_name():
return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)])
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datet... | Update generate_secret function to the root of the app | Update generate_secret function to the root of the app
| Python | mit | gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list | ---
+++
@@ -17,7 +17,7 @@
def secret_key_gen():
- filepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/secret.ini'
+ filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.ini'
generated_key = ''.join([random.SystemRandom().choice(strin... |
22a5985cfd29b87a1215a6a38d5ab07ab19e7508 | auth_backends/__init__.py | auth_backends/__init__.py | """ Django authentication backends.
These package is designed to be used primarily with Open edX Django projects, but should be compatible with non-edX
projects as well.
"""
__version__ = '2.0.0' # pragma: no cover
| """ Django authentication backends.
These package is designed to be used primarily with Open edX Django projects, but should be compatible with non-edX
projects as well.
"""
__version__ = '2.0.1' # pragma: no cover
| Create new Version for auth-backends for release | Create new Version for auth-backends for release
| Python | agpl-3.0 | edx/auth-backends | ---
+++
@@ -3,4 +3,4 @@
These package is designed to be used primarily with Open edX Django projects, but should be compatible with non-edX
projects as well.
"""
-__version__ = '2.0.0' # pragma: no cover
+__version__ = '2.0.1' # pragma: no cover |
61448043a039543c38c5ca7b9828792cfc8afbb8 | justwatch/justwatchapi.py | justwatch/justwatchapi.py | import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
pay... | import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
pay... | Check and raise HTTP errors | Check and raise HTTP errors
| Python | mit | dawoudt/JustWatchAPI | ---
+++
@@ -34,4 +34,8 @@
header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'}
api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country)
r = requests.post(api_url, json=payload, headers=header)
+
+ # Client should deal with rate-limiting. J... |
fc70feec85f0b22ebef05b0fa1316214a48a465a | background/config/prod.py | background/config/prod.py | from decouple import config
from .base import BaseCeleryConfig
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL')
result_backend = config('CELERY_RESULT_BACKEND')
| from decouple import config
from .base import BaseCeleryConfig
REDIS_URL = config('REDIS_URL')
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL',
default=REDIS_URL)
result_backend = ... | Use REDIS_URL by default for Celery | Use REDIS_URL by default for Celery
| Python | mit | RaitoBezarius/ryuzu-fb-bot | ---
+++
@@ -2,8 +2,12 @@
from .base import BaseCeleryConfig
+REDIS_URL = config('REDIS_URL')
+
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
- broker_url = config('CELERY_BROKER_URL')
- result_backend = config('CELERY_RESULT_BACKEND')
+ ... |
431b8db027ce016a957a744ed38f833031e93070 | syncplay/__init__.py | syncplay/__init__.py | version = '1.3.0'
milestone = 'Chami'
release_number = '5'
projectURL = 'http://syncplay.pl/'
| version = '1.3.0'
milestone = 'Chami'
release_number = '6'
projectURL = 'http://syncplay.pl/'
| Move up to release 6 (1.3.0 Beta 3b) | Move up to release 6 (1.3.0 Beta 3b)
| Python | apache-2.0 | NeverDecaf/syncplay,alby128/syncplay,alby128/syncplay,Syncplay/syncplay,NeverDecaf/syncplay,Syncplay/syncplay | ---
+++
@@ -1,4 +1,4 @@
version = '1.3.0'
milestone = 'Chami'
-release_number = '5'
+release_number = '6'
projectURL = 'http://syncplay.pl/' |
dd0cef83edbd3849484b7fc0ec5cb6372f99bb3a | batchflow/models/utils.py | batchflow/models/utils.py | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list) and layers_max > 1:
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
... | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
... | Allow for 1 arg in a list | Allow for 1 arg in a list
| Python | apache-2.0 | analysiscenter/dataset | ---
+++
@@ -5,7 +5,7 @@
""" Return layer parameters """
new_args = {}
for arg in args:
- if isinstance(args[arg], list) and layers_max > 1:
+ if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else: |
5c3863fdb366f857fb25b88c2e47508f23660cf3 | tests/test_socket.py | tests/test_socket.py | import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_e... | import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_e... | Fix python2.6 compatibility in tests. | Fix python2.6 compatibility in tests.
| Python | mit | kramarz/RouterOS-api,socialwifi/RouterOS-api,pozytywnie/RouterOS-api | ---
+++
@@ -36,6 +36,5 @@
socket.error(1),
None
]
- with self.assertRaises(socket.error):
- api_socket.get_socket('host', 123)
+ self.assertRaises(socket.error, api_socket.get_socket, 'host', 123)
connect.assert_has_calls([mock.call(('host', 123))]) |
8581d3bb9a0066b872dc8daddfde070fdcda7b89 | docs/conf.py | docs/conf.py | from __future__ import unicode_literals
import os
import sys
extensions = []
templates_path = []
source_suffix = ".rst"
master_doc = "index"
project = "django-user-accounts"
copyright_holder = "James Tauber and contributors"
copyright = "2013, {0}",format(copyright_holder)
exclude_patterns = ["_build"]
pygments_styl... | from __future__ import unicode_literals
import os
import sys
extensions = []
templates_path = []
source_suffix = ".rst"
master_doc = "index"
project = "django-user-accounts"
copyright_holder = "James Tauber and contributors"
copyright = "2014, {0}",format(copyright_holder)
exclude_patterns = ["_build"]
pygments_styl... | Increment the year in the copyright | Increment the year in the copyright | Python | mit | jmburbach/django-user-accounts,mysociety/django-user-accounts,jpotterm/django-user-accounts,mgpyh/django-user-accounts,GeoNode/geonode-user-accounts,mentholi/django-user-accounts,ntucker/django-user-accounts,pinax/django-user-accounts,osmfj/django-user-accounts,pinax/django-user-accounts,jawed123/django-user-accounts,j... | ---
+++
@@ -10,7 +10,7 @@
master_doc = "index"
project = "django-user-accounts"
copyright_holder = "James Tauber and contributors"
-copyright = "2013, {0}",format(copyright_holder)
+copyright = "2014, {0}",format(copyright_holder)
exclude_patterns = ["_build"]
pygments_style = "sphinx"
html_theme = "default" |
fd76a19b399bb52dc2cd69fda9bbfed912c8a407 | docs/conf.py | docs/conf.py | # -*- coding: utf-8 -*-
import sys
import os
from glob import glob
# -------------------------------------------------------------------------
# Configure extensions
extensions = [
'sphinx.ext.autodoc',
]
# -------------------------------------------------------------------------
# General configuration
projec... | # -*- coding: utf-8 -*-
import sys
import os
from glob import glob
# -------------------------------------------------------------------------
# Configure extensions
extensions = [
'sphinx.ext.autodoc',
]
# -------------------------------------------------------------------------
# Helper function for retrievin... | Add retrieval of docs version from VERSION.txt | Add retrieval of docs version from VERSION.txt
| Python | apache-2.0 | t4ngo/sphinxcontrib-traceables | ---
+++
@@ -12,12 +12,21 @@
]
# -------------------------------------------------------------------------
+# Helper function for retrieving info from files
+
+def read(*names):
+ root_dir = os.path.dirname(__file__)
+ path = os.path.join(root_dir, *names)
+ with open(path) as f:
+ return f.read()
... |
d7c5001f2109b7e97fbb5f8f82282f8187683365 | docs/conf.py | docs/conf.py | import os
import sdv
project = u'stix-validator'
copyright = u'2015, The MITRE Corporation'
version = sdv.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinxcontrib.napoleon',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: ... | import os
import sdv
project = u'stix-validator'
copyright = u'2015, The MITRE Corporation'
version = sdv.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinxcontrib.napoleon',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: ... | Fix zero-length field error when building docs in Python 2.6 | Fix zero-length field error when building docs in Python 2.6
| Python | bsd-3-clause | pombredanne/stix-validator,STIXProject/stix-validator | ---
+++
@@ -17,7 +17,7 @@
master_doc = 'index'
rst_prolog = """
-**Version**: {}
+**Version**: {0}
""".format(release)
exclude_patterns = ['_build'] |
889473ba81816aa0ad349823515843c337a6b985 | benchexec/tools/deagle.py | benchexec/tools/deagle.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.tem... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.tem... | Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64 | Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
| Python | apache-2.0 | ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec | ---
+++
@@ -10,9 +10,9 @@
import benchexec.tools.template
-class Tool(benchexec.tools.template.BaseTool):
- def executable(self):
- return util.find_executable("deagle")
+class Tool(benchexec.tools.template.BaseTool2):
+ def executable(self, tool_locator):
+ return tool_locator.find_executabl... |
6bc1f6e466fa09dd0bc6a076f9081e1aa03efdc7 | examples/translations/dutch_test_1.py | examples/translations/dutch_test_1.py | # Dutch Language Test
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikiped... | # Dutch Language Test
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikiped... | Update the Dutch example test | Update the Dutch example test
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -11,11 +11,11 @@
self.typ("#searchInput", "Stroopwafel")
self.klik("#searchButton")
self.controleren_tekst("Stroopwafel", "#firstHeading")
- self.controleren_element('img[alt="Stroopwafels"]')
+ self.controleren_element('img[src*="Stroopwafels"]')
self.typ(... |
f8d8aac9f342c10268165f4e2e641a6c667f97fd | Algorithms/Implementation/the-grid-search.py | Algorithms/Implementation/the-grid-search.py | # Python 2
import sys
def search_inside(G, P, R, C, r, c):
for i in range(R - r + 1):
for j in range(C - c + 1):
valid = True
for k in range(r):
if G[i + k][j:j + c] != P[k]:
valid = False
break
if va... | # Python 2
import sys
def search_inside(G, P, R, C, r, c):
for i in range(R - r + 1):
for j in range(C - c + 1):
valid = True
for k in range(r):
if G[i + k][j:j + c] != P[k]:
valid = False
break # break out of for-l... | Add comment to clarify roll of break on line 12 | Add comment to clarify roll of break on line 12
| Python | mit | ugaliguy/HackerRank,ugaliguy/HackerRank,ugaliguy/HackerRank | ---
+++
@@ -9,7 +9,7 @@
for k in range(r):
if G[i + k][j:j + c] != P[k]:
valid = False
- break
+ break # break out of for-loop and go to next value of j
if valid:
print 'YES' |
7e068075c6cd231926cc5f5469472f3fafba7c18 | biwako/bin/fields/util.py | biwako/bin/fields/util.py | import sys
from .base import Field
class Reserved(Field):
def __init__(self, *args, **kwargs):
super(Reserved, self).__init__(*args, **kwargs)
# Hack to add the reserved field to the class without
# having to explicitly give it a (likely useless) name
frame = sys._getf... | import sys
from .base import Field
from ..fields import args
class Reserved(Field):
default = args.Override(default=None)
def __init__(self, *args, **kwargs):
super(Reserved, self).__init__(*args, **kwargs)
# Hack to add the reserved field to the class without
# having ... | Add a default value of None for reserved fields | Add a default value of None for reserved fields
| Python | bsd-3-clause | gulopine/steel | ---
+++
@@ -1,9 +1,12 @@
import sys
from .base import Field
+from ..fields import args
class Reserved(Field):
+ default = args.Override(default=None)
+
def __init__(self, *args, **kwargs):
super(Reserved, self).__init__(*args, **kwargs)
|
dc2c960bb937cc287dedf95d407ed2e95f3f6724 | sigma_files/serializers.py | sigma_files/serializers.py | from rest_framework import serializers
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='f... | from rest_framework import serializers
from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(m... | Add permissions field on ImageSerializer | Add permissions field on ImageSerializer
| Python | agpl-3.0 | ProjetSigma/backend,ProjetSigma/backend | ---
+++
@@ -1,4 +1,5 @@
from rest_framework import serializers
+from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
@@ -12,3 +13,4 @@
height = serializers.IntegerField(source='file.height', read_only=True)
... |
d9262650eb1ce108c196bc10b0edcd8de6429dc2 | fabconfig.py | fabconfig.py | from fabric.api import env
env.client = 'zsoobhan'
env.project_code = 'prometheus'
env.web_dir = 'www'
# Environment-agnostic folders
env.project_dir = '/var/www/%(client)s/%(project_code)s' % env
env.static_dir = '/mnt/static/%(client)s/%(project_code)s' % env
env.builds_dir = '%(project_dir)s/builds' % env
def _... | from fabric.api import env
env.client = 'zsoobhan'
env.project_code = 'prometheus'
env.web_dir = 'www'
# Environment-agnostic folders
env.project_dir = '/var/www/%(client)s/%(project_code)s' % env
env.static_dir = '/mnt/static/%(client)s/%(project_code)s' % env
env.builds_dir = '%(project_dir)s/builds' % env
def _... | Switch to new ec2 instance | Switch to new ec2 instance
| Python | mit | zsoobhan/prometheus,zsoobhan/prometheus,zsoobhan/prometheus,zsoobhan/prometheus | ---
+++
@@ -23,7 +23,7 @@
def prod():
_configure('prod')
- env.hosts = ['ec2-54-77-186-157.eu-west-1.compute.amazonaws.com']
+ env.hosts = ['ec2-54-154-143-128.eu-west-1.compute.amazonaws.com']
env.remote_user = 'ubuntu'
|
05c9039c364d87c890cffdb9de7f0c8d1f7f9cb3 | tfx/orchestration/config/kubernetes_component_config.py | tfx/orchestration/config/kubernetes_component_config.py | # Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... | # Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... | Convert k8s pod spec into dict structure to make sure that it's json serializable. | Convert k8s pod spec into dict structure to make sure that it's json serializable.
PiperOrigin-RevId: 279162159
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | ---
+++
@@ -23,6 +23,7 @@
from kubernetes import client
from tfx.orchestration.config import base_component_config
+from tfx.orchestration.launcher import container_common
class KubernetesComponentConfig(base_component_config.BaseComponentConfig):
@@ -37,4 +38,4 @@
def __init__(self, pod: Union[client.V1P... |
0f0a5e42422f71143c8bcbc3278ad0dc3b81c818 | eratosthenes_lambda.py | eratosthenes_lambda.py | from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
f... | from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
for i in ... | Convert tabs to spaces per PEP 8. | Convert tabs to spaces per PEP 8.
| Python | mit | jconning/lambda-cpu-cost,jconning/lambda-cpu-cost | ---
+++
@@ -10,8 +10,8 @@
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
- for i in range(pv+pv, n+1, pv):
- sieve[i] = False
+ for i in range(pv+pv, n+1, pv):
+ sieve[i] = False
markOff(2)
for i in range(3, n+1):
if... |
525e7d5061326c7c815f4ede7757afb7c085ff78 | apartments/models.py | apartments/models.py | from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=True)
craigslist_id = Column(String, u... | from sqlalchemy import create_engine, Column, DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=... | Add timestamp field to Listing | Add timestamp field to Listing
| Python | mit | rlucioni/apartments,rlucioni/craigbot,rlucioni/craigbot | ---
+++
@@ -1,6 +1,7 @@
-from sqlalchemy import create_engine, Column, Integer, String
+from sqlalchemy import create_engine, Column, DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
+from sqlalchemy.sql import func
Base = declarative_bas... |
f67746750bdd2a1d6e662b1fc36d5a6fa13098c5 | scripts/generate.py | scripts/generate.py | #!/usr/bin/env python
template = """#!/bin/bash
#PBS -l walltime=72:00:00
#PBS -l nodes=1:ppn=1
cd /RQusagers/vanmerb/rnnencdec
export PYTHONPATH=/RQusagers/vanmerb/rnnencdec/groundhog-private/:$PYTHONPATH
python /RQusagers/vanmerb/rnnencdec/groundhog-private/scripts/RNN_Enc_Dec_Phrase.py \"{options}\" >{log} 2>&1"... | #!/usr/bin/env python
template = """#!/bin/bash
#PBS -l walltime=72:00:00
#PBS -l nodes=1:ppn=1
cd /RQusagers/vanmerb/rnnencdec
export PYTHONPATH=/RQusagers/vanmerb/rnnencdec/groundhog-private/:$PYTHONPATH
python /RQusagers/vanmerb/rnnencdec/groundhog-private/scripts/RNN_Enc_Dec_Phrase.py \"{options}\" >{log} 2>&1"... | Add different prefixes for the experiments | Add different prefixes for the experiments
| Python | bsd-3-clause | rizar/groundhog-private | ---
+++
@@ -11,11 +11,11 @@
python /RQusagers/vanmerb/rnnencdec/groundhog-private/scripts/RNN_Enc_Dec_Phrase.py \"{options}\" >{log} 2>&1"""
params = [
- ("dict(dim=250, dim_mlp=250)", "run1"),
- ("dict(dim=500, dim_mlp=500)", "run2"),
- ("dict(rank_n_approx=200)", "run3"),
- ("dict(rank_n_approx=500)... |
7675547ab7669d1df03bf258ffc676799879a191 | build/android/pylib/gtest/gtest_config.py | build/android/pylib/gtest/gtest_config.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
]
... | Move content_browsertests to main waterfall/trybots. | [Android] Move content_browsertests to main waterfall/trybots.
It's passing consistently on android_fyi_dbg trybots and on FYI waterfall bots running ICS.
BUG=270144
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/22299007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@216442 0039d316-1c4b-4281-... | Python | bsd-3-clause | jaruba/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,mark... | ---
+++
@@ -6,7 +6,6 @@
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
- 'content_browsertests',
]
# Do not modify this list without approval of an android owner.
@@ -30,4 +29,5 @@
'webkit_unit_tests',
'breakpad_unittests',
'sandbox_linux_u... |
8abd52f37e713d9d26cccd5c073fe338145759fd | child_sync_gp/model/project_compassion.py | child_sync_gp/model/project_compassion.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file _... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file _... | Fix bug in write project. | Fix bug in write project.
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,Secheron/compassion-switzerland,ecino/compassion-switzerland,ndtran/compassion-switzerland,MickSandoz/compassion-switzerland,Secheron/compassion-switzer... | ---
+++
@@ -21,6 +21,8 @@
"""Update Project in GP."""
res = super(project_compassion, self).write(cr, uid, ids, vals,
context)
+ if not isinstance(ids, list):
+ ids = [ids]
gp_connect = gp_connector.GPConnect()
... |
1986000f7e3fff1366de245dadf8cd3b6e53f238 | djstripe/contrib/rest_framework/permissions.py | djstripe/contrib/rest_framework/permissions.py | """
.. module:: dj-stripe.contrib.rest_framework.permissions.
:synopsis: dj-stripe - Permissions to be used with the dj-stripe REST API.
.. moduleauthor:: @kavdev, @pydanny
"""
from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscrib... | """
.. module:: dj-stripe.contrib.rest_framework.permissions.
:synopsis: dj-stripe - Permissions to be used with the dj-stripe REST API.
.. moduleauthor:: @kavdev, @pydanny
"""
from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscrib... | Fix missing return statement in DJStripeSubscriptionPermission | Fix missing return statement in DJStripeSubscriptionPermission
Fixes #1250
| Python | mit | dj-stripe/dj-stripe,dj-stripe/dj-stripe,pydanny/dj-stripe,pydanny/dj-stripe | ---
+++
@@ -17,7 +17,7 @@
A permission to be used when wanting to permit users with active subscriptions.
"""
- def has_permission(self, request, view):
+ def has_permission(self, request, view) -> bool:
"""
Check if the subscriber has an active subscription.
@@ -28,6 +28,8 @@
... |
25d93bf202e1735f21b6c3ad5830e660824efde6 | flask_truss/blueprints/_blueprint/__init__.py | flask_truss/blueprints/_blueprint/__init__.py | from flask import Blueprint, render_template, current_app, request
from flask_truss.async._task import _task
from flask_truss.libs.logger import log_flask_request
_blueprint = Blueprint('_blueprint', __name__, template_folder='templates')
@_blueprint.route('/')
def render_blueprint():
log_flask_request(current... | from flask import Blueprint, render_template, current_app, request
from flask_truss.async._task import _task
from flask_truss.lib.logger import log_flask_request
_blueprint = Blueprint('_blueprint', __name__, template_folder='templates')
@_blueprint.route('/')
def render_blueprint():
log_flask_request(current_... | Fix typo in imports in _blueprint. Libs -> lib | Fix typo in imports in _blueprint. Libs -> lib
| Python | mit | bmoar/flask-truss,bmoar/flask-truss | ---
+++
@@ -1,7 +1,7 @@
from flask import Blueprint, render_template, current_app, request
from flask_truss.async._task import _task
-from flask_truss.libs.logger import log_flask_request
+from flask_truss.lib.logger import log_flask_request
_blueprint = Blueprint('_blueprint', __name__, template_folder='tem... |
94351ce09112c7bd4c9ed58722334ee48fe99883 | datapackage_pipelines_fiscal/processors/upload.py | datapackage_pipelines_fiscal/processors/upload.py | import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp... | import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp... | Set the publication with a parameter. | Set the publication with a parameter. | Python | mit | openspending/datapackage-pipelines-fiscal | ---
+++
@@ -20,4 +20,4 @@
datapackage_json = os.path.join(temp_dir, 'datapackage.json')
package = gobble.fiscal.FiscalDataPackage(datapackage_json, user=user)
-package.upload(skip_validation=True, publish=False)
+package.upload(skip_validation=True, publish=params.get('publish', False)) |
9c52c82fab42ee5667791fdea612bcb94b17445e | server/constants.py | server/constants.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Constants representing the setting keys for this plugin
class PluginSettings:
HISTOMICSTK_DEFAULT_DRAW_STYLES = 'histomicstk.default_draw_styles'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Constants representing the setting keys for this plugin
class PluginSettings(object):
HISTOMICSTK_DEFAULT_DRAW_STYLES = 'histomicstk.default_draw_styles'
| Use new-style Python 2 classes. | Use new-style Python 2 classes.
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | ---
+++
@@ -3,5 +3,5 @@
# Constants representing the setting keys for this plugin
-class PluginSettings:
+class PluginSettings(object):
HISTOMICSTK_DEFAULT_DRAW_STYLES = 'histomicstk.default_draw_styles' |
155ab92dd2ff4340e4773e22762d52f557b300e8 | dividebatur/tests/test_ticket_sort_key.py | dividebatur/tests/test_ticket_sort_key.py | from ..aecdata import ticket_sort_key
def apply_ticket_sort(items):
return list(sorted(items, key=ticket_sort_key))
def test_a_c_already_sorted():
assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])
def test_a_c_reversed():
assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])
def ... | from ..aecdata.utils import ticket_sort_key
def apply_ticket_sort(items):
return list(sorted(items, key=ticket_sort_key))
def test_a_c_already_sorted():
assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])
def test_a_c_reversed():
assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])
... | Fix import in ticket_sort_key tests. | Fix import in ticket_sort_key tests.
| Python | apache-2.0 | grahame/dividebatur,grahame/dividebatur,grahame/dividebatur | ---
+++
@@ -1,4 +1,4 @@
-from ..aecdata import ticket_sort_key
+from ..aecdata.utils import ticket_sort_key
def apply_ticket_sort(items): |
ec4d84e0b67d26dd9888d1b54adda6fbbcdc67da | packages/blueprints/api.py | packages/blueprints/api.py | from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint... | from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint... | Add API endpoint for logging in | Add API endpoint for logging in
| Python | mit | KnightOS/packages.knightos.org,MaxLeiter/packages.knightos.org,MaxLeiter/packages.knightos.org,KnightOS/packages.knightos.org,KnightOS/packages.knightos.org,MaxLeiter/packages.knightos.org | ---
+++
@@ -11,7 +11,17 @@
api = Blueprint('api', __name__)
-@api.route("/test")
+@api.route("/api/v1/login", methods=['POST'])
@json_output
-def test():
- return { 'value': 'Hello world!' }
+def login():
+ username = request.form['username']
+ password = request.form['password']
+ user = User.query... |
58c97445c8d55d48e03498c758f7b7c6dee245aa | enabled/_50_admin_add_monitoring_panel.py | enabled/_50_admin_add_monitoring_panel.py | # The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
# Python panel class of the PANEL to be added.
ADD_PANE... | # The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of t... | Set DEFAULT_PANEL to monitoring panel | Set DEFAULT_PANEL to monitoring panel
| Python | apache-2.0 | stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui | ---
+++
@@ -4,6 +4,8 @@
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
+
+DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
@@ -12,3 +14,6 @@
# A list of applications to be added to INSTALLED_APPS.
ADD_I... |
948c269ba191339a471844eb512448941be4497c | readthedocs/doc_builder/base.py | readthedocs/doc_builder/base.py | from functools import wraps
import os
from functools import wraps
def restoring_chdir(fn):
@wraps(fn)
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
... | from functools import wraps
import os
from functools import wraps
def restoring_chdir(fn):
@wraps(fn)
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
... | Kill _changed from the Base so subclassing makes more sense. | Kill _changed from the Base so subclassing makes more sense. | Python | mit | gjtorikian/readthedocs.org,cgourlay/readthedocs.org,tddv/readthedocs.org,wanghaven/readthedocs.org,asampat3090/readthedocs.org,kenwang76/readthedocs.org,KamranMackey/readthedocs.org,clarkperkins/readthedocs.org,VishvajitP/readthedocs.org,emawind84/readthedocs.org,Carreau/readthedocs.org,johncosta/private-readthedocs.or... | ---
+++
@@ -17,8 +17,6 @@
"""
The Base for all Builders. Defines the API for subclasses.
"""
-
- _changed = True
@restoring_chdir
def force(self, version):
@@ -64,4 +62,4 @@
Defaults to `True`
"""
- return self._changed
+ return getattr(self, '_changed',... |
7cedab4826d5d184e595864f4cf5ca3966a1921e | random_object_id/random_object_id.py | random_object_id/random_object_id.py | import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l... | import binascii
import os
import time
from argparse import ArgumentParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
parser = ArgumentParser(description='Generate a... | Use argparse instead of optparse | Use argparse instead of optparse
| Python | mit | mxr/random-object-id | ---
+++
@@ -2,7 +2,7 @@
import os
import time
-from optparse import OptionParser
+from argparse import ArgumentParser
def gen_random_object_id():
@@ -11,17 +11,17 @@
return timestamp + rest
if __name__ == '__main__':
- parser = OptionParser()
- parser.add_option('-l', '--longform',
- ... |
ad2fd7bf2ccfee18856e6f94b996a630ae8362ee | sharepa/__init__.py | sharepa/__init__.py | from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
def source_counts():
return bucket_to_dataframe(
'total_source_counts',
basic_search.execute().aggregations.sourceAgg.buckets
)
| from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
def source_counts():
return bucket_to_dataframe(
'total_source_counts',
ShareSearch().execute().aggregations.sourceAgg.buckets
)
| Make total_source_counts always be a full query | Make total_source_counts always be a full query
| Python | mit | fabianvf/sharepa,CenterForOpenScience/sharepa,erinspace/sharepa,samanehsan/sharepa | ---
+++
@@ -5,5 +5,5 @@
def source_counts():
return bucket_to_dataframe(
'total_source_counts',
- basic_search.execute().aggregations.sourceAgg.buckets
+ ShareSearch().execute().aggregations.sourceAgg.buckets
) |
404b9208d98753dfccffb6c87594cfc70faed073 | filer/tests/general.py | filer/tests/general.py | #-*- coding: utf-8 -*-
from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0)
def test_travisci_configuration(self):
self.assertTrue(False) | #-*- coding: utf-8 -*-
from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0) | Revert "travis ci: test if it REALLY works" | Revert "travis ci: test if it REALLY works"
This reverts commit 78d87177c71adea7cc06d968374d2c2197dc5289.
| Python | bsd-3-clause | Flight/django-filer,obigroup/django-filer,DylannCordel/django-filer,vstoykov/django-filer,o-zander/django-filer,mitar/django-filer,stefanfoulis/django-filer,skirsdeda/django-filer,thomasbilk/django-filer,kriwil/django-filer,sbussetti/django-filer,jakob-o/django-filer,lory87/django-filer,rollstudio/django-filer,Flight/d... | ---
+++
@@ -6,6 +6,3 @@
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0)
-
- def test_travisci_configuration(self):
- self.assertTrue(False) |
bbe2ef061eb52113d4579eac0415c79275b04721 | src/masterfile/formatters.py | src/masterfile/formatters.py | # -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2018 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licence; see... | # -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2018 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licence; see... | Improve documentation for column formatter | Improve documentation for column formatter
The algorithm is similar to a "convert to base X" one, except that it
doesn't have a zero -- we go from "Z" to "AA" which is like going from
9 to 11.
This is important enough to mention.
| Python | mit | njvack/masterfile | ---
+++
@@ -22,12 +22,17 @@
25 => Z
26 => AA
703 => AAB
+ Note that this is similar to converting numbers to base-26, but not quite
+ the same — this numbering scheme has no concept of 0. We go from
+ "Z" to "AA" which is like going from 9 to 11 with no intervening 10.
+ Only works for posi... |
ffb8f3f0d1fe17e13b349f8f4bae8fd9acbbd146 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman
# Copyright (c) 2014 Ethan Zimmerman
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an ... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman
# Copyright (c) 2014 Ethan Zimmerman
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an ... | Update regex to match new parser output | Update regex to match new parser output
| Python | mit | thebinarypenguin/SublimeLinter-contrib-raml-cop | ---
+++
@@ -22,7 +22,6 @@
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
- r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0) |
302c246d1da11282e2f6a687fb504e18f1399a84 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Jack Cherng
# Copyright (c) 2017-2019 jfcherng
#
# License: MIT
#
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
... | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Jack Cherng
# Copyright (c) 2017-2019 jfcherng
#
# License: MIT
#
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
... | Add "-i" flag to ignore module not found errors | Add "-i" flag to ignore module not found errors
https://github.com/steveicarus/iverilog/pull/151
Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
| Python | mit | jfcherng/SublimeLinter-contrib-iverilog,jfcherng/SublimeLinter-contrib-iverilog | ---
+++
@@ -15,7 +15,7 @@
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
name = "iverilog"
- cmd = "iverilog -t null ${args}"
+ cmd = "iverilog -i -t null ${args}"
tempfile_suffix = "verilog"
multiline = True
on_stderr = None |
90c5c9db788c0450483d71c38155fcf0a9d56220 | sc2reader/engine/plugins/apm.py | sc2reader/engine/plugins/apm.py | from collections import Counter
class APMTracker(object):
def handleInitGame(self, event, replay):
for player in replay.players:
player.apm = Counter()
player.aps = Counter()
player.seconds_played = replay.length.seconds
def handlePlayerActionEvent(self, event, rep... | from collections import Counter
class APMTracker(object):
"""
Builds ``player.aps`` and ``player.apm`` dictionaries where an action is
any Selection, Hotkey, or Ability event.
Also provides ``player.avg_apm`` which is defined as the sum of all the
above actions divided by the number of seconds pla... | Fix the engine's APM plugin and add some documentation. | Fix the engine's APM plugin and add some documentation.
| Python | mit | StoicLoofah/sc2reader,vlaufer/sc2reader,ggtracker/sc2reader,GraylinKim/sc2reader,GraylinKim/sc2reader,vlaufer/sc2reader,ggtracker/sc2reader,StoicLoofah/sc2reader | ---
+++
@@ -1,6 +1,16 @@
from collections import Counter
class APMTracker(object):
+ """
+ Builds ``player.aps`` and ``player.apm`` dictionaries where an action is
+ any Selection, Hotkey, or Ability event.
+
+ Also provides ``player.avg_apm`` which is defined as the sum of all the
+ above actions ... |
cd1eac109ed52f34df35ecea95935b7546147c87 | tests/builtins/test_sum.py | tests/builtins/test_sum.py | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, ... | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
print(sum([[1, 2], [3, 4], [5, 6]], []))
""")
def test_sum_tuple(self):
se... | Add more tests for the sum builtin | Add more tests for the sum builtin
| Python | bsd-3-clause | cflee/voc,freakboy3742/voc,freakboy3742/voc,cflee/voc | ---
+++
@@ -5,6 +5,7 @@
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
+ print(sum([[1, 2], [3, 4], [5, 6]], []))
""")
def test_sum_tuple(self):
@@ -24,10 +25,29 @@
print(sum([1, 1.414, 2, 3.14159]))
"... |
f3aea781c633c2ee212b59f17a6028684041568c | scripts/dbutil/clean_afos.py | scripts/dbutil/clean_afos.py | """
Clean up the AFOS database
called from RUN_2AM.sh
"""
import psycopg2
AFOS = psycopg2.connect(database='afos', host='iemdb')
acursor = AFOS.cursor()
acursor.execute("""
delete from products WHERE
entered < ('YESTERDAY'::date - '7 days'::interval) and
entered > ('YESTERDAY'::date - '31 days'::interval... | """Clean up some tables that contain bloaty NWS Text Data
called from RUN_2AM.sh
"""
import psycopg2
# Clean AFOS
AFOS = psycopg2.connect(database='afos', host='iemdb')
acursor = AFOS.cursor()
acursor.execute("""
delete from products WHERE
entered < ('YESTERDAY'::date - '7 days'::interval) and
entered >... | Add purging of postgis/text_products table | Add purging of postgis/text_products table | Python | mit | akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem | ---
+++
@@ -1,21 +1,30 @@
-"""
- Clean up the AFOS database
- called from RUN_2AM.sh
+"""Clean up some tables that contain bloaty NWS Text Data
+
+called from RUN_2AM.sh
"""
import psycopg2
+
+# Clean AFOS
AFOS = psycopg2.connect(database='afos', host='iemdb')
acursor = AFOS.cursor()
acursor.execute("""
-... |
6f9b2dd428cde88418aafdf1708aefdfd047df13 | test_assess_recovery.py | test_assess_recovery.py | from subprocess import CalledProcessError
from textwrap import dedent
from unittest import TestCase
from test_recovery import (
parse_new_state_server_from_error,
)
class RecoveryTestCase(TestCase):
def test_parse_new_state_server_from_error(self):
output = dedent("""
Waiting for address... | from subprocess import CalledProcessError
from textwrap import dedent
from unittest import TestCase
from test_recovery import (
parse_new_state_server_from_error,
)
class AssessRecoveryTestCase(TestCase):
def test_parse_new_state_server_from_error(self):
output = dedent("""
Waiting for a... | Rename the test case to match the renamed module. | Rename the test case to match the renamed module. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | ---
+++
@@ -7,7 +7,7 @@
)
-class RecoveryTestCase(TestCase):
+class AssessRecoveryTestCase(TestCase):
def test_parse_new_state_server_from_error(self):
output = dedent(""" |
6c9bf9ee4428fbb3b35985d1bbd1c1e29b882f5c | appengine_django/db/creation.py | appengine_django/db/creation.py | #!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | #!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Update SUPPORTS_TRANSACTIONS attribute to what is expected by Django 1.2. | Update SUPPORTS_TRANSACTIONS attribute to what is expected by Django 1.2.
Patch contributed by Felix Leong. Thanks.
Fixes Issue #162.
git-svn-id: 7c59d995a3d63779dc3f8cdf6830411bfeeaa67b@109 d4307497-c249-0410-99bd-594fbd7e173e
| Python | apache-2.0 | wtanaka/google-app-engine-helper-for-django,clones/google-app-engine-django | ---
+++
@@ -25,7 +25,9 @@
def create_test_db(self, *args, **kw):
"""Destroys the test datastore. A new store will be recreated on demand"""
+ # Only needed for Django 1.1, deprecated @ 1.2.
settings.DATABASE_SUPPORTS_TRANSACTIONS = False
+ self.connection.settings_dict['SUPPORTS_TRANSACTIONS'] = ... |
69c81b16e07b67ba0a0bc8e1f55049e7987c5b8c | openstack_dashboard/dashboards/admin/instances/panel.py | openstack_dashboard/dashboards/admin/instances/panel.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | Fix an incorrect policy rule in Admin > Instances | Fix an incorrect policy rule in Admin > Instances
Change-Id: I765ae0c36d19c88138fbea9545a2ca4791377ffb
Closes-Bug: #1703066
| Python | apache-2.0 | BiznetGIO/horizon,BiznetGIO/horizon,noironetworks/horizon,ChameleonCloud/horizon,yeming233/horizon,NeCTAR-RC/horizon,yeming233/horizon,BiznetGIO/horizon,yeming233/horizon,openstack/horizon,noironetworks/horizon,NeCTAR-RC/horizon,yeming233/horizon,ChameleonCloud/horizon,NeCTAR-RC/horizon,noironetworks/horizon,openstack/... | ---
+++
@@ -26,4 +26,4 @@
slug = 'instances'
permissions = ('openstack.services.compute',)
policy_rules = ((("compute", "context_is_admin"),
- ("compute", "compute:get_all")),)
+ ("compute", "os_compute_api:servers:detail")),) |
5516b125bb00b928d85a044d3df777e1b0004d03 | ovp_organizations/migrations/0008_auto_20161207_1941.py | ovp_organizations/migrations/0008_auto_20161207_1941.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-07 19:41
from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
for organization in Organization.objects.all():
organization.members.add(orga... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-07 19:41
from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
for organization in Organization.objects.only('pk', 'members').all():
organiz... | Add ".only" restriction to query on migration 0008 | Add ".only" restriction to query on migration 0008
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-organizations,OpenVolunteeringPlatform/django-ovp-organizations | ---
+++
@@ -7,12 +7,12 @@
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
- for organization in Organization.objects.all():
+ for organization in Organization.objects.only('pk', 'members').all():
organization.members.add(organization.owner)
def remove_members(ap... |
8b7529551d11c67aad4729e53a2b25473599b1f7 | billjobs/urls.py | billjobs/urls.py | from django.conf.urls import url, include
from rest_framework.authtoken.views import obtain_auth_token
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf,
name='generate-pdf'),
url... | from django.conf.urls import url, include
from rest_framework.authtoken.views import obtain_auth_token
from . import views
urlpatterns = [
url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf,
name='generate-pdf'),
url(r'^users/$', views.UserAdmin.as_view(), name='users'),
url(r'^users/(?P<pk... | Remove rest_framework routers, add urlpattern for users api | Remove rest_framework routers, add urlpattern for users api
| Python | mit | ioO/billjobs | ---
+++
@@ -1,9 +1,6 @@
from django.conf.urls import url, include
from rest_framework.authtoken.views import obtain_auth_token
from . import views
-
-router = routers.DefaultRouter()
-router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf, |
f8bc5893ee875a309361c26b93996917dbef3ba8 | silk/webdoc/html/__init__.py | silk/webdoc/html/__init__.py |
from .common import *
|
from .common import ( # noqa
A,
ABBR,
ACRONYM,
ADDRESS,
APPLET,
AREA,
ARTICLE,
ASIDE,
AUDIO,
B,
BASE,
BASEFONT,
BDI,
BDO,
BIG,
BLOCKQUOTE,
BODY,
BR,
BUTTON,
Body,
CANVAS,
CAPTION,
CAT,
CENTER,
CITE,
CODE,
COL,
... | Replace import * with explicit names | Replace import * with explicit names
| Python | bsd-3-clause | orbnauticus/silk | ---
+++
@@ -1,2 +1,140 @@
-from .common import *
+from .common import ( # noqa
+ A,
+ ABBR,
+ ACRONYM,
+ ADDRESS,
+ APPLET,
+ AREA,
+ ARTICLE,
+ ASIDE,
+ AUDIO,
+ B,
+ BASE,
+ BASEFONT,
+ BDI,
+ BDO,
+ BIG,
+ BLOCKQUOTE,
+ BODY,
+ BR,
+ BUTTON,
+ Body,
+ ... |
4ec16018192c1bd8fbe60a9e4c410c6c898149f0 | server/ec2spotmanager/migrations/0007_instance_type_to_list.py | server/ec2spotmanager/migrations/0007_instance_type_to_list.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-02-28 16:47
from __future__ import unicode_literals
from django.db import migrations, models
def instance_types_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.ob... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-02-28 16:47
from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration"... | Fix migration. Custom triggers are not run in data migrations. | Fix migration. Custom triggers are not run in data migrations.
| Python | mpl-2.0 | MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager | ---
+++
@@ -1,15 +1,30 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-02-28 16:47
-from __future__ import unicode_literals
+from __future__ import print_function, unicode_literals
+import json
+import sys
from django.db import migrations, models
-def instance_types_to_list(apps, schema_edito... |
9d4b85cdad969dfeb8e9bee1203eb9c916849b1a | wafer/sponsors/views.py | wafer/sponsors/views.py | from django.views.generic.list import ListView
from django.views.generic import DetailView
from rest_framework import viewsets
from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
from wafer.sponsors.models import Sponsor, SponsorshipPackage
from wafer.sponsors.serializers import SponsorSeriali... | from django.views.generic.list import ListView
from django.views.generic import DetailView
from rest_framework import viewsets
from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
from wafer.sponsors.models import Sponsor, SponsorshipPackage
from wafer.sponsors.serializers import SponsorSeriali... | Use order in all sponsors view query | Use order in all sponsors view query
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | ---
+++
@@ -13,7 +13,7 @@
model = Sponsor
def get_queryset(self):
- return Sponsor.objects.all().order_by('packages', 'id')
+ return Sponsor.objects.all().order_by('packages', 'order', 'id')
class SponsorView(DetailView): |
19cd85215a7a305e6f253405a88d087aef114811 | candidates/tests/test_constituencies_view.py | candidates/tests/test_constituencies_view.py | import re
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
def test_constituencies_page(self):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'... | import re
from mock import patch
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
@patch('candidates.popit.PopIt')
def test_constituencies_page(self, mock_popit):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
... | Make test_constituencies_page work without PopIt | Make test_constituencies_page work without PopIt
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/... | ---
+++
@@ -1,10 +1,13 @@
import re
+
+from mock import patch
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
- def test_constituencies_page(self):
+ @patch('candidates.popit.PopIt')
+ def test_constituencies_page(self, mock_popit):
# Just a smoke test to check... |
09b1830f1f8683f73ef0ad111155c8d0aa75e5e2 | settings_unittest.py | settings_unittest.py | from settings_common import *
DEBUG = TEMPLATE_DEBUG = True
DATABASE_ENGINE = 'sqlite3'
DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410')
| from settings_common import *
DEBUG = TEMPLATE_DEBUG = False
DATABASE_ENGINE = 'sqlite3'
TEST_DATABASE_NAME = 'unittest.db'
DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410')
| Disable debug for unit test and specify a test db name. | Disable debug for unit test and specify a test db name.
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | ---
+++
@@ -1,7 +1,8 @@
from settings_common import *
-DEBUG = TEMPLATE_DEBUG = True
+DEBUG = TEMPLATE_DEBUG = False
DATABASE_ENGINE = 'sqlite3'
+TEST_DATABASE_NAME = 'unittest.db'
DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') |
a4585dc9a0d30b223db14755a00df79b96dd1f28 | site/threads/urls.py | site/threads/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list.as_view()),
url(r'/?P<id>[0-9]/$', views.post_detail.as_view())
] | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list.as_view()),
url(r'P<id>[0-9]/$', views.post_detail.as_view())
] | Remove leading slash from URL. | Remove leading slash from URL.
| Python | mit | annaelde/forum-app,annaelde/forum-app,annaelde/forum-app | ---
+++
@@ -3,5 +3,5 @@
urlpatterns = [
url(r'^$', views.post_list.as_view()),
- url(r'/?P<id>[0-9]/$', views.post_detail.as_view())
+ url(r'P<id>[0-9]/$', views.post_detail.as_view())
] |
723a102d6272e7ba4b9df405b7c1493c34ac5b77 | masters/master.chromium.fyi/master_site_config.py | masters/master.chromium.fyi/master_site_config.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
... | Revert pubsub roll on FYI | Revert pubsub roll on FYI
BUG=
TBR=estaab
Review URL: https://codereview.chromium.org/1688503002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298680 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -13,6 +13,3 @@
master_port_alt = 8211
buildbot_url = 'http://build.chromium.org/p/chromium.fyi/'
reboot_on_step_timeout = True
- pubsub_service_account_file = 'service-account-pubsub.json'
- pubsub_topic_url = 'projects/luci-milo/topics/public-buildbot'
- name = 'chromium.fyi' |
39d3f605d240a8abef22107424ec1d6f76161580 | static_precompiler/models.py | static_precompiler/models.py | from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
| from __future__ import unicode_literals
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
def __unicode__(s... | Add __unicode__ to Dependency model | Add __unicode__ to Dependency model
| Python | mit | jaheba/django-static-precompiler,jaheba/django-static-precompiler,paera/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,paera/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengju... | ---
+++
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
from django.db import models
@@ -8,3 +9,6 @@
class Meta:
unique_together = ("source", "depends_on")
+
+ def __unicode__(self):
+ return "{0} depends on {1}".format(self.source, self.depends_on) |
d2051073d48873408a711b56676ee099e5ff685a | sunpy/timeseries/__init__.py | sunpy/timeseries/__init__.py | """
SunPy's TimeSeries module provides a datatype for 1D time series data, replacing the SunPy LightCurve module.
Currently the objects can be instansiated from files (such as CSV and FITS) and urls to these files, but don't include data downloaders for their specific instruments as this will become part of the univer... | """
SunPy's TimeSeries module provides a datatype for 1D time series data, replacing the SunPy LightCurve module.
Currently the objects can be instansiated from files (such as CSV and FITS) and urls to these files, but don't include data downloaders for their specific instruments as this will become part of the univer... | Fix matplotlib / pandas 0.21 bug in examples | Fix matplotlib / pandas 0.21 bug in examples
Here we manually register the pandas matplotlib converters so people
doing manual plotting with pandas works under pandas 0.21
| Python | bsd-2-clause | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | ---
+++
@@ -14,3 +14,8 @@
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
+
+# register pandas datetime converter with matplotlib
+# This is to work around the change in ... |
dae3f42c6f6800181bc1d9f2e98cbacf03849431 | scripts/create_heatmap.py | scripts/create_heatmap.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)) + '/src')
import DataVisualizing
if len(sys.argv) != 2:
print 'usage: create_heatmap.py <data file>'
print ' expected infile is a datafile containing tracking data'
print ' this is a... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)) + '/src')
import DataVisualizing
if len(sys.argv) != 2:
print 'usage: create_heatmap.py <data file>'
print ' expected infile is a datafile containing tracking data'
print ' this is a... | Add raw line data to output | Add raw line data to output
| Python | mit | LifeWatchINBO/bird-tracking,LifeWatchINBO/bird-tracking | ---
+++
@@ -17,5 +17,6 @@
dvis = DataVisualizing.TrackingVisualizer(infile=sys.argv[1])
print ('var day_month_heatdata = {0};'.format(dvis.as_heatmap_json(domain='month', agg_function='max')))
print ('var hour_month_heatdata = {0};'.format(dvis.as_heatmap_json(domain='month', subdomain='hour', agg_func... |
2de7222ffd3d9f4cc7971ad142aa2542eb7ca117 | yunity/stores/models.py | yunity/stores/models.py | from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates... | from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates... | Add related name for group of store | Add related name for group of store
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend | ---
+++
@@ -11,6 +11,6 @@
class Store(BaseModel, LocationModel):
- group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
+ group = models.ForeignKey('groups.Group', on_delete=models.CASCADE, related_name='store')
name = models.TextField()
description = models.TextField(null=True) |
77ae27596c96ef5b8c05fcd02448576b419de074 | config.py | config.py | class Config:
SECRET_KEY = 'jsA5!@z1'
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "postgresql://admin:adminpass@localhost/fastmonkeys"
config = {
'development': DevelopmentConfig
}
| class Config:
SECRET_KEY = 'jsA5!@z1'
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "postgresql://admin:adminpass@localhost/fastmonkeys"
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
config = {
'development': DevelopmentConfig
}
| Add SQLAlchemy commit on after request end | Add SQLAlchemy commit on after request end
| Python | mit | timzdevz/fm-flask-app | ---
+++
@@ -4,6 +4,7 @@
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "postgresql://admin:adminpass@localhost/fastmonkeys"
+ SQLALCHEMY_COMMIT_ON_TEARDOWN = True
config = {
'development': DevelopmentConfig |
a475fc39480b52d4f38d37e58b3e3c45e8335a1e | tagalog/command/logship.py | tagalog/command/logship.py | from __future__ import print_function, unicode_literals
import argparse
import json
import sys
import textwrap
from tagalog import io, stamp, tag
from tagalog import shipper
parser = argparse.ArgumentParser(description=textwrap.dedent("""
Ship log data from STDIN to somewhere else, timestamping and preprocessing
... | from __future__ import print_function, unicode_literals
import argparse
import json
import sys
import textwrap
from tagalog import io, stamp, tag
from tagalog import shipper
parser = argparse.ArgumentParser(description=textwrap.dedent("""
Ship log data from STDIN to somewhere else, timestamping and preprocessing
... | Add support for elasticsearch bulk format | Add support for elasticsearch bulk format
Add a switch to logship to enable support for sending log data in
elasticsearch bulk format.
| Python | mit | nickstenning/tagalog,nickstenning/tagalog,alphagov/tagalog,alphagov/tagalog | ---
+++
@@ -10,11 +10,21 @@
parser = argparse.ArgumentParser(description=textwrap.dedent("""
Ship log data from STDIN to somewhere else, timestamping and preprocessing
each log entry into a JSON document along the way."""))
-parser.add_argument('-t', '--tags', nargs='+')
-parser.add_argument('-s', '--shipp... |
667182bf3460e2237255b00b0eea20a1cf4a83ab | app/main/views/feedback.py | app/main/views/feedback.py | import requests
from werkzeug.exceptions import ServiceUnavailable
from werkzeug.datastructures import MultiDict
from werkzeug.urls import url_parse
from flask import current_app, request, redirect, flash, Markup
from .. import main
@main.route('/feedback', methods=["POST"])
def send_feedback():
feedback_confi... | import requests
from werkzeug.exceptions import ServiceUnavailable
from werkzeug.datastructures import MultiDict
from werkzeug.urls import url_parse
from flask import current_app, request, redirect, flash, Markup
from .. import main
@main.route('/feedback', methods=["POST"])
def send_feedback():
feedback_confi... | Fix broken submission on Python 3. | Fix broken submission on Python 3.
- this breaks Python 2, but we don't care any more.
https://trello.com/c/Uak7y047/8-feedback-forms
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend | ---
+++
@@ -16,7 +16,7 @@
for field, google_form_field in feedback_config['fields'].items():
form_data.setlist(google_form_field, request.form.getlist(field))
- result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True)))
+ result = requests.post(feedback_config['uri'], ... |
7ddc4b975910bf9c77b753e8e0aeaebc45949e4e | linkatos.py | linkatos.py | #! /usr/bin/env python
import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.parser as parser
import linkatos.confirmation as confirmation
import linkatos.printer as printer
import linkatos.utils as utils
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.... | #! /usr/bin/env python
import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKE... | Remove old imports from main | refactor: Remove old imports from main
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -3,10 +3,6 @@
import time
from slackclient import SlackClient
import pyrebase
-import linkatos.parser as parser
-import linkatos.confirmation as confirmation
-import linkatos.printer as printer
-import linkatos.utils as utils
import linkatos.firebase as fb
# starterbot environment variables |
d5cd1eddf1ecf0c463a90d0e69413aadd311977a | lots/urls.py | lots/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^appl... | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^apply/$', 'lots_client.views.apply', ... | Revert "Picture access from admin console" | Revert "Picture access from admin console"
This reverts commit 324fa160fb629f6c4537ca15212c0822e8ac436d.
| Python | mit | opencleveland/large-lots,skorasaurus/large-lots,opencleveland/large-lots,skorasaurus/large-lots,skorasaurus/large-lots,skorasaurus/large-lots,opencleveland/large-lots,opencleveland/large-lots | ---
+++
@@ -1,5 +1,4 @@
from django.conf.urls import patterns, include, url
-from django.conf import settings
from django.contrib import admin
admin.autodiscover()
@@ -17,13 +16,6 @@
url(r'^csv-dump/$', 'lots_admin.views.csv_dump', name='csv_dump'),
url(r'^lots-login/$', 'lots_admin.views.lots_login', ... |
418b65554d86f6fea33d0656ef2a98cb32607fd9 | src/dicomweb_client/__init__.py | src/dicomweb_client/__init__.py | __version__ = '0.21.0rc'
from dicomweb_client.api import DICOMwebClient
| __version__ = '0.21.0'
from dicomweb_client.api import DICOMwebClient
| Increase package version for release | Increase package version for release
| Python | mit | MGHComputationalPathology/dicomweb-client | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '0.21.0rc'
+__version__ = '0.21.0'
from dicomweb_client.api import DICOMwebClient |
88a31ebcd7b65f9282bb0d0a19ad299c1ad431ec | spectral_cube/__init__.py | spectral_cube/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is an Astropy affiliated package.
"""
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init im... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is an Astropy affiliated package.
"""
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init im... | Make Projection importable from the top level of the package | Make Projection importable from the top level of the package
| Python | bsd-3-clause | e-koch/spectral-cube,jzuhone/spectral-cube,radio-astro-tools/spectral-cube,keflavich/spectral-cube,low-sky/spectral-cube | ---
+++
@@ -13,4 +13,5 @@
from .spectral_cube import SpectralCube, VaryingResolutionSpectralCube
from .stokes_spectral_cube import StokesSpectralCube
from .masks import *
+ from .lower_dimensional_structures import Projection
|
26749bd6bd36c4cd930e60c1eb2d0460fd16506e | CodeFights/knapsackLight.py | CodeFights/knapsackLight.py | #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():... | #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():... | Add half tests to knapsack light problem | Add half tests to knapsack light problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -13,6 +13,9 @@
def main():
tests = [
[10, 5, 6, 4, 8, 10],
+ [10, 5, 6, 4, 9, 16],
+ [5, 3, 7, 4, 6, 7],
+ [10, 2, 11, 3, 1, 0],
[]
]
|
60290b0ae96f144cc3b5672a47596355fe117ba7 | tests/test_project/settings.py | tests/test_project/settings.py | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tests.db',
},
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
... | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tests.db',
},
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
... | Remove tz context processor (not available in 1.3) | Remove tz context processor (not available in 1.3)
| Python | mit | ionelmc/django-easyfilters,ionelmc/django-easyfilters | ---
+++
@@ -22,7 +22,6 @@
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
- "django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
] |
a8d2ede0a38188670f6921bd9c2f08ee073b0cdd | test/test_configuration.py | test/test_configuration.py | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_c... | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_c... | FIX test for Windows platform. | FIX test for Windows platform.
| Python | bsd-2-clause | allanlewis/behave,allanlewis/behave,Gimpneek/behave,vrutkovs/behave,metaperl/behave,kymbert/behave,jenisys/behave,Abdoctor/behave,kymbert/behave,benthomasson/behave,mzcity123/behave,joshal/behave,charleswhchan/behave,joshal/behave,hugeinc/behave-parallel,benthomasson/behave,spacediver/behave,connorsml/behave,KevinOrtma... | ---
+++
@@ -27,7 +27,7 @@
d = configuration.read_configuration(tn)
eq_(d['outfile'], '/tmp/spam')
eq_(d['paths'], [
- '/absolute/path',
+ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath
os.path.normpath(os.path.join(os.path.dirname(tn)... |
6a4046aafe43930c202e2f18a55b1cd8517d95f9 | testanalyzer/javaanalyzer.py | testanalyzer/javaanalyzer.py | import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content))
# TODO: Accept angle brackets and decline "else if"
def get_function_count(self, content):
... | import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content))
def get_function_count(self, content):
matches = re.findall(
"[a-zA-Z <>]+ ... | Fix regex to match generics | Fix regex to match generics
| Python | mpl-2.0 | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer | ---
+++
@@ -5,11 +5,14 @@
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
- re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content))
+ re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content))
- # TODO: Accept angle brackets and de... |
3d1f4a241363d2acff056798e6cb459db1acfb1b | tests/server/handlers/test_render.py | tests/server/handlers/test_render.py | import mfr
import json
from tests import utils
from tornado import testing
class TestRenderHandler(utils.HandlerTestCase):
@testing.gen_test
def test_options_skips_prepare(self):
# Would crash b/c lack of mocks
yield self.http_client.fetch(
self.get_url('/render'),
met... | Add a small test for renderer | Add a small test for renderer
| Python | apache-2.0 | AddisonSchiller/modular-file-renderer,haoyuchen1992/modular-file-renderer,TomBaxter/modular-file-renderer,Johnetordoff/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,haoyuchen1992/modular-file-renderer,felliott/modular-file-renderer,Johnetordoff/... | ---
+++
@@ -0,0 +1,15 @@
+import mfr
+import json
+from tests import utils
+from tornado import testing
+
+
+class TestRenderHandler(utils.HandlerTestCase):
+
+ @testing.gen_test
+ def test_options_skips_prepare(self):
+ # Would crash b/c lack of mocks
+ yield self.http_client.fetch(
+ ... | |
ea1c62ae3f13d47ee820eae31a2e284e3d66b6ab | libPiLite.py | libPiLite.py | #!/usr/bin/env python
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
ro... | #!/usr/bin/env python
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
ro... | Add setGrid and resetGrid functions | Add setGrid and resetGrid functions
| Python | mit | rorasa/RPiClockArray | ---
+++
@@ -28,4 +28,13 @@
for i in range(0,numRow):
gridstr += str(grid[i][j])
return gridstr
-
+
+def setGrid(grid, setlist, rowoffset, coloffset):
+ for entry in setlist:
+ grid[entry[0]+rowoffset][entry[1]+coloffset] = 1
+ return grid
+
+def resetGrid(grid, setl... |
e0b3b767ccb7fc601eb7b40d336f94d75f8aa43c | 2016/python/aoc_2016_03.py | 2016/python/aoc_2016_03.py | from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into sorted triples of side lengths."""
sorted_sides = [
sorted(int(x) for x in ... | from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into triples of side lengths."""
sides = [[int(x) for x in line.split()] for line in str... | Sort triples in separate step | 2016-03.py: Sort triples in separate step
| Python | mit | robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions | ---
+++
@@ -6,18 +6,20 @@
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
- """Parse the instruction lines into sorted triples of side lengths."""
- sorted_sides = [
- sorted(int(x) for x in line.split()) for line in string.splitlines()
- ]
- triples = [(sides[0], sides[1], si... |
28fe69ab1bb9362a1ee105821ec4631b574417d3 | tools/perf_expectations/PRESUBMIT.py | tools/perf_expectations/PRESUBMIT.py | #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on ... | #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on ... | Use full pathname to perf_expectations in test. | Use full pathname to perf_expectations in test.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/266055
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@28770 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | littlstar/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,keishi/chromium,markYoungH/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,Chilledheart/chromium,timopulkkinen/BubbleFish,keishi/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,pozdnyakov/chromium-crossw... | ---
+++
@@ -13,12 +13,12 @@
'tests.perf_expectations_unittest',
]
-PERF_EXPECTATIONS = 'perf_expectations.json'
+PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
- if PERF_EXPECT... |
8b5337878172df95400a708b096e012436f8a706 | dags/main_summary.py | dags/main_summary.py | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': 'mreid@mozilla.com',
'depends_on_past': False,
'start_date': datetime(2016, 6, 27),
'email': ['telemetry-alerts... | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': 'mreid@mozilla.com',
'depends_on_past': False,
'start_date': datetime(2016, 6, 25),
'email': ['telemetry-alerts... | Prepare "Main Summary" job for backfill | Prepare "Main Summary" job for backfill
Set the max number of active runs so we don't overwhelm the system,
and rewind the start date by a couple of days to test that the
scheduler does the right thing.
| Python | mpl-2.0 | opentrials/opentrials-airflow,opentrials/opentrials-airflow | ---
+++
@@ -6,7 +6,7 @@
default_args = {
'owner': 'mreid@mozilla.com',
'depends_on_past': False,
- 'start_date': datetime(2016, 6, 27),
+ 'start_date': datetime(2016, 6, 25),
'email': ['telemetry-alerts@mozilla.com', 'mreid@mozilla.com'],
'email_on_failure': True,
'email_on_retry': Tru... |
847375a5cd6cbc160c190c9fb5e9fa2b1f0cdea9 | lustro/db.py | lustro/db.py | # -*- coding: utf-8 -*-
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.... | # -*- coding: utf-8 -*-
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.... | Fix arguments to diff method | Fix arguments to diff method
| Python | mit | ashwoods/lustro | ---
+++
@@ -30,7 +30,7 @@
self.source = DB(source, source_schema)
self.target = DB(target, target_schema)
- def diff(self, tables):
+ def diff(self, tables, modified):
pass
def create(self, tables): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.