commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
3ddcc3ed5b6288ea6b39b7a11c5d85232a2d224f
networkzero/__init__.py
networkzero/__init__.py
# -*- coding: utf-8 -*- """Easy network discovery & messaging Aimed at a classrom or club situation, networkzero makes it simpler to have several machines or several processes on one machine discovering each other and talking across a network. Typical examples would include: * Sending commands to a robot * Sending sc...
# -*- coding: utf-8 -*- """Easy network discovery & messaging Aimed at a classrom or club situation, networkzero makes it simpler to have several machines or several processes on one machine discovering each other and talking across a network. Typical examples would include: * Sending commands to a robot * Sending sc...
Improve the examples in the package root docstring
Improve the examples in the package root docstring
Python
mit
tjguk/networkzero,tjguk/networkzero,tjguk/networkzero
d7eb2dc9eb5f391a6a6742bea3692c8ab1d8aa69
doc/examples/plot_edge_filter.py
doc/examples/plot_edge_filter.py
import matplotlib.pyplot as plt from skimage.data import camera from skimage.filter import roberts, sobel image = camera() edge_roberts = roberts(image) edge_sobel = sobel(image) fig, (ax0, ax1) = plt.subplots(ncols=2) ax0.imshow(edge_roberts, cmap=plt.cm.gray) ax0.set_title('Roberts Edge Detection') ax0.axis('off'...
""" ============== Edge operators ============== Edge operators are used in image processing within edge detection algorithms. They are discrete differentiation operators, computing an approximation of the gradient of the image intensity function. """ import matplotlib.pyplot as plt from skimage.data import camera f...
Add short description to edge filter example
Add short description to edge filter example
Python
bsd-3-clause
ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,bsipocz/scikit-image,oew1v07/scikit-image,michaelaye/scikit-image,SamHames/scikit-image,paalge/scikit-image,almarklein/scikit-image,Midafi/scikit-image,chintak/scikit-image,vighneshbirodkar/scikit-image,juliusbierk/scikit-image,rjeli/scikit-image,chintak/scikit-i...
a4a1d924686a0d74a080369d81e20a75c4e7d210
gem/templatetags/gem_tags.py
gem/templatetags/gem_tags.py
from django.template import Library from django.conf import settings from gem.models import GemSettings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter() def get_bbm_app_id(request): return GemSettings.for_site(request.site).bbm...
from django.template import Library from django.conf import settings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttr...
Revert "Create GEM filter to get BBM App ID"
Revert "Create GEM filter to get BBM App ID" This reverts commit 2805eb26865d7a12cbc0e6f7a71dbd99ba49224e.
Python
bsd-2-clause
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
0e9c2fead2c8ad0194f1174ea7d5ad6acd74a12c
private_storage/storage.py
private_storage/storage.py
""" Django Storage interface """ from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, ...
""" Django Storage interface """ from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy from django.utils.encoding import force_text from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ ...
Fix url reversing in Python 3
Fix url reversing in Python 3
Python
apache-2.0
edoburu/django-private-storage
4ec431669134f8ac01fe5ef1d883bc4dc31fd6d7
number_to_words_test.py
number_to_words_test.py
import unittest from number_to_words import NumberToWords class TestNumberToWords(unittest.TestCase): def setUp(self): self.n2w = NumberToWords() def tearDown(self): self.n2w = None def test_zero_and_single_digits(self): NUMBERS = { 0: 'zero', 1: 'one', 2: 'two', 3: '...
import unittest from number_to_words import NumberToWords class TestNumberToWords(unittest.TestCase): def setUp(self): self.n2w = NumberToWords() def tearDown(self): self.n2w = None def test_zero_and_single_digits(self): NUMBERS = { 0: 'zero', 1: 'one', 2: 'two', 3: '...
Add tests for numbers 11 to 19
Add tests for numbers 11 to 19
Python
mit
ianfieldhouse/number_to_words
954c38e9242da5bd2f8c036dd7c774c942860978
geotrek/api/mobile/urls.py
geotrek/api/mobile/urls.py
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import url, include from rest_framework import routers from geotrek.api.mobile import views as api_mobile router = routers.DefaultRouter() if 'geotrek.flatpages' in settings.INSTALLED_APPS: router.register(r'flatpages'...
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import url, include from rest_framework import routers if 'geotrek.flatpages' and 'geotrek.trekking' and 'geotrek.tourism': from geotrek.api.mobile import views as api_mobile router = routers.DefaultRouter() ur...
Fix api mobile only with geotrek flatpages trekking tourism
Fix api mobile only with geotrek flatpages trekking tourism
Python
bsd-2-clause
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
b07c9ae13f80cb0afbe787543b28e15d546763e6
elevator/db.py
elevator/db.py
import os import md5 import leveldb class DatabasesHandler(dict): def __init__(self, dest, *args, **kwargs): self['index'] = {} self.dest = dest self._init_default_db() def _init_default_db(self): self.add('default') def load(self): # Retrieving every databases fr...
import os import md5 import leveldb class DatabasesHandler(dict): def __init__(self, dest, *args, **kwargs): self['index'] = {} self.dest = dest self._init_default_db() def _init_default_db(self): self.add('default') def load(self): # Retrieving every databases fr...
Add : database handler list and del methods
Add : database handler list and del methods
Python
mit
oleiade/Elevator
97abbb8b38ff38b7b150bb2c4b5e9243856ede02
dork/dns.py
dork/dns.py
""" Dynamic host file management. """ import docker from subprocess import call import re def refresh(): """ Ensure that all running containers have a valid entry in /etc/hosts. """ containers = docker.containers() hosts = '\n'.join(['%s %s' % (c.address, c.domain) for c in [d for d in containers ...
""" Dynamic host file management. """ import docker from subprocess import call import re def refresh(): """ Ensure that all running containers have a valid entry in /etc/hosts. """ containers = docker.containers() hosts = '\n'.join(['%s %s.%s.dork %s' % (c.address, c.project, c.instance, c.domain...
Add both domains to hostsfile.
Add both domains to hostsfile.
Python
mit
iamdork/dork
cbc69077016885ebf2b481eebd2f11511c8184ce
nbgrader/tests/apps/test_nbgrader.py
nbgrader/tests/apps/test_nbgrader.py
import os import sys from .. import run_nbgrader, run_command from .base import BaseTestApp class TestNbGrader(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["--help-all"]) def test_no_subapp(self): """Is the help displayed when no subapp...
import os import sys from .. import run_nbgrader, run_command from .base import BaseTestApp class TestNbGrader(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["--help-all"]) def test_no_subapp(self): """Is the help displayed when no subapp...
Include directory name for python 2 compatibility
Include directory name for python 2 compatibility
Python
bsd-3-clause
jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader
96777198fda175de0f53b8a2a36cc693fe4f50a3
scipy_base/__init__.py
scipy_base/__init__.py
from info_scipy_base import __doc__ from scipy_base_version import scipy_base_version as __version__ from ppimport import ppimport, ppimport_attr # The following statement is equivalent to # # from Matrix import Matrix as mat # # but avoids expensive LinearAlgebra import when # Matrix is not used. mat = ppimport_a...
from info_scipy_base import __doc__ from scipy_base_version import scipy_base_version as __version__ from ppimport import ppimport, ppimport_attr # The following statement is equivalent to # # from Matrix import Matrix as mat # # but avoids expensive LinearAlgebra import when # Matrix is not used. mat = ppimport_a...
Fix for matrixmultiply != dot on Numeric < 23.4
Fix for matrixmultiply != dot on Numeric < 23.4
Python
bsd-3-clause
ddasilva/numpy,behzadnouri/numpy,joferkington/numpy,bertrand-l/numpy,groutr/numpy,Eric89GXL/numpy,jakirkham/numpy,matthew-brett/numpy,cowlicks/numpy,githubmlai/numpy,musically-ut/numpy,dimasad/numpy,jakirkham/numpy,stefanv/numpy,tynn/numpy,ahaldane/numpy,utke1/numpy,pelson/numpy,mingwpy/numpy,skwbc/numpy,Dapid/numpy,ch...
a9f51a3e8eacc360d4f353a1fbe649809f88e4ce
astropy/io/misc/asdf/tags/time/tests/test_timedelta.py
astropy/io/misc/asdf/tags/time/tests/test_timedelta.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest from asdf.tests.helpers import assert_roundtrip_tree from astropy.time import Time @pytest.mark.parametrize('fmt', Time.FORMATS.keys()) def test_timedelta(fmt, tmpdir): t1 = Time(Time.now(), format=fmt) t...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest asdf = pytest.importorskip('asdf') from asdf.tests.helpers import assert_roundtrip_tree from astropy.time import Time @pytest.mark.parametrize('fmt', Time.FORMATS.keys()) def test_timedelta(fmt, tmpdir): t1 =...
Add importorskip('asdf') to test for TimeDelta tag
Add importorskip('asdf') to test for TimeDelta tag
Python
bsd-3-clause
dhomeier/astropy,pllim/astropy,bsipocz/astropy,MSeifert04/astropy,StuartLittlefair/astropy,pllim/astropy,aleksandr-bakanov/astropy,saimn/astropy,bsipocz/astropy,pllim/astropy,saimn/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,astropy/astropy,saimn/astropy,larrybradley/astropy,MSeifert04/astropy,pllim/astr...
a938128b1e6b7654f93047883c90bf7b80ee564e
pentai/t_all.py
pentai/t_all.py
#!/usr/bin/python import unittest import pentai.base.t_all as b_t import pentai.ai.t_all as ai_t import pentai.db.t_all as db_t import pentai.db.zodb_dict as z_m import os def suite(): global all_tests all_tests = unittest.TestSuite() all_tests.addTest(b_t.suite()) all_tests.addTest(ai_t.suite()) ...
#!/usr/bin/python import unittest import pentai.base.t_all as b_t import pentai.ai.t_all as ai_t import pentai.db.t_all as db_t import pentai.db.zodb_dict as z_m import pentai.db.test_db as tdb_m def suite(): global all_tests all_tests = unittest.TestSuite() all_tests.addTest(b_t.suite()) all_tests.a...
Delete test db after a run
Delete test db after a run
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
827bb2fb8025fcd882c58b7b9136bc68231319dd
src/randbot.py
src/randbot.py
__author__ = 'Antony Cherepanov' import tweepy from src import dbhandler from src import generator class RandBot(object): def __init__(self): self.db = dbhandler.DBHandler() self.auth = tweepy.OAuthHandler(*(self.db.get_consumer_data())) self.auth.set_access_token(*(self.db.get_access_tok...
__author__ = 'Antony Cherepanov' import tweepy from src import dbhandler from src import generator class RandBot(object): def __init__(self): self.tweets = list() self.db = dbhandler.DBHandler() self.auth = tweepy.OAuthHandler(*(self.db.get_consumer_data())) self.auth.set_access_t...
Add functions to process tweets
Add functions to process tweets
Python
mit
iamantony/randbot
28d8e67420b64a126db2c14e5532323b0782575b
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, util, highlight class PugLint(NodeLinter): """Prov...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, util, highlight class PugLint(NodeLinter): """Prov...
Remove lines that cause error in Sublime Text console
Remove lines that cause error in Sublime Text console Logs: puglint: Defining 'cls.version_args' has no effect. Please cleanup and remove this setting. puglint: Defining 'cls.version_re' has no effect. Please cleanup and remove this setting. puglint: Defining 'cls.version_requirement' has no effect. Please cleanup an...
Python
mit
benedfit/SublimeLinter-contrib-jade-lint,benedfit/SublimeLinter-contrib-pug-lint
805c6097b3dc7e7e2468235a9c28d159cb99f187
satchless/cart/__init__.py
satchless/cart/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .handler import AddToCartHandler add_to_cart_handler = AddToCartHandler('cart') if not getattr(settings, 'SATCHLESS_DEFAULT_CURRENCY', None): raise ImproperlyConfigured('You need to configure ' ...
class InvalidQuantityException(Exception): def __init__(self, reason, quantity_delta): self.reason = reason self.quantity_delta = quantity_delta def __str__(self): return self.reason
Add cart quantity exception, remove old handler
Add cart quantity exception, remove old handler
Python
bsd-3-clause
taedori81/satchless
0829ca1bb133841efd9ff1753384b0895c1be924
nightbus/utils.py
nightbus/utils.py
# Copyright 2017 Codethink Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
# Copyright 2017 Codethink Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
Fix crash when no commandline args are passed
Fix crash when no commandline args are passed Regression from 3513da19363b8b4564f199b469d13486996ede57
Python
apache-2.0
ssssam/nightbus,ssssam/nightbus
06ab217f49e00bd52c9f8b632db904e1ebe7256d
pycroft/helpers/date.py
pycroft/helpers/date.py
from datetime import timedelta from datetime import date def diff_month(d1: date, d2: date) -> int: """Calculate the difference in months ignoring the days If d1 > d2, the result is positive. """ return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d): next_month = d.repl...
from calendar import monthrange from datetime import date def diff_month(d1: date, d2: date) -> int: """Calculate the difference in months ignoring the days If d1 > d2, the result is positive. """ return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d: date) -> date: _, n...
Use builtin function to find last month
Use builtin function to find last month
Python
apache-2.0
agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft
c9efa5897426b6c1f8f0e99185e8b15878a9abd2
gallery/urls.py
gallery/urls.py
from django.conf.urls import url from . import views app_name = 'gallery' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<slug>[-\w]+)/$', views.GalleryView.as_view(), name='gallery'), url(r'^(?P<gallery_slug>[-\w]+)/(?P<slug>[-\w]+)/$', views.GalleryImageView.as_view(), na...
from django.urls import include, path from . import views app_name = 'gallery' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:slug>/', views.GalleryView.as_view(), name='gallery'), path('<slug:gallery_slug>/<slug:slug>/', views.GalleryImageView.as_view(), name='gallery_imag...
Move gallery urlpatterns to Django 2.0 preferred method
Move gallery urlpatterns to Django 2.0 preferred method
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
7f78484fbefc0c193668fffd03b38bf8523e89f6
pyecore/notification.py
pyecore/notification.py
class ENotifer(object): def notify(self, notification): notification.notifier = notification.notifier or self for listener in self._eternal_listener + self.listeners: listener.notifyChanged(notification) def enum(enumName, *listValueNames): """Clever implementation of an enum lik...
from enum import Enum, unique class ENotifer(object): def notify(self, notification): notification.notifier = notification.notifier or self for listener in self._eternal_listener + self.listeners: listener.notifyChanged(notification) @unique class Kind(Enum): ADD = 0 ADD_MANY...
Add better enumeration for Notification
Add better enumeration for Notification The previous 'Kind' enumeration for Notification were using a home-made-cooked way of dealing with enumeration. The code were got from an article from the http://sametmax.com/ website (great website by the way). This new version uses the python 3.4 enumeration module, but as thi...
Python
bsd-3-clause
aranega/pyecore,pyecore/pyecore
006423b8975fa9e9bc3758e5c2e82002f0838ca7
scripts/link-python-apt.py
scripts/link-python-apt.py
""" Make python-apt available in the Python virtual environment without using the system site-packages support built into Travis CI because this doesn't work for Python 3.4, 3.7 and PyPy. See the following failed build: https://travis-ci.org/xolox/python-deb-pkg-tools/builds/581437417 """ import os import sys from di...
""" Workaround to enable python-apt on Travis CI. Make python-apt available in the Python virtual environment without using the system site-packages support built into Travis CI because this doesn't work for Python 3.4, 3.7 and PyPy. See the following failed build: https://travis-ci.org/xolox/python-deb-pkg-tools/buil...
Change s/apt/apt_pkg/g (follow up to previous commit)
Change s/apt/apt_pkg/g (follow up to previous commit)
Python
mit
xolox/python-deb-pkg-tools,xolox/python-deb-pkg-tools
353728aba17695396c6167543e74181f9f853fdc
examples/template_render.py
examples/template_render.py
import django.template.loader import django.conf import sys sys.path.append('django_test') django.conf.settings.configure(INSTALLED_APPS=(), TEMPLATE_DIRS=('.', 'examples',)) for x in range(0,100): django.template.loader.render_to_string('template.html')
import django.template.loader import django.conf import sys, os os.chdir(os.path.dirname(__file__)) django.conf.settings.configure( INSTALLED_APPS=(), TEMPLATES=[{ "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ['.'] }], ) django.setup() for x in range(0,100): ...
Update template render example for Django 1.8+
Update template render example for Django 1.8+
Python
bsd-3-clause
joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument
5ef233bf3bb3bd1346bb64a9da2ed5542c0e40df
regparser/layer/meta.py
regparser/layer/meta.py
import re from regparser.layer.layer import Layer import settings class Meta(Layer): shorthand = 'meta' def __init__(self, tree, cfr_title, version, **context): super(Meta, self).__init__(tree, **context) self.cfr_title = cfr_title self.version = version def process(self, node):...
import re from regparser.layer.layer import Layer import settings class Meta(Layer): shorthand = 'meta' def __init__(self, tree, cfr_title, version, **context): super(Meta, self).__init__(tree, **context) self.cfr_title = cfr_title self.version = version def process(self, node):...
Use dictionary update instead of addition
Use dictionary update instead of addition
Python
cc0-1.0
eregs/regulations-parser,tadhg-ohiggins/regulations-parser,tadhg-ohiggins/regulations-parser,eregs/regulations-parser
e980aaf833b6f289069ee9ae9c2d3571ae297246
tools/publish_all_pkgs.py
tools/publish_all_pkgs.py
#!/usr/bin/env python # # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # # Upload all packages in pkg/ (other than a few that should be explicitly # exclu...
#!/usr/bin/env python # # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # # Upload all packages in pkg/ (other than a few that should be explicitly # exclu...
Stop publishing compiler_unsupported. Start publishing fixnum.
Stop publishing compiler_unsupported. Start publishing fixnum. R=sigmund@google.com Review URL: https://codereview.chromium.org//19757010 git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@25217 260f80e4-7a28-3924-810f-c04153c831b5
Python
bsd-3-clause
dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,...
9ff75ff858681665141650d4e1ef310265956f35
tools/workplace_status.py
tools/workplace_status.py
#! /usr/bin/env python3 # Note that this file should work in both Python 2 and 3. from __future__ import print_function from subprocess import Popen, PIPE dirty = Popen(["git", "diff-index", "--quiet", "HEAD"], stdout=PIPE).wait() != 0 commit_process = Popen(["git", "describe", "--tags", "--abbrev=0"], stdout=PIPE)...
#! /usr/bin/env python3 # Note that this file should work in both Python 2 and 3. from __future__ import print_function from subprocess import Popen, PIPE dirty = Popen(["git", "diff-index", "--quiet", "HEAD"], stdout=PIPE).wait() != 0 commit_process = Popen(["git", "describe", "--always", "--tags", "--abbrev=0"], ...
Make git describe --always return a value
Make git describe --always return a value This means that the latest commit will be stamped if there are no tags.
Python
apache-2.0
bazelbuild/bazel-watcher,bazelbuild/bazel-watcher,bazelbuild/bazel-watcher,bazelbuild/bazel-watcher
3681b5a485662656d6419d95ad89f1fbdb7a2a50
myuw/context_processors.py
myuw/context_processors.py
# Determins if the requesting device is a native hybrid app (android/ios) def is_hybrid(request): return { 'is_hybrid': 'HTTP_MYUW_HYBRID' in request.META }
# Determins if the requesting device is a native hybrid app (android/ios) def is_hybrid(request): return { 'is_hybrid': 'MyUW_Hybrid/1.0' in request.META['HTTP_USER_AGENT'] }
Update context processer to check for custom hybrid user agent.
Update context processer to check for custom hybrid user agent.
Python
apache-2.0
uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw
1fd43c6b87db9599c73b7cb26856e99404b2e0f7
corehq/apps/data_interfaces/tests/test_xform_management.py
corehq/apps/data_interfaces/tests/test_xform_management.py
from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest, QueryDict from django.test import TestCase, Client from corehq.apps.data_interfaces.views import XFormManagementView from corehq.apps.domain.shortcuts import create_domain from corehq.apps.users.models import WebUser ...
from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest, QueryDict from django.test import TestCase, Client from corehq.apps.data_interfaces.views import XFormManagementView from corehq.apps.domain.shortcuts import create_domain from corehq.apps.users.models import WebUser ...
Fix ES index setup in XFormManagementTest
Fix ES index setup in XFormManagementTest
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
ebce20c36007f5665d927b860a64f45de5f128c4
uptests/web/responding.py
uptests/web/responding.py
#!/usr/bin/env python import urllib2 import argparse import portend parser = argparse.ArgumentParser() parser.add_argument('host') parser.add_argument('port', type=int) args = parser.parse_args() portend.occupied(args.host, args.port, timeout=3) root = 'http://{host}:{port}/'.format(**vars(args)) urllib2.urlopen(ro...
#!/usr/bin/env python3 import urllib.request import argparse import portend parser = argparse.ArgumentParser() parser.add_argument('host') parser.add_argument('port', type=int) args = parser.parse_args() portend.occupied(args.host, args.port, timeout=3) root = 'http://{host}:{port}/'.format(**vars(args)) urllib.req...
Update uptest for Python 3
Update uptest for Python 3
Python
mit
yougov/librarypaste,yougov/librarypaste
56e3f571196bdc0ab8882f56ed66192d54ff8cad
gmt/clib/tests/test_functions.py
gmt/clib/tests/test_functions.py
""" Test the wrappers for the API functions """ import os from .. import create_session, call_module def test_create_session(): "Test that create_session is called without errors" session = create_session() assert session is not None def test_call_module(): "Run a psbasemap call to see if the modul...
""" Test the wrappers for the API functions """ import os from .. import create_session, call_module def test_create_session(): "Test that create_session is called without errors" session = create_session() assert session is not None def test_call_module(): "Run a psbasemap call to see if the modul...
Remove tmp file created by test
Remove tmp file created by test
Python
bsd-3-clause
GenericMappingTools/gmt-python,GenericMappingTools/gmt-python
c4d58ef971b850d3f201903bb6091d159241112f
histomicstk/features/__init__.py
histomicstk/features/__init__.py
from .ReinhardNorm import ReinhardNorm from .ReinhardSample import ReinhardSample __all__ = ( 'FeatureExtraction' )
__all__ = ( 'FeatureExtraction' )
Resolve import issue in color_normalization_test
Resolve import issue in color_normalization_test
Python
apache-2.0
DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK
c4278b404b313c4fa5fad67a5703b7368d1c4428
fileapi/tests/test_qunit.py
fileapi/tests/test_qunit.py
import os from django.conf import settings from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test.utils import override_settings from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriv...
import os from django.conf import settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test.utils import override_settings from django.utils.functional import empty from selenium import webdriver from selenium.webdriver.co...
Clear global state/caching handled by Django so the test passes when run in the full suite.
Clear global state/caching handled by Django so the test passes when run in the full suite.
Python
bsd-2-clause
mlavin/fileapi,mlavin/fileapi,mlavin/fileapi
4bf0c58f8c8349239352d6153899fd7858df3436
faker/compat.py
faker/compat.py
# Python 2/3 compat import sys if sys.version < '3': import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x
# Python 2/3 compat import sys if sys.version_info < (3, 0): import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x
Change Python version check to use sys.version_info
Change Python version check to use sys.version_info
Python
mit
deepthawtz/faker
4720809f31c559e14ca69f6205766265d1095f44
vk/__init__.py
vk/__init__.py
# coding=utf-8 from .auth import * from .groups import * from .messages import * from .users import *
# coding=utf-8 from .auth import * from .error import VKError from .groups import * from .messages import * from .users import *
Use `vk.VKError` instead of `vk.error.VKError`
Use `vk.VKError` instead of `vk.error.VKError`
Python
mit
sgaynetdinov/py-vkontakte
e57bd1eeb551cf05a220b18ec1e3fafa311d9d78
MetaTools/buildChangeLog.py
MetaTools/buildChangeLog.py
#! /usr/bin/env python import os, sys fontToolsDir = os.path.dirname(os.path.dirname(os.path.normpath( os.path.join(os.getcwd(), sys.argv[0])))) os.chdir(fontToolsDir) os.system("svn2cl -o Doc/ChangeLog https://fonttools.svn.sourceforge.net/svnroot/fonttools/trunk") print "done."
#! /usr/bin/env python import os, sys fontToolsDir = os.path.dirname(os.path.dirname(os.path.normpath( os.path.join(os.getcwd(), sys.argv[0])))) os.chdir(fontToolsDir) os.system("svn2cl -o Doc/ChangeLog https://svn.code.sf.net/p/fonttools/code/trunk") print "done."
Fix the location of the SVN repository
Fix the location of the SVN repository git-svn-id: 05b73559aeb8bace4cf49b5ea964569f1305eff8@618 4cde692c-a291-49d1-8350-778aa11640f8
Python
mit
fonttools/fonttools,googlefonts/fonttools
4c52e331052a2b5f11ce56b0a6c1b6e3d2f18cdf
partner_communication_switzerland/controllers/b2s_image.py
partner_communication_switzerland/controllers/b2s_image.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 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 __manifest__.py...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 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 __manifest__.py...
Revert bad renaming of route url parameter
Revert bad renaming of route url parameter
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland
5a680d25a5e5a697440f17639d1a0617b903aa06
opps/__init__.py
opps/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 0, 1) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"BSD"...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf import settings VERSION = (0, 0, 1) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googl...
Add installed app on opps init
Add installed app on opps init
Python
mit
jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps
991f37a5946f2fdf821ab7de367f3ced7b68a635
segmentation/segment_pool/signals.py
segmentation/segment_pool/signals.py
# -*- coding: utf-8 -*- from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.core.exceptions import ImproperlyConfigured from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered from .segment_pool import segment_pool @receiver(post_save) def regi...
# -*- coding: utf-8 -*- from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.core.exceptions import ImproperlyConfigured from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered from .segment_pool import segment_pool from ..models import SegmentBas...
Use a broad-brush filter for the signal handlers
Use a broad-brush filter for the signal handlers
Python
bsd-3-clause
aldryn/aldryn-segmentation,aldryn/aldryn-segmentation
5ad09d329b331c4c50a192a76b1c450e6340f508
distarray/core/tests/test_distributed_array_protocol.py
distarray/core/tests/test_distributed_array_protocol.py
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTes...
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTes...
Test keys and values separately.
Test keys and values separately.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,RaoUmer/distarray,enthought/distarray
44ef488bbe25576ba25ca5855b726fa16fffa8bc
fireplace/cards/blackrock/collectible.py
fireplace/cards/blackrock/collectible.py
from ..utils import * ## # Spells # Dragon's Breath class DragonsBreath: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn
from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] ## # Spells # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn
Implement Flamewaker and correct Dragon's Breath id
Implement Flamewaker and correct Dragon's Breath id
Python
agpl-3.0
jleclanche/fireplace,Ragowit/fireplace,butozerca/fireplace,amw2104/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,liujimj/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,liujimj/fireplace,butozerca/fireplace,NightKev/fireplace,Meerkov/fi...
f9ffd5021f8af96df503c8a2743e97c8f1a17be0
infupy/backends/common.py
infupy/backends/common.py
def printerr(msg, e=''): print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _ev...
def printerr(msg, e=''): msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(sel...
Add marker to indicate backend error
Add marker to indicate backend error
Python
isc
jaj42/infupy
55c24a4e47dfd6eab1dcceef8989a2a326322a14
osmABTS/trips.py
osmABTS/trips.py
""" Trip generation =============== """
""" Trip generation =============== This module can be roughtly devided into two parts, the trip description and trip generation. The trip description part contains mostly class definitions that can be used to describe kinds of trips, while the trip generation contains the main driver function to generate a large list...
Implement the trip description classes
Implement the trip description classes And a default list for trips has also been written.
Python
mit
tschijnmo/osmABTS
dc8099d10028266411c928befe9c690fe75ff391
tools/bundle.py
tools/bundle.py
#!/usr/bin/env python import os import sys import glob import getopt def file_list(path): files = [] if os.path.isfile(path): return [path] for f in os.listdir(path): new_dir = os.path.join(path, f) if os.path.isdir(new_dir) and not os.path.islink(new_dir): files.extend(file_list(new_dir)) ...
#!/usr/bin/env python import os import sys import glob import getopt def file_list(path): files = [] if os.path.isfile(path): return [path] for f in os.listdir(path): new_dir = path + '/' + f if os.path.isdir(new_dir) and not os.path.islink(new_dir): files.extend(file_list(new_dir)) else...
Stop using os.path.join, because Visual Studio can actually handle forward slash style paths, and the os.path method was creating mixed \\ and / style paths, b0rking everything.
Stop using os.path.join, because Visual Studio can actually handle forward slash style paths, and the os.path method was creating mixed \\ and / style paths, b0rking everything.
Python
apache-2.0
cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/r...
cb2a9032e1ffef5020b24a28079ecc127cc178b7
comparch/__init__.py
comparch/__init__.py
from .implicit import implicit from .registry import ClassRegistry, Registry from .lookup import Lookup, CachedLookup
from .implicit import implicit from .registry import ClassRegistry, Registry from .lookup import Lookup, CachedLookup from .interface import Interface
Include Interface in public API.
Include Interface in public API.
Python
bsd-3-clause
taschini/reg,morepath/reg
f1d05060356f0bb31cc418c1d4abca9438c39d86
km3pipe/tests/test_srv.py
km3pipe/tests/test_srv.py
# Filename: test_srv.py # pylint: disable=locally-disabled,C0111,R0904,C0103 from km3pipe.testing import TestCase, patch from km3pipe.dataclasses import Table from km3pipe.srv import srv_event __author__ = "Tamas Gal" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license_...
# Filename: test_srv.py # pylint: disable=locally-disabled,C0111,R0904,C0103 from km3pipe.testing import TestCase, patch from km3pipe.dataclasses import Table from km3pipe.srv import srv_event __author__ = "Tamas Gal" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license_...
Add rba url, since it's normally taken from the config
Add rba url, since it's normally taken from the config
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
b844b5ea9f7df47a9c000699b6b2636fa16a20cd
lfc/context_processors.py
lfc/context_processors.py
# lfc imports import lfc.utils from django.conf import settings from django.utils import translation def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE return { "PORTAL" : lfc.utils.get_portal(), ...
# lfc imports import lfc.utils from django.conf import settings from django.utils import translation def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE is_default_language = default_language == current_la...
Return correct language for using within links
Improvement: Return correct language for using within links
Python
bsd-3-clause
diefenbach/django-lfc,diefenbach/django-lfc,diefenbach/django-lfc
435fce76241d41eaffaf63bbd948eb306806d8f0
microdash/settings/production.py
microdash/settings/production.py
import os import dj_database_url from microdash.settings.base import * env = os.getenv PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) # settings is one directory up now here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x) SECRET_KEY = env('SECRET_KEY') DATABASES = {'default': dj_database_url.config(de...
import os import dj_database_url from microdash.settings.base import * env = os.getenv PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) # settings is one directory up now here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x) SECRET_KEY = env('SECRET_KEY') DATABASES = {'default': dj_database_url.config(de...
Read settings from the environment.
Read settings from the environment.
Python
bsd-3-clause
alfredo/microdash,alfredo/microdash
9909fe549753d13355552c7462f16c42908d4b21
ligand/urls.py
ligand/urls.py
from django.conf.urls import url from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from ligand.views import * urlpatterns = [ url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'), url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, ...
from django.conf.urls import url from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from ligand.views import * urlpatterns = [ url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'), url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, ...
Add caching to ligand statistics
Add caching to ligand statistics
Python
apache-2.0
cmunk/protwis,protwis/protwis,cmunk/protwis,cmunk/protwis,protwis/protwis,cmunk/protwis,protwis/protwis
281208f9ecfa3f5f5028df75fff86f1cdb752487
jasylibrary.py
jasylibrary.py
#import os, json #from jasy.core.Util import executeCommand #import jasy.core.Console as Console #import urllib.parse # Little helper to allow python modules in current jasylibrarys path import sys, os.path, inspect filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath...
#import os, json #from jasy.core.Util import executeCommand #import jasy.core.Console as Console #import urllib.parse # Little helper to allow python modules in current jasylibrarys path import sys, os.path, inspect filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath...
Add support for part loading
Add support for part loading
Python
mit
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
b4ce232f050de073572f64c04b170a2e790fdc24
nefertari_mongodb/serializers.py
nefertari_mongodb/serializers.py
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoder(_JSONEncoder): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj)...
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoderMixin(object): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) ...
Refactor encoders to have base class
Refactor encoders to have base class
Python
apache-2.0
brandicted/nefertari-mongodb,ramses-tech/nefertari-mongodb
d726efa1116f95ced28994c7c6bbcfe4cf703b05
wavvy/views.py
wavvy/views.py
from wavvy import app from flask import Flask, url_for, render_template, request, session, escape @app.route('/hello') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name) @app.route('/') def index(): if session.get('logged_in', False): return 'Logged in ...
from wavvy import app from flask import Flask, url_for, render_template, request, session, escape def clear_session(s): if 'username' in s: del s['username'] s['logged_in'] = False @app.route('/hello') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=na...
Generalize the logout a bit
Generalize the logout a bit This is on the road to removing auth from this file.
Python
mit
john-patterson/wavvy,john-patterson/wavvy
69a6ced2bb923c6a77c74443e8892cdba550651e
pyramda/iterable/reject.py
pyramda/iterable/reject.py
from pyramda.function.curry import curry from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(p, xs))...
from pyramda.function.curry import curry from pyramda.logic import complement from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ ret...
Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates
Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates
Python
mit
jackfirth/pyramda
78af31feb8ac731eda18a5fff8075bb7dde90dde
scripts/test_deployment.py
scripts/test_deployment.py
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == ...
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == ...
Use API route in promotion tests
Use API route in promotion tests
Python
mit
jacebrowning/memegen,jacebrowning/memegen
d6432aa912f6d654f45c9bbfd27df46529816caf
rakuten/apis/travel_api.py
rakuten/apis/travel_api.py
import requests from .api_exception import RakutenApiException from .base_api import BaseApi class TravelApi(BaseApi): def __init__(self, options): super(TravelApi, self).__init__(options) def vacant_hotel_search(self, **kwargs): params = self._dict_to_camel_case(kwargs) params.update(...
import requests from .api_exception import RakutenApiException from .base_api import BaseApi class TravelApi(BaseApi): def __init__(self, options): super(TravelApi, self).__init__(options) self._default_params['datumType'] = 1 def vacant_hotel_search(self, **kwargs): params = self._dic...
Change default format to normal longitude/latitude.
Change default format to normal longitude/latitude.
Python
mit
claudetech/python_rakuten
76d45475090144903ec3421491dc5f998f67e236
mqueue/apps.py
mqueue/apps.py
import importlib from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" verbose_name = _(u"Events queue") def ready(self): # models registration from settings from django.conf import settings from mq...
import importlib from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" verbose_name = _(u"Events queue") def ready(self): # models registration from settings from django.conf import settings from mq...
Add error handling on module import at initilization time
Add error handling on module import at initilization time
Python
mit
synw/django-mqueue,synw/django-mqueue,synw/django-mqueue
32a238838778fb74ee269b891feca59048e78a3a
api/management/commands/update_account_center_cache.py
api/management/commands/update_account_center_cache.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import F, Q from api import models def update_account_center_cache(opt={}): print '# Update account center' accounts = models.Account.objects.filter(center__isnull=False).select_related('center', 'center__card') for acc...
from django.core.management.base import BaseCommand, CommandError from django.db.models import F, Q from api import models def update_account_center_cache(opt={}): print '# Update account center' accounts = models.Account.objects.filter(center__isnull=False, center_card_id__isnull=True).select_related('center'...
Allow to restart the account center cache script without reloading everything
Allow to restart the account center cache script without reloading everything
Python
apache-2.0
rdsathene/SchoolIdolAPI,dburr/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,dburr/SchoolIdolAPI,dburr/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,rdsathene/SchoolIdolAPI,rdsathene/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI
61465e1df2f43d2d82b40ddb15c17bee4ddcccda
src/poliastro/ephem.py
src/poliastro/ephem.py
import numpy as np from scipy.interpolate import interp1d from astropy import units as u from astropy.time import Time from poliastro.bodies import Moon from poliastro.twobody.orbit import Orbit from poliastro.coordinates import transform from astropy.coordinates import ICRS, GCRS def build_ephem_interpolant(body, ...
import numpy as np from scipy.interpolate import interp1d from astropy import units as u from astropy.time import Time from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation def build_ephem_interpolant(body, period, t_span, rtol=1e-5): h = (period * rtol).to(u.day).value t_...
Fix 3rd body tests for Moon, simplify interpolant code
Fix 3rd body tests for Moon, simplify interpolant code
Python
mit
Juanlu001/poliastro,Juanlu001/poliastro,newlawrence/poliastro,Juanlu001/poliastro,newlawrence/poliastro,poliastro/poliastro,newlawrence/poliastro
081dcb1a6f3531249f8948b019d8fdc4175dbe61
makerscience_profile/api.py
makerscience_profile/api.py
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileRe...
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileRe...
Add fullname in REST response
Add fullname in REST response
Python
agpl-3.0
atiberghien/makerscience-server,atiberghien/makerscience-server
4b097d7d343523c99b50dc910b62bf29eb7c4081
vint/linting/policy/prohibit_implicit_scope_variable.py
vint/linting/policy/prohibit_implicit_scope_variable.py
from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility @register_policy class ProhibitImplicitScopeVariable(...
from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility @register_policy class ProhibitImplicitScopeVariable(...
Replace try..except with get_policy_option call
Replace try..except with get_policy_option call
Python
mit
RianFuro/vint,Kuniwak/vint,Kuniwak/vint,RianFuro/vint
ef102617e5d73b32c43e4e9422a19917a1d3d717
molo/polls/wagtail_hooks.py
molo/polls/wagtail_hooks.py
from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_a...
from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_a...
Add M&E Expert to polls entries permissions
Add M&E Expert to polls entries permissions
Python
bsd-2-clause
praekelt/molo.polls,praekelt/molo.polls
932606e41fa5289551a026ae993ececbd117ca7d
openedx/core/djangoapps/appsembler/tpa_admin/serializers.py
openedx/core/djangoapps/appsembler/tpa_admin/serializers.py
import json from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig from rest_framework import serializers class JSONSerializerField(serializers.Field): """ Serializer for JSONField -- required to make field writable""" def to_internal_value(self, data): return json.dumps(data) ...
import json from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData from rest_framework import serializers class JSONSerializerField(serializers.Field): """ Serializer for JSONField -- required to make field writable""" def to_internal_value(self, data): return js...
Add metadata ready field to IdP serializer
Add metadata ready field to IdP serializer
Python
agpl-3.0
appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform
d1941980e48e738eaf6231a630595d85eeadf390
readthedocs/config/models.py
readthedocs/config/models.py
"""Models for the response of the configuration object.""" from __future__ import division, print_function, unicode_literals from readthedocs.config.utils import to_dict class Base(object): """ Base class for every configuration. Each inherited class should define its attibutes in the `__slots__` ...
"""Models for the response of the configuration object.""" from __future__ import division, print_function, unicode_literals from readthedocs.config.utils import to_dict class Base(object): """ Base class for every configuration. Each inherited class should define its attibutes in the `__slots__` ...
Add explanation about using __slots__
Add explanation about using __slots__
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
9a94e9e61a7bb1680265692eb7cdf926842aa766
streamline/__init__.py
streamline/__init__.py
from .base import RouteBase, NonIterableRouteBase from .template import TemplateRoute, XHRPartialRoute, ROCARoute from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute __version__ = '1.0' __author__ = 'Outernet Inc' __all__ = ( RouteBase, NonIterableRouteBase, TemplateRoute, XHRPartialR...
from .base import RouteBase, NonIterableRouteBase from .template import TemplateRoute, XHRPartialRoute, ROCARoute from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute __version__ = '1.0' __author__ = 'Outernet Inc' __all__ = ( 'RouteBase', 'NonIterableRouteBase', 'TemplateRoute', 'XHRP...
Fix __all__ using objects instead of strings
Fix __all__ using objects instead of strings Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is>
Python
bsd-2-clause
Outernet-Project/bottle-streamline
325ca5357af3b3c769b9d80d5452aae41cc2ba4f
src/utils/versioning.py
src/utils/versioning.py
''' Backup es index to S3 and refresh ''' from tornado.ioloop import IOLoop from web.api.es import ESQuery async def backup_and_refresh(): ''' Run periodically in the main event loop ''' def sync_func(): esq = ESQuery() esq.backup_all(aws_s3_bucket='smartapi') ...
''' Backup es index to S3 and refresh ''' import logging from tornado.ioloop import IOLoop from web.api.es import ESQuery async def backup_and_refresh(): ''' Run periodically in the main event loop ''' def sync_func(): esq = ESQuery() try: esq.backup_al...
Make backup failures not disruptive
Make backup failures not disruptive
Python
mit
Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI
76e048b581de16fbcbd270f6e6faa4ba11b27f19
s3img_magic.py
s3img_magic.py
from IPython.display import Image import boto def s3img(uri): if uri.startswith('s3://'): uri = uri[5:] bucket_name, key_name = uri.split('/', 1) conn = boto.connect_s3() bucket = conn.get_bucket(bucket_name) key = bucket.get_key(key_name) data = key.get_contents_as_string() ret...
from IPython.display import Image import boto def parse_s3_uri(uri): if uri.startswith('s3://'): uri = uri[5:] return uri.split('/', 1) def get_s3_key(uri): bucket_name, key_name = parse_s3_uri(uri) conn = boto.connect_s3() bucket = conn.get_bucket(bucket_name) return bucket.get_k...
Refactor S3 interactions for reusability
Refactor S3 interactions for reusability
Python
mit
AustinRochford/s3img-ipython-magic,AustinRochford/s3img-ipython-magic
d301a0635578550ededd1bca7ac34e841366b0ef
devito/foreign/__init__.py
devito/foreign/__init__.py
""" The ``foreign`` Devito backend is meant to be used by codes that don't run Python natively. This backend is only capable of generating and compiling kernels; however, kernels must be executed explicitly from outside Devito. Further, with the ``foreign`` backed, Devito doesn't allocate any data. """ # The following...
""" The ``foreign`` Devito backend is meant to be used by codes that don't run Python natively. This backend is only capable of generating and compiling kernels; however, kernels must be executed explicitly from outside Devito. Further, with the ``foreign`` backed, Devito doesn't allocate any data. """ # The following...
Add leftover import due to disfunctional testing
Add leftover import due to disfunctional testing
Python
mit
opesci/devito,opesci/devito
18aafd9218efe636c6efb75980b2014d43b6736e
tests/test_conditionals.py
tests/test_conditionals.py
import pytest from thinglang.runner import run def test_simple_conditionals(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") if "dog" eq "cat" Output.write("dog is cat") """).output == """dog is dog""".strip()
import pytest from thinglang.runner import run def test_simple_conditionals(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") if "dog" eq "cat" Output.write("dog is cat") """).output == """dog is dog""".strip() def test_uncon...
Test for unconditional else branches
Test for unconditional else branches
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
47612ac76be1f0d2929d470f34298117fa843d6f
tests/test_py3/__init__.py
tests/test_py3/__init__.py
""" For tests that require python 3 only syntax. """ import six if six.PY2: # don't import this package on python2 def load_tests(loader, standard_tests, pattern): return standard_tests
""" For tests that require python 3 only syntax. """ import sys if sys.version_info < (3, 6): # These tests require annotations def load_tests(loader, standard_tests, pattern): return standard_tests
Fix python 3.5 test switching.
Fix python 3.5 test switching.
Python
mit
tim-mitchell/pure_interface
da8efb34fe00f4c625c6ab7d3cf5651193d972d0
mopidy/backends/__init__.py
mopidy/backends/__init__.py
import logging import time from mopidy.exceptions import MpdNotImplemented from mopidy.models import Playlist logger = logging.getLogger('backends.base') class BaseBackend(object): current_playlist = None library = None playback = None stored_playlists = None uri_handlers = [] class BaseCurrentP...
import logging import time from mopidy.exceptions import MpdNotImplemented from mopidy.models import Playlist logger = logging.getLogger('backends.base') class BaseBackend(object): current_playlist = None library = None playback = None stored_playlists = None uri_handlers = [] class BaseCurrentP...
Add add method to BaseCurrentPlaylistController
Add add method to BaseCurrentPlaylistController
Python
apache-2.0
priestd09/mopidy,jcass77/mopidy,mokieyue/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,mopidy/mopidy,bencevans/mopidy,tkem/mopidy,quartz55/mopidy,rawdlite/mopidy,tkem/mopidy,quartz55/mopidy,glogiotatidis/mopidy,SuperStarPL/mopidy,adamcik/mopidy,woutervanwijk/mopidy,bencevans/mopidy,pacificIT/mopidy,hkariti/mopidy,bacontext...
4a07beaf945ce26186fa80f3114cb4c7dc0dd697
tests/app/test_rest.py
tests/app/test_rest.py
import pytest from flask import json, url_for class WhenAccessingSiteInfo(object): def it_shows_info(self, client, db): response = client.get( url_for('.get_info') ) query = 'SELECT version_num FROM alembic_version' version_from_db = db.session.execute(query).fetchone...
import pytest from flask import json, url_for class WhenAccessingSiteInfo(object): def it_shows_info(self, client, db): response = client.get( url_for('.get_info') ) query = 'SELECT version_num FROM alembic_version' version_from_db = db.session.execute(query).fetchone...
Add test for info when db error
Add test for info when db error
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
149ca57fabad4430b22af08c88d8df6fbcc6dfc2
statictemplate/tests.py
statictemplate/tests.py
# -*- coding: utf-8 -*- from StringIO import StringIO from django.conf import settings from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unit...
# -*- coding: utf-8 -*- from StringIO import StringIO from django.conf import settings from django.http import HttpResponseRedirect from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands....
Add test for meddling middleware
Add test for meddling middleware
Python
bsd-3-clause
bdon/django-statictemplate,ojii/django-statictemplate,yakky/django-statictemplate
cd00388bdc4c1963ac8ff81f9b7132ba32272fc8
adwords_client/__init__.py
adwords_client/__init__.py
__version__ = '17.07' # Date based versioning # See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
""" Copyright 2017 GetNinjas Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writ...
Print license on each import
Print license on each import
Python
apache-2.0
getninjas/adwords-client
3188e993ccbd8ae49c43f21ccb35947364030bcd
seabird/test/test_rules.py
seabird/test/test_rules.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check the rules """ import os import pkg_resources import json import re import seabird def test_load_available_rules(): """ Try to read all available rules https://github.com/castelao/seabird/issues/7 """ rules_dir = 'rules' rule_files = pk...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check the rules """ import os import pkg_resources import json import re import seabird def test_load_available_rules(): """ Try to read all available rules https://github.com/castelao/seabird/issues/7 """ rules_dir = 'rules' rule_files = pk...
Test all rules but refnames.
Test all rules but refnames.
Python
bsd-3-clause
castelao/seabird
f3eb6cbc0f518ed8ec6098d3dfdd205ed734022c
eval_kernel/eval_kernel.py
eval_kernel/eval_kernel.py
from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} ...
from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} ...
Return python eval instead of printing it
Return python eval instead of printing it
Python
bsd-3-clause
Calysto/metakernel
a7be9a07a7f2d2556d6c93326098a00e0b2c67a8
tests/api/test_licenses.py
tests/api/test_licenses.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- """pytest Licenses API wrapper tests and fixtures.""" import pytest import ciscosparkapi # Helper Functions def get_list_of_licenses(api, orgId=None, max=None): return api.licenses.list(orgId=orgId, max=max) def get_license_by_id(api, licenseId): return api.licenses.get(licenseI...
Add tests and fixtures for the Licenses API wrapper
Add tests and fixtures for the Licenses API wrapper
Python
mit
jbogarin/ciscosparkapi
4139ff0361c499f5b9bc48b9ac6013b5bc61e955
test/test_exceptions.py
test/test_exceptions.py
import unittest from pymodbus3.exceptions import * class SimpleExceptionsTest(unittest.TestCase): """ This is the unittest for the pymodbus3.exceptions module """ def setUp(self): """ Initializes the test environment """ self.exceptions = [ ModbusException("bad base"), ...
import unittest from pymodbus3.exceptions import * class SimpleExceptionsTest(unittest.TestCase): """ This is the unittest for the pymodbus3.exceptions module """ def setUp(self): """ Initializes the test environment """ self.exceptions = [ ModbusException("bad base"), ...
Remove test of built-in "NotImplementedError" exception.
Remove test of built-in "NotImplementedError" exception.
Python
bsd-3-clause
gregorschatz/pymodbus3,uzumaxy/pymodbus3
beb7d06bd9f7b65ad3f25184ee05b808f893cfda
flatland/__init__.py
flatland/__init__.py
"""Schemas for structured data.""" from flatland.exc import AdaptationError from flatland.schema import Array, Boolean, Compound, Constrained, Container,\ Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\ Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\ Pr...
"""Schemas for structured data.""" from flatland.exc import AdaptationError from flatland.schema import Array, Boolean, Compound, Constrained, Container,\ Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\ Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\ Pr...
Fix version string so that we can install with pip/setuptools
Fix version string so that we can install with pip/setuptools
Python
mit
wheeler-microfluidics/flatland-fork
540bfff4a0622c3d9a001c09f0c39e65b29e1a0c
mrbelvedereci/build/management/commands/metaci_scheduled_jobs.py
mrbelvedereci/build/management/commands/metaci_scheduled_jobs.py
from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from scheduler.models import RepeatableJob class Command(BaseCommand): help = 'Returns the API token for a given username. If one does not exist, a token is first created.' def handle(self, *args, **options): ...
from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from scheduler.models import RepeatableJob class Command(BaseCommand): help = 'Returns the API token for a given username. If one does not exist, a token is first created.' def handle(self, *args, **options): ...
Add job id and enable/disabled status if the job already exists
Add job id and enable/disabled status if the job already exists
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
2d9c40ee9d41ef3e9c7d91410e410f1e764d8eb1
pdc/apps/release/migrations/0011_auto_20170912_1108.py
pdc/apps/release/migrations/0011_auto_20170912_1108.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('release', '0010_release_sigkey'), ] operations = [ migrations.CreateModel( name='CPE', fields=[ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('release', '0010_release_sigkey'), ] operations = [ migrations.CreateModel( name='CPE', fields=[ ...
Fix migrating CPE field from string to ID
Fix migrating CPE field from string to ID JIRA: PDC-2228
Python
mit
product-definition-center/product-definition-center,release-engineering/product-definition-center,release-engineering/product-definition-center,product-definition-center/product-definition-center,release-engineering/product-definition-center,product-definition-center/product-definition-center,release-engineering/produc...
8929957d854f66c738c773bd629d9c6f18aa66a2
sports/admin.py
sports/admin.py
from django.contrib import admin from .models import (Sport, Match, Session, CancelledSession) @admin.register(Sport) class SportAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Match) class Match...
from django.contrib import admin from .models import (Sport, Match, Session, CancelledSession) class SessionInline(admin.StackedInline): model = Session extra = 0 @admin.register(Sport) class SportAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} inlines = [SessionInline,] class ...
Move Session to Sport as an inline.
Move Session to Sport as an inline.
Python
mit
QSchulz/sportassociation,QSchulz/sportassociation,QSchulz/sportassociation
b739da9bcbc7c1f1fc95a04e1e12a44f23d0a1de
tests/test_extension.py
tests/test_extension.py
import unittest from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', config)...
import mock, unittest from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', c...
Test extension with mock registry
Test extension with mock registry
Python
apache-2.0
kingosticks/mopidy-spotify,mopidy/mopidy-spotify,jodal/mopidy-spotify
b6389de5f531fa49e911b344cbaea29599260c82
src/tests/test_cleanup_marathon_orphaned_containers.py
src/tests/test_cleanup_marathon_orphaned_containers.py
#!/usr/bin/env python import cleanup_marathon_orphaned_images # These should be left running mesos_deployed_old = { 'Names': ['/mesos-deployed-old', ], } mesos_undeployed_young = { 'Names': ['/mesos-undeployed-young', ], } nonmesos_undeployed_old = { 'Names': ['/nonmesos-undeployed-old', ], } # These sho...
#!/usr/bin/env python import cleanup_marathon_orphaned_images # These should be left running mesos_deployed_old = { 'Names': ['/mesos-deployed-old', ], } mesos_undeployed_young = { 'Names': ['/mesos-undeployed-young', ], } nonmesos_undeployed_old = { 'Names': ['/nonmesos-undeployed-old', ], } # These sho...
Clarify intent and fail fast
Clarify intent and fail fast
Python
apache-2.0
Yelp/paasta,somic/paasta,gstarnberger/paasta,somic/paasta,gstarnberger/paasta,Yelp/paasta
04e253ef897197bd9550d00870583c67db7f1d0a
tests/test_bmipytest.py
tests/test_bmipytest.py
from bmi_tester.bmipytest import load_component entry_point = 'pymt_hydrotrend.bmi:Hydrotrend' module_name, cls_name = entry_point.split(":") def test_component_is_string(): component = load_component(entry_point) assert isinstance(component, str) def test_component_is_classname(): component = load_co...
from bmi_tester.bmipytest import load_component entry_point = 'os:getcwd' module_name, cls_name = entry_point.split(":") def test_component_is_string(): component = load_component(entry_point) assert isinstance(component, str) def test_component_is_classname(): component = load_component(entry_point) ...
Use a package in base Python distro for test
Use a package in base Python distro for test I was too ambitious -- pymt_hydrotrend isn't a default on Windows. Using os.getcwd() should be less fragile.
Python
mit
csdms/bmi-tester
052905dbff6f91740c8f8b9cb5e06aa07b06a186
tests/test_spicedham.py
tests/test_spicedham.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_spicedham ---------------------------------- Tests for `spicedham` module. """ import unittest from spicedham import spicedham class TestSpicedham(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tear...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_spicedham ---------------------------------- Tests for `spicedham` module. """ import os import json import tarfile import unittest from spicedham import SpicedHam class TestSpicedham(unittest.TestCase): def setUp(self, tarball='corpus.tar.gz', test_data_...
Add tests based off of the corpus.
Add tests based off of the corpus.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
09268200fcc1ae21206659ae261c488eb1567071
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, ...
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, ...
Add '/admin' url_prefix to main blueprint
Add '/admin' url_prefix to main blueprint Also attaches the authentication check to main blueprint instead of the app itself. This means we can use other blueprints for status and internal use that don't require authentication. One important note: before_request must be added before registering the blueprint, otherwi...
Python
mit
alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace...
39fbce2a0e225591423f9b2d1edd111822063466
app/core/api.py
app/core/api.py
from flask import jsonify, request from ..main import app @app.route('/api/ip') def api_ip(): return jsonify({'Success': True, 'ipAddress': get_client_ip()}) def get_client_ip(): return request.headers.get('X-Forwarded-For') or request.remote_addr
from flask import jsonify, request from ..main import app @app.route('/api/ip') def api_ip(): """Return client IP""" return api_reply({'ipAddress': get_client_ip()}) def get_client_ip(): """Return the client x-forwarded-for header or IP address""" return request.headers.get('X-Forwarded-For') or req...
Add a standard API reply interface
Add a standard API reply interface
Python
mit
jniedrauer/jniedrauer.com,jniedrauer/jniedrauer.com,jniedrauer/jniedrauer.com
b56eccf32fc7fe80405350fd122d3d257aa55788
runtests.py
runtests.py
"""Alternate way of running the unittests, for Python 2.5 or Windows.""" __author__ = 'Beech Horn' import sys import unittest def suite(): mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread'] test_mods = ['%s_test' % name for name in mods] ndb = __import__('ndb', fromlist=test_mods, ...
"""Alternate way of running the unittests, for Python 2.5 or Windows.""" __author__ = 'Beech Horn' import sys import unittest def suite(): mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread'] test_mods = ['%s_test' % name for name in mods] ndb = __import__('ndb', fromlist=test_mods, ...
Simplify and improve -v/-q handling.
Simplify and improve -v/-q handling.
Python
apache-2.0
GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python
a485c2b107987cfab334137cfa4031c366617ccd
runtests.py
runtests.py
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitema...
#!/usr/bin/env python from os.path import dirname, abspath import sys import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitemap test ...
Support Django 1.7 in test runner.
Support Django 1.7 in test runner.
Python
mit
extertioner/django-localeurl,carljm/django-localeurl
039768aeacbf2ad3ca3d498d035f2fcf1163ff8f
pi_gpio/meta.py
pi_gpio/meta.py
from flask.ext.restful import Resource, marshal class BasicResource(Resource): def __init__(self): super(BasicResource, self).__init__() def response(self, data, code): return marshal(data, self.fields), code
from flask.ext.restful import Resource, marshal, reqparse class BasicResource(Resource): def __init__(self): super(BasicResource, self).__init__() self.parser = reqparse.RequestParser() def response(self, data, code): return marshal(data, self.fields), code
Add parser to basic resource
Add parser to basic resource
Python
mit
thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server
991725f873909a268d12cade08de85026b34f5a3
csunplugged/tests/infrastructure/test_resource_generation.py
csunplugged/tests/infrastructure/test_resource_generation.py
"""Tests for resource generation.""" import os import re from django.core import management from tests.BaseTestWithDB import BaseTestWithDB from resources.models import Resource class ResourceGenerationTest(BaseTestWithDB): """Tests for resource generation.""" def test_all_resources_are_generated(self): ...
"""Tests for resource generation.""" import os import re import copy from django.core import management from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES from tests.BaseTestWithDB import BaseTestWithDB from resources.models import Resource class ResourceGenerationTest(BaseTestWithDB): """Tests for ...
Fix test for checking resource PDF generation
Fix test for checking resource PDF generation
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
c3e2c6f77dffc2ff5874c1bb495e6de119800cf4
rx/core/observable/merge.py
rx/core/observable/merge.py
import rx from rx import operators as ops from rx.core import Observable def _merge(*args) -> Observable: """Merges all the observable sequences into a single observable sequence. 1 - merged = rx.merge(xs, ys, zs) 2 - merged = rx.merge([xs, ys, zs]) Returns: The observable sequence that...
from typing import Iterable, Union import rx from rx import operators as ops from rx.core import Observable def _merge(*args: Union[Observable, Iterable[Observable]]) -> Observable: """Merges all the observable sequences into a single observable sequence. 1 - merged = rx.merge(xs, ys, zs) 2 - merge...
Fix typing and accept iterable instead of list
Fix typing and accept iterable instead of list
Python
mit
ReactiveX/RxPY,ReactiveX/RxPY
595555433d7495ab54cdeb26d37cb2bc6c58f830
plyades/core.py
plyades/core.py
import datetime import numpy as np class Epoch(datetime.datetime): def get_jd(self, epoch=2000): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.seco...
import datetime import numpy as np class Epoch(datetime.datetime): @property def jd(self): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.second/60...
Change julian date to be a property.
Change julian date to be a property.
Python
mit
helgee/plyades
d120e092c2e6422e63500666947aea43891908c2
progress_bar.py
progress_bar.py
import sys import time index = 0 for url_dict in range(100): time.sleep(0.1) index += 1 percentual = "%.2f%%" % index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index, ' ' * (100-index), percentual)) sys.st...
import sys import time import math n_messages = 650 for index, url_dict in enumerate(range(n_messages)): index += 1 time.sleep(0.01) progress_index = math.floor(index/n_messages*100) percentual = "%.2f%%" % progress_index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index, ...
Make it work properly with every number
Make it work properly with every number
Python
mit
victorpantoja/python-progress-bar
33e1c781b0e430cb1e0df19d02ed06a193f9d202
waterbutler/identity.py
waterbutler/identity.py
import asyncio from waterbutler import settings @asyncio.coroutine def fetch_rest_identity(params): response = yield from aiohttp.request( 'get', settings.IDENTITY_API_URL, params=params, headers={'Content-Type': 'application/json'}, ) # TOOD Handle Errors nicely if r...
import asyncio import aiohttp from waterbutler import settings IDENTITY_METHODS = {} def get_identity_func(name): try: return IDENTITY_METHODS[name] except KeyError: raise NotImplementedError('No identity getter for {0}'.format(name)) def register_identity(name): def _register_identi...
Make use of a register decorator
Make use of a register decorator
Python
apache-2.0
CenterForOpenScience/waterbutler,kwierman/waterbutler,TomBaxter/waterbutler,rafaeldelucena/waterbutler,Ghalko/waterbutler,RCOSDP/waterbutler,hmoco/waterbutler,felliott/waterbutler,rdhyee/waterbutler,Johnetordoff/waterbutler,icereval/waterbutler,chrisseto/waterbutler,cosenal/waterbutler
b33b063e49b394265bc890f6d3b39da08e355416
blogs/tests/test_parser.py
blogs/tests/test_parser.py
from unittest import TestCase from ..parser import get_all_entries from .utils import get_test_rss_path class BlogParserTest(TestCase): def setUp(self): self.test_file_path = get_test_rss_path() self.entries = get_all_entries("file://{}".format(self.test_file_path)) def test_entries(self): ...
import datetime import unittest from ..parser import get_all_entries from .utils import get_test_rss_path class BlogParserTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.test_file_path = get_test_rss_path() cls.entries = get_all_entries("file://{}".format(cls.test_file_path)) ...
Add some tests to make sure we can parse RSS feeds
Add some tests to make sure we can parse RSS feeds
Python
apache-2.0
manhhomienbienthuy/pythondotorg,proevo/pythondotorg,manhhomienbienthuy/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,Mariatta/pythondotorg,proevo/pythondotorg,python/pythondotorg,manhhomienbienthuy/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,pyth...
5c677c11b35dcb49b9b33807685284bfe9d86338
xgds_map_server/urls.py
xgds_map_server/urls.py
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ from django.conf.urls.defaults import * from xgds_map_server import settings from xgds_map_server.views import * ...
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ from django.conf.urls.defaults import * from xgds_map_server import settings from xgds_map_server.views import * ...
Tweak login required and auth settings to work with C3
Tweak login required and auth settings to work with C3
Python
apache-2.0
xgds/xgds_map_server,xgds/xgds_map_server,xgds/xgds_map_server
b3e20fff43c3d04677f552ec5c7522a840359104
schematics/types/temporal.py
schematics/types/temporal.py
from __future__ import absolute_import import datetime from time import mktime try: from dateutil.tz import tzutc, tzlocal except ImportError: raise ImportError( 'Using the datetime fields requires the dateutil library. ' 'You can obtain dateutil from http://labix.org/python-dateutil' ) f...
from __future__ import absolute_import import datetime from time import mktime try: from dateutil.tz import tzutc, tzlocal except ImportError: raise ImportError( 'Using the datetime fields requires the dateutil library. ' 'You can obtain dateutil from http://labix.org/python-dateutil' ) f...
Change TimeStampType to not accept negative values
Change TimeStampType to not accept negative values This is to work around a Python bug (http://bugs.python.org/issue1777412)
Python
bsd-3-clause
nKey/schematics
02c125755a1e29f36f8bd45279327c811fadff33
datapipe/targets/objects.py
datapipe/targets/objects.py
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return...
from ..target import Target import hashlib import dill import joblib import binascii class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self)...
Fix error on Python 3
Fix error on Python 3
Python
mit
ibab/datapipe
9126a1b65e907c3c23fccf85295042a9bd4c36c2
reobject/models/fields.py
reobject/models/fields.py
from attr import ib, Factory def Field(*args, **kwargs): default = kwargs.get('default') if callable(default): kwargs.pop('default') return ib(*args, default=Factory(default), **kwargs) else: return ib(*args, **kwargs)
import attr def Field(*args, default=attr.NOTHING, **kwargs): if callable(default): default = attr.Factory(default) return attr.ib(*args, default=default, **kwargs) def ManyToManyField(cls, *args, **kwargs): metadata = { 'related': { 'target': cls, 'type': 'ManyT...
Introduce dummy ManyToManyField with attrs metadata
Introduce dummy ManyToManyField with attrs metadata
Python
apache-2.0
onyb/reobject,onyb/reobject
62f2d7b4fe2e39863067c6e2f56f385117d5f66a
helusers/jwt.py
helusers/jwt.py
from django.conf import settings from rest_framework import exceptions from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from .user_utils import get_or_create_user def patch_jwt_settings(): """Patch rest_framework_jwt authentication sett...
from django.conf import settings from rest_framework import exceptions from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from .user_utils import get_or_create_user def patch_jwt_settings(): """Patch rest_framework_jwt authentication sett...
Fix JWTAuthentication active user check
Fix JWTAuthentication active user check
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
893b06261bb97407736ef7572d800bd5843f24f6
robber/matchers/called.py
robber/matchers/called.py
from robber import expect from robber.matchers.base import Base class Called(Base): """ expect(function).to.be.called() """ def matches(self): try: return self.actual.called except AttributeError: raise TypeError('{function} is not a mock'.format(function=self....
from robber import expect from robber.matchers.base import Base class Called(Base): """ expect(function).to.be.called() """ def matches(self): try: return self.actual.called except AttributeError: raise TypeError('{actual} is not a mock'.format(actual=self.actu...
Use `actual` in string format
[f] Use `actual` in string format
Python
mit
vesln/robber.py
0f6f4857eb7cd6675313325714f080f181c08c76
tests/users.py
tests/users.py
""" A static dictionary with SAML testusers that can be used as response. """ USERS = { "testuser1": { "sn": ["Testsson 1"], "givenName": ["Test 1"], "eduPersonAffiliation": ["student"], "eduPersonScopedAffiliation": ["student@example.com"], "eduPersonPrincipalName": ["test@e...
""" A static dictionary with SAML testusers that can be used as response. """ USERS = { "testuser1": { "sn": ["Testsson 1"], "givenName": ["Test 1"], "eduPersonAffiliation": ["student"], "eduPersonScopedAffiliation": ["student@example.com"], "eduPersonPrincipalName": ["test@e...
Remove non-standard attribute in test user.
Remove non-standard attribute in test user.
Python
apache-2.0
irtnog/SATOSA,SUNET/SATOSA,its-dirg/SATOSA,irtnog/SATOSA,SUNET/SATOSA