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 |
|---|---|---|---|---|---|---|---|---|---|---|
1b479a607d068b51d342a15e3544ea198a88fbbd | wsgi/foodcheck_proj/urls.py | wsgi/foodcheck_proj/urls.py | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'foodcheck.views.home', name='home'),
# url(r'^foodcheck/', include('foodcheck.foo.urls')... | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'foodcheck_app.views.home', name='home'),
# url(r'^foodcheck/', include('foodcheck.foo.ur... | Update with name of app | Update with name of app
| Python | agpl-3.0 | esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck | ---
+++
@@ -6,7 +6,7 @@
urlpatterns = patterns('',
# Examples:
- url(r'^$', 'foodcheck.views.home', name='home'),
+ url(r'^$', 'foodcheck_app.views.home', name='home'),
# url(r'^foodcheck/', include('foodcheck.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation: |
d097f773260d06b898ab70e99596a07b056a7cb3 | ccdproc/__init__.py | ccdproc/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The ccdproc package is a collection of code that will be helpful in basic CCD
processing. These steps will allow reduction of basic CCD data as either a
stand-alone processing or as part of a pipeline.
"""
# Affiliated packages may add whatever they l... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The ccdproc package is a collection of code that will be helpful in basic CCD
processing. These steps will allow reduction of basic CCD data as either a
stand-alone processing or as part of a pipeline.
"""
# Affiliated packages may add whatever they l... | Add ImageFileCollection to ccdproc namespace | Add ImageFileCollection to ccdproc namespace
| Python | bsd-3-clause | indiajoe/ccdproc,mwcraig/ccdproc,astropy/ccdproc,evertrol/ccdproc,crawfordsm/ccdproc,pulsestaysconstant/ccdproc | ---
+++
@@ -16,3 +16,4 @@
from .core import *
from .ccddata import *
from .combiner import *
+ from .image_collection import * |
16b21e6e3ddf0e26cb1412bffbe2be4acca1deb6 | app/readers/basereader.py | app/readers/basereader.py | from lxml import etree
from app import formatting
def get_namespace_from_top(fn, key='xmlns'):
ac, el = next(etree.iterparse(fn))
return {'xmlns': el.nsmap[key]}
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
"""
# Dep... | from lxml import etree
import itertools
from app import formatting
def get_namespace_from_top(fn, key='xmlns'):
ac, el = next(etree.iterparse(fn))
return {'xmlns': el.nsmap[key]}
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
... | Return chained iterators instead of only first of multiple iterators | Return chained iterators instead of only first of multiple iterators
| Python | mit | glormph/msstitch | ---
+++
@@ -1,4 +1,5 @@
from lxml import etree
+import itertools
from app import formatting
@@ -11,9 +12,8 @@
"""
Calls xmltag generator for multiple files.
"""
- # Deprecate?
- for fn in input_files:
- return generate_xmltags(fn, tag, ignore_tags, ns)
+ return itertools.chain.fro... |
7d8f291dea725c28e4d904a3195fde46a3418925 | parafermions/tests/test_peschel_emery.py | parafermions/tests/test_peschel_emery.py | #!/usr/bin/env python
"""
Test the MPS class
"""
import unittest
import numpy as np
import parafermions as pf
class Test(unittest.TestCase):
def test_pe_degeneracy(self):
# should initialise with all zeros
N, l = 8, 0.2
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
... | #!/usr/bin/env python
"""
Test the MPS class
"""
import unittest
import numpy as np
import parafermions as pf
class Test(unittest.TestCase):
def test_pe_degeneracy(self):
# should initialise with all zeros
N, l = 8, 0.0
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
... | Update slicing so that array sizes match | Update slicing so that array sizes match
| Python | bsd-2-clause | nmoran/pf_resonances | ---
+++
@@ -12,13 +12,15 @@
def test_pe_degeneracy(self):
# should initialise with all zeros
- N, l = 8, 0.2
+ N, l = 8, 0.0
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
d, v = pe.Diagonalise(k=100)
- assert(np.sum(d[1:11:2]-d[:11:2]) < 1e-10)
+ ... |
5bc1731288b76978fa66acab7387a688cea76b4c | wallabag/wallabag_add.py | wallabag/wallabag_add.py | """
Module for adding new entries
"""
import re
import api
import conf
def add(target_url, title=None, star=False, read=False):
conf.load()
valid_url = False
if not re.compile("(?i)https?:\\/\\/.+").match(target_url):
for protocol in "https://", "http://":
if api.is_vali... | """
Module for adding new entries
"""
import re
import api
import conf
import json
def add(target_url, title=None, star=False, read=False):
conf.load()
valid_url = False
if not re.compile("(?i)https?:\\/\\/.+").match(target_url):
for protocol in "https://", "http://":
i... | Check if an anetry already exists before adding it | Check if an anetry already exists before adding it
| Python | mit | Nepochal/wallabag-cli | ---
+++
@@ -4,6 +4,7 @@
import re
import api
import conf
+import json
def add(target_url, title=None, star=False, read=False):
@@ -25,6 +26,23 @@
exit(-1)
try:
+ request = api.api_entry_exists(target_url)
+ if(request.hasError()):
+ print("Error: {0} - {1}".format(requ... |
5a09c6e9545373cece95f87ed28579f05959fced | tests/skip_check.py | tests/skip_check.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | Include teh name of the backend in the error message | Include teh name of the backend in the error message
| Python | bsd-3-clause | Hasimir/cryptography,skeuomorf/cryptography,skeuomorf/cryptography,dstufft/cryptography,bwhmather/cryptography,skeuomorf/cryptography,Lukasa/cryptography,bwhmather/cryptography,Hasimir/cryptography,kimvais/cryptography,sholsapp/cryptography,Ayrx/cryptography,Hasimir/cryptography,sholsapp/cryptography,dstufft/cryptograp... | ---
+++
@@ -17,6 +17,8 @@
def skip_check(name, iface, item):
- if name in item.keywords and item.funcargs.get('backend') is not None:
- if not isinstance(item.funcargs['backend'], iface):
- pytest.skip("Backend does not support {0}".format(name))
+ if name in item.keywords and "backend" i... |
8e6aebf8cb96f5ccf4a119ab213c888a4c33a0d8 | tests/testQuotas.py | tests/testQuotas.py | import json
import os
import sys
sys.path.append('..')
from skytap.Quotas import Quotas # noqa
quotas = Quotas()
def test_quota_count():
assert len(quotas) > 0
def test_quota_id():
for quota in quotas:
assert len(quota.id) > 0
def test_quota_usage():
for quota in quotas:
assert quot... | # import json
# import os
# import sys
#
# sys.path.append('..')
# from skytap.Quotas import Quotas # noqa
#
# quotas = Quotas()
#
#
# def test_quota_count():
# assert len(quotas) > 0
#
#
# def test_quota_id():
# for quota in quotas:
# assert len(quota.id) > 0
#
#
# def test_quota_usage():
# for qu... | Remove quota testing from notestest since API change == quotas broken | Remove quota testing from notestest since API change == quotas broken
| Python | mit | FulcrumIT/skytap,mapledyne/skytap | ---
+++
@@ -1,45 +1,45 @@
-import json
-import os
-import sys
-
-sys.path.append('..')
-from skytap.Quotas import Quotas # noqa
-
-quotas = Quotas()
-
-
-def test_quota_count():
- assert len(quotas) > 0
-
-
-def test_quota_id():
- for quota in quotas:
- assert len(quota.id) > 0
-
-
-def test_quota_usage... |
737fa51dc31b315e554553fc5e3b971de663d0e5 | blog/models.py | blog/models.py | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
| from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField... | Define Post model related fields. | Ch03: Define Post model related fields. [skip ci]
https://docs.djangoproject.com/en/1.8/ref/models/fields/#manytomanyfield
Blog Posts may be about multiple Startups, just as Startups may be
written about multiple times. Posts may also be categorized by multiple
Tags, just as Tags may be used multiple times to cat... | Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -1,4 +1,6 @@
from django.db import models
+
+from organizer.models import Startup, Tag
# Model Field Reference
@@ -10,3 +12,5 @@
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
+ tags = models.ManyToManyField(Tag)
+ startups = models.ManyToManyFi... |
f27e1ba885fb8ba5ce33ee84d76dc562bf51db70 | netbox/netbox/__init__.py | netbox/netbox/__init__.py | from distutils.version import StrictVersion
from django.db import connection
# NetBox v2.2 and later requires PostgreSQL 9.4 or higher
with connection.cursor() as cursor:
cursor.execute("SELECT VERSION()")
row = cursor.fetchone()
pg_version = row[0].split()[1]
if StrictVersion(pg_version) < StrictVer... | Check that PostgreSQL is 9.4 or higher on initialization | Check that PostgreSQL is 9.4 or higher on initialization
| Python | apache-2.0 | digitalocean/netbox,lampwins/netbox,digitalocean/netbox,lampwins/netbox,digitalocean/netbox,lampwins/netbox,lampwins/netbox,digitalocean/netbox | ---
+++
@@ -0,0 +1,12 @@
+from distutils.version import StrictVersion
+
+from django.db import connection
+
+
+# NetBox v2.2 and later requires PostgreSQL 9.4 or higher
+with connection.cursor() as cursor:
+ cursor.execute("SELECT VERSION()")
+ row = cursor.fetchone()
+ pg_version = row[0].split()[1]
+ if... | |
64fb250967775c690e1ae6a7c43c562f4c94438b | tests/test_utils.py | tests/test_utils.py | from springfield_mongo.entities import Entity as MongoEntity
from springfield_mongo import utils
from springfield import fields
from bson.objectid import ObjectId
# This dummy class just used to have an extra attribute to verify during
# using the utils
class FooEntity(MongoEntity):
foo = fields.StringField()
d... | from springfield_mongo import utils
from springfield_mongo.fields import ObjectIdField
from springfield import fields
from springfield import Entity
from bson.objectid import ObjectId
# This dummy class just used to have an extra attribute to verify during
# using the utils
class FooEntity(Entity):
id = ObjectIdF... | Update tests to reflect removal of springfield_mongo Entity. | Update tests to reflect removal of springfield_mongo Entity.
| Python | mit | six8/springfield-mongo | ---
+++
@@ -1,12 +1,14 @@
-from springfield_mongo.entities import Entity as MongoEntity
from springfield_mongo import utils
+from springfield_mongo.fields import ObjectIdField
from springfield import fields
+from springfield import Entity
from bson.objectid import ObjectId
# This dummy class just used to have... |
fb08c6cfe6b6295a9aca9e579a067f34ee1c69c2 | test/get-gh-comment-info.py | test/get-gh-comment-info.py | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases
parser.add_argument('--focus', type=str, default="")
parser.add_argument('--kernel_version', type=str, default="")
parser.add_argument('--k8s_version', type=str, default="")
parser.add_arg... | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases
parser.add_argument('--focus', type=str, default="")
parser.add_argument('--kernel_version', type=str, default="")
parser.add_argument('--k8s_version', type=str, default="")
parser.add_arg... | Format test-only's kernel_version to avoid mistakes | test: Format test-only's kernel_version to avoid mistakes
I often try to start test-only builds with e.g.:
test-only --kernel_version=4.19 --focus="..."
That fails because our tests expect "419". We can extend the Python
script used to parse argument to recognize that and update
kernel_version to the expected fo... | Python | apache-2.0 | cilium/cilium,tklauser/cilium,tgraf/cilium,tklauser/cilium,michi-covalent/cilium,tklauser/cilium,cilium/cilium,tgraf/cilium,cilium/cilium,michi-covalent/cilium,tgraf/cilium,tgraf/cilium,michi-covalent/cilium,michi-covalent/cilium,tgraf/cilium,cilium/cilium,tklauser/cilium,michi-covalent/cilium,tklauser/cilium,cilium/ci... | ---
+++
@@ -9,4 +9,9 @@
args = parser.parse_args()
+# Update kernel_version to expected format
+args.kernel_version = args.kernel_version.replace('.', '')
+if args.kernel_version == "netnext":
+ args.kernel_version = "net-next"
+
print(args.__dict__[args.retrieve]) |
4fc109c93daa3a5d39a184cd692ac7c6b19b9fab | simpleflow/swf/process/worker/dispatch/dynamic_dispatcher.py | simpleflow/swf/process/worker/dispatch/dynamic_dispatcher.py | # -*- coding: utf-8 -*-
import importlib
from simpleflow.activity import Activity
from .exceptions import DispatchError
class Dispatcher(object):
"""
Dispatch by name, like simpleflow.swf.process.worker.dispatch.by_module.ModuleDispatcher
but without a hierarchy.
"""
@staticmethod
def dispat... | # -*- coding: utf-8 -*-
import importlib
from simpleflow.activity import Activity
from .exceptions import DispatchError
class Dispatcher(object):
"""
Dispatch by name, like simpleflow.swf.process.worker.dispatch.by_module.ModuleDispatcher
but without a hierarchy.
"""
@staticmethod
def dispat... | Add comment to explain the choice in dynamic dispatcher | Add comment to explain the choice in dynamic dispatcher
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow | ---
+++
@@ -25,7 +25,15 @@
module = importlib.import_module(module_name)
activity = getattr(module, activity_name, None)
if not activity:
+ # We were not able to import a function at all.
raise DispatchError("unable to import '{}'".format(name))
if not isins... |
85897c2bf4e4e9c89db6111894879d18fef577dd | app.tmpl/__init__.py | app.tmpl/__init__.py | # Main application file
#
# Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com>
from flask import Flask
app = Flask(__name__)
# Import anything that depended on `app`
from {{PROJECTNAME}}.views import *
from {{PROJECTNAME}}.models import *
| # Main application file
#
# Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com>
from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
app.secret_key = 'default-secret-key'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# Impo... | Use the login manager and set a default app secret key | Use the login manager and set a default app secret key
| Python | mit | 0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template | ---
+++
@@ -4,7 +4,12 @@
from flask import Flask
+from flask_login import LoginManager
app = Flask(__name__)
+app.secret_key = 'default-secret-key'
+login_manager = LoginManager()
+login_manager.init_app(app)
+login_manager.login_view = 'login'
# Import anything that depended on `app`
from {{PROJECTNAME}}.v... |
4f45e55e5b0e14cf6bf32b42a14cbdf9b3c08258 | dbus_notify.py | dbus_notify.py | from cgi import escape
import dbus
from utils import is_string
ITEM = "org.freedesktop.Notifications"
PATH = "/org/freedesktop/Notifications"
INTERFACE = "org.freedesktop.Notifications"
APP_NAME = "mpd-hiss"
def dbus_raw_image(im):
"""Convert image for DBUS"""
raw = im.tobytes("raw", "RGBA")
alpha, bps... | from cgi import escape
import dbus
from utils import is_string
ITEM = "org.freedesktop.Notifications"
PATH = "/org/freedesktop/Notifications"
INTERFACE = "org.freedesktop.Notifications"
APP_NAME = "mpd-hiss"
def dbus_raw_image(im):
"""Convert image for DBUS"""
raw = im.tobytes("raw", "RGBA")
alpha, bps... | Make sure we do not try to convert None | Make sure we do not try to convert None
| Python | cc0-1.0 | hellhovnd/mpd-hiss,ahihi/mpd-hiss | ---
+++
@@ -27,12 +27,12 @@
actions = ""
hint = {"suppress-sound": True, "urgency": 0}
time = 5000
+ icon_file = ""
if is_string(icon):
# File path
icon_file = icon
- else:
- icon_file = ""
+ elif icon:
# Not all notifiers support this
# Some r... |
6b4ec52a3fa6fdbb4f70f9d24904bc978341150c | nagare/admin/info.py | nagare/admin/info.py | #--
# Copyright (c) 2008, 2009 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
"""The ``info`` administrative command
Display informations about the framework environment
"""
... | #--
# Copyright (c) 2008, 2009 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
"""The ``info`` administrative command
Display informations about the framework environment
"""
... | Print the Nagare version number | Print the Nagare version number
--HG--
extra : convert_revision : svn%3Afc25bd86-f976-46a1-be41-59ef0291ea8c/trunk%4076
| Python | bsd-3-clause | nagareproject/core,nagareproject/core | ---
+++
@@ -12,7 +12,7 @@
Display informations about the framework environment
"""
-import sys
+import sys, pkg_resources
from nagare.admin import util
@@ -32,4 +32,6 @@
"""
# For the moment, just diplay the Python version
print sys.version
+ print
+ print 'Na... |
9fffcafca0f611cfcbbf3e80435c250f43a0c68b | tests/dataretrival_tests.py | tests/dataretrival_tests.py | import unittest
from bluefin.dataretrieval.clients import V1Client
from bluefin.dataretrieval.exceptions import V1ClientInputException, V1ClientProcessingException
from tests.api_details import API_DETAILS, TEST_CARD
class TransactionReportingTest(unittest.TestCase):
"""
Tests for transaction reporting API cal... | import unittest
from bluefin.dataretrieval.clients import V1Client
from bluefin.dataretrieval.exceptions import V1ClientInputException, V1ClientProcessingException
from tests.api_details import API_DETAILS, TEST_CARD
class TransactionReportingTest(unittest.TestCase):
"""
Tests for transaction reporting API cal... | Use the new auth keyword set by Ligonier. We're working now. | Use the new auth keyword set by Ligonier. We're working now.
| Python | bsd-3-clause | duointeractive/python-bluefin | ---
+++
@@ -12,11 +12,12 @@
Test a basic successful API call.
"""
api = V1Client()
- api.send_request({
+ result = api.send_request({
'transactions_after': '2006-12-30',
'account_id': API_DETAILS['account_id'],
- 'authorization': 'qRdNQK0lk... |
60a10e8fbfd40197db8226f0791c7064c80fe370 | run.py | run.py | import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py"... | import sys
import os
import argparse
import shutil
from efselab import build
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).... | Add new update command that updates efselab dependencies. | Add new update command that updates efselab dependencies.
Former-commit-id: 6cfed1b9af9c0bbf34b7e58e3aa8ac3bada85aa7 | Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger | ---
+++
@@ -1,8 +1,14 @@
+import sys
import os
import argparse
+import shutil
+
+from efselab import build
+
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
+parser.add_argument('--update', action="store_true")
args = pars... |
073dd8529c95f44d7d250508dd10b8ffc8208926 | two_factor/migrations/0003_auto_20150817_1733.py | two_factor/migrations/0003_auto_20150817_1733.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import two_factor.models
class Migration(migrations.Migration):
dependencies = [
('two_factor', '0002_auto_20150110_0810'),
]
operations = [
migrations.AlterField(
model_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from django.db import models, migrations
import phonenumbers
import two_factor.models
logger = logging.getLogger(__name__)
def migrate_phone_numbers(apps, schema_editor):
PhoneDevice = apps.get_model("two_factor", "PhoneDevice")
... | Migrate phone numbers to E.164 format | Migrate phone numbers to E.164 format
| Python | mit | koleror/django-two-factor-auth,Bouke/django-two-factor-auth,koleror/django-two-factor-auth,Bouke/django-two-factor-auth | ---
+++
@@ -1,8 +1,28 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+import logging
from django.db import models, migrations
+import phonenumbers
import two_factor.models
+
+logger = logging.getLogger(__name__)
+
+
+def migrate_phone_numbers(apps, schema_editor):
+ PhoneDevice = apps.get... |
ac664513eb1e99bc7aad9dda70a155e25fcff084 | tests/services/shop/order/test_models_order_payment_state.py | tests/services/shop/order/test_models_order_payment_state.py | """
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.shop.order.models.order import PaymentState
from testfixtures.shop_order import create_order
from testfixtures.user import create_user
def test_is_open():
payment_state = PaymentState.open
... | """
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.shop.order.models.order import PaymentState
from testfixtures.shop_order import create_order
from testfixtures.user import create_user
def test_is_open():
payment_state = PaymentState.open
... | Fix overshadowed tests by giving test functions unique names | Fix overshadowed tests by giving test functions unique names
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -20,7 +20,7 @@
assert order.is_paid == False
-def test_is_open():
+def test_is_canceled():
payment_state = PaymentState.canceled
order = create_order_with_payment_state(payment_state)
@@ -31,7 +31,7 @@
assert order.is_paid == False
-def test_is_open():
+def test_is_paid():
... |
32687e078a50315baa88a9854efea5bb1ca65532 | Cython/Compiler/Future.py | Cython/Compiler/Future.py | def _get_feature(name):
import __future__
# fall back to a unique fake object for earlier Python versions or Python 3
return getattr(__future__, name, object())
unicode_literals = _get_feature("unicode_literals")
with_statement = _get_feature("with_statement")
division = _get_feature("division")
print_func... | def _get_feature(name):
import __future__
# fall back to a unique fake object for earlier Python versions or Python 3
return getattr(__future__, name, object())
unicode_literals = _get_feature("unicode_literals")
with_statement = _get_feature("with_statement") # dummy
division = _get_feature("division")
p... | Mark the "with_statement" __future__ feature as no-op since it's always on. | Mark the "with_statement" __future__ feature as no-op since it's always on.
| Python | apache-2.0 | da-woods/cython,scoder/cython,cython/cython,scoder/cython,scoder/cython,da-woods/cython,da-woods/cython,cython/cython,cython/cython,cython/cython,da-woods/cython,scoder/cython | ---
+++
@@ -4,7 +4,7 @@
return getattr(__future__, name, object())
unicode_literals = _get_feature("unicode_literals")
-with_statement = _get_feature("with_statement")
+with_statement = _get_feature("with_statement") # dummy
division = _get_feature("division")
print_function = _get_feature("print_function"... |
9545c2d78696d7f75299d958cf44f8cf695581ac | DGEclust/readCountData.py | DGEclust/readCountData.py | ## Copyright (C) 2012-2013 Dimitrios V. Vavoulis
## Computational Genomics Group (http://bioinformatics.bris.ac.uk/)
## Department of Computer Science
## University of Bristol
################################################################################
import numpy as np
import pandas as pd
####################... | ## Copyright (C) 2012-2013 Dimitrios V. Vavoulis
## Computational Genomics Group (http://bioinformatics.bris.ac.uk/)
## Department of Computer Science
## University of Bristol
################################################################################
import numpy as np
import pandas as pd
####################... | Normalize by the size of the library | Normalize by the size of the library
| Python | mit | dvav/dgeclust | ---
+++
@@ -15,7 +15,7 @@
## add attributes
df.counts = df.values
- df.exposures = df.sum() / df.sum().astype('double') #df.sum() / df.sum().max().astype('double')
+ df.exposures = df.sum() / df.sum().max().astype('double')
df.samples = df.columns
df.genes = df.index
... |
6c31af53cdc16d9f9cb3b643e9d7f0fee14cbc85 | __main__.py | __main__.py | #--coding:utf-8--
from __init__ import *
import json
import Queue
open('Chinese.bak.json', 'ab').write('[')
open('Foreigner.bak.json', 'ab').write('[')
open('Student.bak.json', 'ab').write('[')
Output = open('result.json', 'wb')
TaskQueue = Queue.Queue(maxsize = 0)
downloader = Downloader(TaskQueue)
downloader.start... | #--coding:utf-8--
from __init__ import *
import json
import Queue
open('Chinese.bak.json', 'ab').write('[')
open('Foreigner.bak.json', 'ab').write('[')
open('Student.bak.json', 'ab').write('[')
Output = open('result.json', 'wb')
TaskQueue = Queue.Queue(maxsize = 0)
downloader = Downloader(TaskQueue)
downloader.start... | Fix Bugs: Cannot Backup Scan Task Queue | Fix Bugs: Cannot Backup Scan Task Queue
| Python | mit | nday-dev/FbSpider | ---
+++
@@ -22,6 +22,5 @@
try:
print "Info: Start Colony.Manage()"
colony.Manage()
-finally:
- colony.End()
- downloader.stop()
+except KeyboardInterrupt:
+ pass |
63d989821040b5b57f6c1076dd5665d1651b30bb | dallinger/transformations.py | dallinger/transformations.py | """
Define custom transformations.
See class Transformation in models.py for the base class Transformation. This
file stores a list of all the subclasses of Transformation made available by
default. Note that they don't necessarily tell you anything about the nature
in which two Info's relate to each other, but if use... | """
Define custom transformations.
See class Transformation in models.py for the base class Transformation. This
file stores a list of all the subclasses of Transformation made available by
default. Note that they don't necessarily tell you anything about the nature
in which two Info's relate to each other, but if use... | Fix relative import of models | Fix relative import of models
| Python | mit | jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger | ---
+++
@@ -7,7 +7,7 @@
in which two Info's relate to each other, but if used sensibly they will do so.
"""
-from models import Transformation
+from .models import Transformation
class Replication(Transformation): |
e19cee4b47d296967286a7f065f363f1e64e58f6 | linter.py | linter.py | from SublimeLinter.lint import PythonLinter
class Pyflakes(PythonLinter):
cmd = 'pyflakes'
regex = r'''(?x)
^(?P<filename>[^:\n]+):(?P<line>\d+):((?P<col>\d+):)?\s
# The rest of the line is the error message.
# Within that, capture anything within single quotes as `near`.
(?P<... | from SublimeLinter.lint import PythonLinter
import re
class Pyflakes(PythonLinter):
cmd = 'pyflakes'
regex = r'''(?x)
^(?P<filename>[^:\n]+):(?P<line>\d+):((?P<col>\d+):)?\s
# The rest of the line is the error message.
# Within that, capture anything within single quotes as `near`.
... | Improve col reporting for unused imports | Improve col reporting for unused imports
| Python | mit | SublimeLinter/SublimeLinter-pyflakes | ---
+++
@@ -1,4 +1,5 @@
from SublimeLinter.lint import PythonLinter
+import re
class Pyflakes(PythonLinter):
@@ -16,3 +17,23 @@
defaults = {
'selector': 'source.python'
}
+
+ def reposition_match(self, line, col, match, vv):
+ if 'imported but unused' in match.message:
+ ... |
1f47381705e7115e6e466fb625fbb925fbd503e2 | birdy/dependencies.py | birdy/dependencies.py | # -*- coding: utf-8 -*-
"""
This module is used to manage optional dependencies.
Example usage::
from birdy.dependencies import ipywidgets as widgets
"""
import warnings
from .exceptions import IPythonWarning
# TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook,
# but we cu... | # -*- coding: utf-8 -*-
"""
This module is used to manage optional dependencies.
Example usage::
from birdy.dependencies import ipywidgets as widgets
"""
import warnings
from .exceptions import IPythonWarning
# TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook,
# but we cu... | Undo change that did not fix issue | Undo change that did not fix issue
| Python | apache-2.0 | bird-house/birdy | ---
+++
@@ -15,7 +15,7 @@
# but we currently don't know how to handle this (see #89 and #138).
warnings.filterwarnings('ignore', category=IPythonWarning)
-try:
+try:
import ipywidgets
except ImportError:
ipywidgets = None
@@ -28,7 +28,7 @@
warnings.warn('IPython is not supported. Please install *... |
aac08ae7dbfa8542210664922b8857de0b185b6f | apps/bluebottle_utils/tests.py | apps/bluebottle_utils/tests.py | import uuid
from django.contrib.auth.models import User
class UserTestsMixin(object):
""" Mixin base class for tests requiring users. """
def create_user(self, username=None, password=None):
""" Create, save and return a new user. """
# If no username is set, create a random unique username... | import uuid
from django.contrib.auth.models import User
class UserTestsMixin(object):
""" Mixin base class for tests requiring users. """
def create_user(self, username=None, password=None):
""" Create, save and return a new user. """
def generate_username():
return str(uuid.uui... | Fix bug in username uniqueness. | Fix bug in username uniqueness.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | ---
+++
@@ -9,13 +9,18 @@
def create_user(self, username=None, password=None):
""" Create, save and return a new user. """
- # If no username is set, create a random unique username
- while not username or User.objects.filter(username=username).exists():
- # Generate a random ... |
d49d383c62233036d4195d71ba4fda78ff2278de | 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... | Improve basic checks of distarray export. | Improve basic checks of distarray export. | Python | bsd-3-clause | enthought/distarray,RaoUmer/distarray,RaoUmer/distarray,enthought/distarray | ---
+++
@@ -15,8 +15,14 @@
grid_shape=(4,),
comm=comm, buf=None, offset=0)
- def test_export(self):
- self.assertIsInstance(self.arr, da.LocalArray)
+ def test_has_export(self):
+ self.assertTrue(hasattr(self.arr, '__dis... |
bc78bf85442b0ffb7962a1c9c4a3560a0fd1960d | skimage/io/_plugins/matplotlib_plugin.py | skimage/io/_plugins/matplotlib_plugin.py | import matplotlib.pyplot as plt
def imshow(*args, **kwargs):
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
imread = plt.imread
show = plt.show
def _app_show():
show()
| import matplotlib.pyplot as plt
def imshow(*args, **kwargs):
if plt.gca().has_data():
plt.figure()
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs)
imread = plt.imread
show = plt.show
def _app_show():
show()
| Create a new figure for imshow if there is already data | Create a new figure for imshow if there is already data
| Python | bsd-3-clause | keflavich/scikit-image,GaZ3ll3/scikit-image,pratapvardhan/scikit-image,jwiggins/scikit-image,oew1v07/scikit-image,robintw/scikit-image,vighneshbirodkar/scikit-image,michaelaye/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,paalge/scikit-image,paalge/scikit-image,michaelaye/scikit-image,warmspringwinds... | ---
+++
@@ -2,6 +2,8 @@
def imshow(*args, **kwargs):
+ if plt.gca().has_data():
+ plt.figure()
kwargs.setdefault('interpolation', 'nearest')
kwargs.setdefault('cmap', 'gray')
plt.imshow(*args, **kwargs) |
7b9b1a7bb7f9e48e466bd00b3edffc67be841b4e | pavement.py | pavement.py | import os.path
from paver.easy import sh, task
config = """# replace pass with values you would like to overwrite from DefaultConfig in
# default_config.py. Values you do not explicitly overwrite will be inherited
# from DefaultConfig. At the very least, you must set secret_key and
# tmdb_api_key.
from default_confi... | import os.path
import shutil
from paver.easy import sh, task
config = """# replace pass with values you would like to overwrite from DefaultConfig in
# default_config.py. Values you do not explicitly overwrite will be inherited
# from DefaultConfig. At the very least, you must set secret_key and
# tmdb_api_key.
from... | Add some git hook related tasks to paver file | Add some git hook related tasks to paver file
| Python | mit | simon-andrews/movieman2,simon-andrews/movieman2 | ---
+++
@@ -1,4 +1,5 @@
import os.path
+import shutil
from paver.easy import sh, task
@@ -13,6 +14,24 @@
class Config(DefaultConfig):
pass
"""
+
+
+@task
+def apply_hooks():
+ """Copies hooks from git_hooks folder into .git/hooks"""
+ os.chdir('git_hooks')
+ for item in os.listdir('.'):
+ ... |
1c3bffed864fab3163244486441f08fba00b1a65 | fireplace/cards/gvg/warlock.py | fireplace/cards/gvg/warlock.py | from ..utils import *
##
# Minions
# Mistress of Pain
class GVG_018:
events = [
Damage().on(
lambda self, source, target, amount: source is self and [Heal(FRIENDLY_HERO, amount)] or []
)
]
# Fel Cannon
class GVG_020:
events = [
OWN_TURN_END.on(Hit(RANDOM(ALL_MINIONS - MECH), 2))
]
# Anima Golem
clas... | from ..utils import *
##
# Minions
# Mistress of Pain
class GVG_018:
events = [
Damage().on(
lambda self, target, amount, source: source is self and [Heal(FRIENDLY_HERO, amount)] or []
)
]
# Fel Cannon
class GVG_020:
events = [
OWN_TURN_END.on(Hit(RANDOM(ALL_MINIONS - MECH), 2))
]
# Anima Golem
clas... | Fix argument ordering in Mistress of Pain | Fix argument ordering in Mistress of Pain
Fixes #71
| Python | agpl-3.0 | amw2104/fireplace,smallnamespace/fireplace,liujimj/fireplace,Meerkov/fireplace,NightKev/fireplace,oftc-ftw/fireplace,butozerca/fireplace,jleclanche/fireplace,Ragowit/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,beheh/fireplace,butozerca/fireplace,Meerkov/fireplace,amw2104/fireplace,liujimj/fireplace,smallnamespace/fi... | ---
+++
@@ -8,7 +8,7 @@
class GVG_018:
events = [
Damage().on(
- lambda self, source, target, amount: source is self and [Heal(FRIENDLY_HERO, amount)] or []
+ lambda self, target, amount, source: source is self and [Heal(FRIENDLY_HERO, amount)] or []
)
]
|
843b4c4c0ec7176f4b60fc9d39e7a033c2d4ef7d | utils/crypto.py | utils/crypto.py | import hashlib
import os
import string
import random
from django.conf import settings
def hasher(string):
'''Helper method to hash a string to SHA512'''
h = hashlib.sha512(settings.SECRET_KEY + string).hexdigest()
for _ in range(settings.HASH_PASSES):
h = hashlib.sha512(h).hexdigest()
return h... | import hashlib
import os
import string
import random
from django.conf import settings
def hasher(string):
'''Helper method to hash a string to SHA512'''
h = hashlib.sha512(settings.SECRET_KEY + string.encode("utf-8")).hexdigest()
for _ in range(settings.HASH_PASSES):
h = hashlib.sha512(h).hexdiges... | Make the password hashing unicode safe. | Make the password hashing unicode safe.
| Python | bsd-3-clause | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker | ---
+++
@@ -7,7 +7,7 @@
def hasher(string):
'''Helper method to hash a string to SHA512'''
- h = hashlib.sha512(settings.SECRET_KEY + string).hexdigest()
+ h = hashlib.sha512(settings.SECRET_KEY + string.encode("utf-8")).hexdigest()
for _ in range(settings.HASH_PASSES):
h = hashlib.sha512(... |
7403e79c9e3cccc7ea97e61915ec01c2176c0f57 | tests/test_heroku.py | tests/test_heroku.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import mock
from dallinger.config import get_config
from dallinger.heroku import app_name
class TestHeroku(object):
def test_heroku_app_name(self):
id = "8fbe62f5-2e33-4274-8aeb-40fc3dd621a0"
assert(len(app_name(id)) < 30)
class TestHerokuCloc... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import mock
import pytest
import dallinger.db
from dallinger.config import get_config
from dallinger.heroku import app_name
@pytest.fixture
def setup():
db = dallinger.db.init_db(drop_all=True)
os.chdir('tests/experiment')
config = get_config()
if no... | Allow test to run without MTurk/AWS credentials configured, and defend against other tests which don’t clean up database | Allow test to run without MTurk/AWS credentials configured, and defend against other tests which don’t clean up database
| Python | mit | Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger | ---
+++
@@ -2,8 +2,23 @@
# -*- coding: utf-8 -*-
import os
import mock
+import pytest
+import dallinger.db
from dallinger.config import get_config
from dallinger.heroku import app_name
+
+
+@pytest.fixture
+def setup():
+ db = dallinger.db.init_db(drop_all=True)
+ os.chdir('tests/experiment')
+ config =... |
825c83697b3453644a6ec699d653ba0d4bd5d790 | pymanopt/tools/autodiff/_autograd.py | pymanopt/tools/autodiff/_autograd.py | """
Module containing functions to differentiate functions using autograd.
"""
import autograd.numpy as np
from autograd.core import grad
from ._backend import Backend
def _hessian_vector_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-vector product.
The returned function has arg... | """
Module containing functions to differentiate functions using autograd.
"""
import autograd.numpy as np
from autograd.core import grad
from ._backend import Backend
def _hessian_vector_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-vector product.
The returned function has arg... | Remove unnecessary arguments from autograd hessian | Remove unnecessary arguments from autograd hessian
| Python | bsd-3-clause | pymanopt/pymanopt,j-towns/pymanopt,nkoep/pymanopt,tingelst/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,nkoep/pymanopt | ---
+++
@@ -32,4 +32,4 @@
return grad(objective)
def compute_hessian(self, objective, argument):
- return _hessian_vector_product(objective)(x, g)
+ return _hessian_vector_product(objective) |
c1a38cb5fd2f6dd0f81515bece18a47f2b20234b | data_record.py | data_record.py | class DataRecord:
@classmethod
def get_store( cls ):
if hasattr( cls, 'store' ): return cls.store
cls.store = {}
return cls.store
@classmethod
def find( cls, record_id ):
return cls.get_store().get( record_id, None )
@classmethod
def save( cls, record_id, record ):
cls.get_store()[ re... | class DataRecord:
@classmethod
def get_store( cls ):
if hasattr( cls, 'store' ): return cls.store
cls.store = {}
return cls.store
@classmethod
def find( cls, record_id ):
return cls.get_store().get( str(record_id), None )
@classmethod
def save( cls, record_id, record ):
cls.get_store(... | Make all data records store record id keys as strings | Make all data records store record id keys as strings
| Python | mit | fire-uta/iiix-data-parser | ---
+++
@@ -8,22 +8,22 @@
@classmethod
def find( cls, record_id ):
- return cls.get_store().get( record_id, None )
+ return cls.get_store().get( str(record_id), None )
@classmethod
def save( cls, record_id, record ):
- cls.get_store()[ record_id ] = record
+ cls.get_store()[ str(record_id)... |
f787cf0303159fdae9b5a53eca86d0985b1096ee | coreplugins/editshortlinks/plugin.py | coreplugins/editshortlinks/plugin.py | from app.plugins import PluginBase, Menu, MountPoint
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext as _
from .api import GetShortLink, EditShortLink, DeleteShortLink, HandleShortLink
class Plugin(PluginBase):
def build_jsx... | from app.plugins import PluginBase, Menu, MountPoint
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext as _
from .api import GetShortLink, EditShortLink, DeleteShortLink, HandleShortLink
class Plugin(PluginBase):
def build_jsx... | Modify regex group for username to allow periods | Modify regex group for username to allow periods
Fix for #1076 | Python | agpl-3.0 | OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM | ---
+++
@@ -13,7 +13,7 @@
def root_mount_points(self):
return [
- MountPoint(r'^s(?P<view_type>[m3])/(?P<username>[^/.]+)/(?P<short_id>[A-Za-z0-9_-]+)/?$', HandleShortLink)
+ MountPoint(r'^s(?P<view_type>[m3])/(?P<username>[^/]+)/(?P<short_id>[A-Za-z0-9_-]+)/?$', HandleShortLink)... |
5780f72ff95329295c735fff61463315ec3856d7 | manage.py | manage.py | #!/usr/bin/env python
# This manage.py exists for the purpose of creating migrations
import sys
import django
from django.conf import settings
settings.configure(
ROOT_URLCONF='',
DATABASES={'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
... | #!/usr/bin/env python
# This manage.py exists for the purpose of creating migrations
import sys
import django
from django.conf import settings
settings.configure(
ROOT_URLCONF='',
DATABASES={'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
... | Remove stupid South thing that is messing up Heroku | Remove stupid South thing that is messing up Heroku
remove, I say!! | Python | mit | millanp/django-paypal,millanp/django-paypal | ---
+++
@@ -22,7 +22,7 @@
'paypal.standard',
'paypal.standard.ipn',
'paypal.standard.pdt',
- ] + (['south'] if django.VERSION < (1,7) else []),
+ ],
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache', |
b363b0ffc9e4fd7790f418f84107c3b7233642f1 | zou/app/utils/chats.py | zou/app/utils/chats.py | from slackclient import SlackClient
def send_to_slack(app_token, userid, message):
client = SlackClient(token=app_token)
client.api_call(
"chat.postMessage", channel="@%s" % userid, text=message, as_user=True
)
return True
| from slackclient import SlackClient
def send_to_slack(app_token, userid, message):
client = SlackClient(token=app_token)
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": message,
}
},
]
client.api_c... | Allow to format messages sent to Slack | Allow to format messages sent to Slack
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -3,7 +3,16 @@
def send_to_slack(app_token, userid, message):
client = SlackClient(token=app_token)
+ blocks = [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": message,
+ }
+ },
+ ]
client.ap... |
dc8b2e0a68644655d95d67b3ffd6d9122e94584a | zc_common/remote_resource/relations.py | zc_common/remote_resource/relations.py | from collections import OrderedDict
import json
import six
from rest_framework.relations import *
from rest_framework_json_api.relations import ResourceRelatedField
from zc_common.remote_resource.models import *
class RemoteResourceField(ResourceRelatedField):
def __init__(self, *args, **kwargs):
if 'mo... | from collections import OrderedDict
import json
import six
from rest_framework.relations import *
from rest_framework_json_api.relations import ResourceRelatedField
from zc_common.remote_resource.models import *
class RemoteResourceField(ResourceRelatedField):
def __init__(self, *args, **kwargs):
if 'mo... | Use empty dict instead of True for remote resource queryset | Use empty dict instead of True for remote resource queryset
| Python | mit | ZeroCater/zc_common,ZeroCater/zc_common | ---
+++
@@ -15,7 +15,7 @@
if not kwargs.get('read_only', None):
# The queryset is required to be not None, but not used
# due to the overriding of the methods below.
- kwargs['queryset'] = True
+ kwargs['queryset'] = {}
super(RemoteResourceField, sel... |
cd2b628ca118ffae8090004e845e399110aada21 | disk/datadog_checks/disk/__init__.py | disk/datadog_checks/disk/__init__.py | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .disk import Disk
__all__ = ['Disk']
| # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .disk import Disk
all = [
'__version__', 'Disk'
]
| Allow Agent to properly pull version info | [Disk] Allow Agent to properly pull version info | Python | bsd-3-clause | DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core | ---
+++
@@ -1,6 +1,9 @@
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
+from .__about__ import __version__
from .disk import Disk
-__all__ = ['Disk']
+all = [
+ '__version__', 'Disk'
+] |
06c3e03db75617b824eae088053a9fc563b936a7 | virtool/user_permissions.py | virtool/user_permissions.py | #: A list of the permission strings used by Virtool.
PERMISSIONS = [
"cancel_job",
"create_sample",
"create_subtraction",
"manage_users",
"modify_hmm",
"modify_options",
"modify_virus",
"rebuild_index",
"remove_job",
"remove_virus"
]
| #: A list of the permission strings used by Virtool.
PERMISSIONS = [
"cancel_job",
"create_sample",
"manage_users",
"modify_hmm",
"modify_options",
"modify_subtraction",
"modify_virus",
"rebuild_index",
"remove_job",
"remove_virus"
]
| Change create_subtraction permission to modify_subtraction | Change create_subtraction permission to modify_subtraction
| Python | mit | virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool | ---
+++
@@ -2,10 +2,10 @@
PERMISSIONS = [
"cancel_job",
"create_sample",
- "create_subtraction",
"manage_users",
"modify_hmm",
"modify_options",
+ "modify_subtraction",
"modify_virus",
"rebuild_index",
"remove_job", |
1424ce565ee8b47e6a9a3bc143589c7e7e0c3e53 | cloudenvy/commands/envy_scp.py | cloudenvy/commands/envy_scp.py | import logging
import fabric.api
import fabric.operations
from cloudenvy.envy import Envy
class EnvySCP(object):
"""SCP Files to your ENVy"""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('scp',... | import logging
import fabric.api
import fabric.operations
from cloudenvy.envy import Envy
class EnvySCP(object):
"""SCP Files to your ENVy"""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('scp',... | Document source and target arguments of envy scp | Document source and target arguments of envy scp
Fix issue #67
| Python | apache-2.0 | cloudenvy/cloudenvy | ---
+++
@@ -16,8 +16,11 @@
subparser = subparsers.add_parser('scp', help='scp help')
subparser.set_defaults(func=self.run)
- subparser.add_argument('source')
- subparser.add_argument('target')
+ subparser.add_argument('source',
+ help='Local path to copy into yo... |
94ad83d899f0c9372013a9bcdad25ee3c9783626 | wallace/interval_storage.py | wallace/interval_storage.py | class IntervalStorage(object):
def __init__(self, interval_map=None):
if interval_map == None:
self.interval_map = {}
else:
if not isinstance(interval_map, dict):
raise ValueError("Interval map must be a dictionary containing entries as keys and interval tuple... | class IntervalStorage(object):
def __init__(self, interval_map=None):
if interval_map == None:
self.interval_map = {}
else:
if not isinstance(interval_map, dict):
raise ValueError("Interval map must be a dictionary containing entries as keys and interval tuple... | Make sure that have intervals of the form [start, end). | Make sure that have intervals of the form [start, end).
| Python | mit | wangjohn/wallace | ---
+++
@@ -31,8 +31,8 @@
def has_intersection(self, start, end):
for value in self.interval_map.itervalues():
- if (value[0] <= start and start <= value[1]) or \
- (value[0] <= end and end <= value[1]) or \
- (start <= value[0] and value[1] <= end):
+ ... |
901e6cc8bdafcd6e6d419ffd5eee4e58d266d40a | extensions.py | extensions.py | import subprocess
from functools import wraps
import os
extensions = {}
def extension(f):
# keep unwrapped function
unwrapped = f
@wraps(f)
def wrapper(**kwargs):
wrapper.settings = dict(kwargs)
return unwrapped
extensions[f.__name__] = wrapper
return wrapper
@extension
de... | import subprocess
from functools import wraps
import os
extensions = {}
def extension(f):
# keep unwrapped function
unwrapped = f
@wraps(f)
def wrapper(**kwargs):
wrapper.settings = dict(kwargs)
return unwrapped
extensions[f.__name__] = wrapper
return wrapper
@extension
de... | Fix file not found error on directory | Fix file not found error on directory
| Python | mit | rolurq/flask-gulp | ---
+++
@@ -36,10 +36,14 @@
dest = filename.replace(ext, '.js')
return dest, out
+
@extension
def dest(filename, data):
destination = dest.settings.get('destination')
if destination:
+ if not os.path.exists(destination):
+ os.mkdir(destination)
+ _, tail = os.p... |
9982e62981a7ec0fc7f05dcc8b5eabe11c65d2b3 | anthology/representations.py | anthology/representations.py | """Representation filters for API"""
from flask import make_response, current_app
from bson.json_util import dumps
def output_bson(data, code, headers=None):
"""Makes Flask response with a BSON encoded body
Copied from module `flask_restful.representations.json`
"""
settings = current_app.config.g... | """Representation filters for API"""
from flask import make_response, current_app
from bson.json_util import dumps
def output_bson(data, code, headers=None):
"""Makes Flask response with a JSON encoded body.
Response items are serialized from MongoDB BSON objects to
JSON compatible format.
Modified... | Correct JSON/BSON terminology in docstrings | Correct JSON/BSON terminology in docstrings
| Python | mit | surfmikko/anthology | ---
+++
@@ -5,9 +5,12 @@
def output_bson(data, code, headers=None):
- """Makes Flask response with a BSON encoded body
+ """Makes Flask response with a JSON encoded body.
- Copied from module `flask_restful.representations.json`
+ Response items are serialized from MongoDB BSON objects to
+ JSON... |
aca3cf45ba32cdad69c232794497fc8033b63cc6 | utils/builder.py | utils/builder.py | import sys
import os
output = '../build/Tween.js';
# os.system("java -jar yuicompressor-2.4.2.jar ../src/Tween.js -o ../build/Tween.js --charset utf-8 -v");
os.system("java -jar compiler.jar --js ../src/Tween.js --js_output_file ../build/Tween.js")
# HEADER
string = "// Tween.js - http://github.com/sole/tween.js\n"... | import sys
import os
output = '../build/tween.js';
# os.system("java -jar yuicompressor-2.4.2.jar ../src/Tween.js -o ../build/Tween.js --charset utf-8 -v");
os.system("java -jar compiler.jar --js ../src/Tween.js --js_output_file %s" % (output))
# HEADER
with open(os.path.join('..', 'REVISION'), 'r') as handle:
rev... | Update packer system to include REVISION number too | Update packer system to include REVISION number too
| Python | mit | CasualBot/tween.js,JITBALJINDER/tween.js,altereagle/tween.js,gopalindians/tween.js,rocbear/tween.js,Twelve-60/tween.js,wangzuo/cxx-tween,Twelve-60/tween.js,olizilla/tween.js,gopalindians/tween.js,camellhf/tween.js,camellhf/tween.js,olizilla/tween.js,rocbear/tween.js,npmcomponent/bestander-tween.js,altereagle/tween.js,T... | ---
+++
@@ -1,14 +1,17 @@
import sys
import os
-output = '../build/Tween.js';
+output = '../build/tween.js';
# os.system("java -jar yuicompressor-2.4.2.jar ../src/Tween.js -o ../build/Tween.js --charset utf-8 -v");
-os.system("java -jar compiler.jar --js ../src/Tween.js --js_output_file ../build/Tween.js")
+os... |
ef67ce4372128d8f7e9689e1090ee44674c8f391 | scripts/analytics/run_keen_events.py | scripts/analytics/run_keen_events.py | from framework.celery_tasks import app as celery_app
from scripts.analytics.base import DateAnalyticsHarness
from scripts.analytics.node_log_events import NodeLogEvents
class EventAnalyticsHarness(DateAnalyticsHarness):
@property
def analytics_classes(self):
return [NodeLogEvents]
@celery_app.task(... | from framework.celery_tasks import app as celery_app
from scripts.analytics.base import DateAnalyticsHarness
from scripts.analytics.node_log_events import NodeLogEvents
from scripts.analytics.user_domain_events import UserDomainEvents
class EventAnalyticsHarness(DateAnalyticsHarness):
@property
def analytics... | Add new user domain event collector to main keen events script | Add new user domain event collector to main keen events script
| Python | apache-2.0 | chrisseto/osf.io,caneruguz/osf.io,felliott/osf.io,alexschiller/osf.io,leb2dg/osf.io,chrisseto/osf.io,caseyrollins/osf.io,baylee-d/osf.io,icereval/osf.io,hmoco/osf.io,leb2dg/osf.io,chrisseto/osf.io,mluo613/osf.io,rdhyee/osf.io,acshi/osf.io,mluo613/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,felliott/... | ---
+++
@@ -1,13 +1,14 @@
from framework.celery_tasks import app as celery_app
from scripts.analytics.base import DateAnalyticsHarness
from scripts.analytics.node_log_events import NodeLogEvents
+from scripts.analytics.user_domain_events import UserDomainEvents
class EventAnalyticsHarness(DateAnalyticsHarness... |
2b64dc699e222a011d5946fd53a2bda4df77d0fe | scripts/rename_tutorial_src_files.py | scripts/rename_tutorial_src_files.py | #%%
from pathlib import Path
from string import digits
#%%
directory = Path("./docs/tutorial/src")
output_directory = Path("./docs/tutorial/out")
output_directory.mkdir(exist_ok=True)
files = sorted([Path(f) for f in directory.iterdir()])
for i, f in enumerate(files):
f: Path
index = str(i + 1).zfill(2)
n... | #%%
from pathlib import Path, PurePath
from string import digits
#%%
directory = Path("./docs/tutorial/src")
dirs = sorted([Path(f) for f in directory.iterdir()])
d: PurePath
sufix = "__out__"
for d in dirs:
if d.name.endswith(sufix):
continue
output_dir_name = d.name + "__out__"
output_directory ... | Update tutorial src renamer to use sub-directories | :sparkles: Update tutorial src renamer to use sub-directories
| Python | mit | tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi | ---
+++
@@ -1,16 +1,30 @@
#%%
-from pathlib import Path
+from pathlib import Path, PurePath
from string import digits
#%%
directory = Path("./docs/tutorial/src")
-output_directory = Path("./docs/tutorial/out")
-output_directory.mkdir(exist_ok=True)
-files = sorted([Path(f) for f in directory.iterdir()])
-for ... |
1fce6a621ad4fe149988147478e15c7415295a7b | changes/api/serializer/models/source.py | changes/api/serializer/models/source.py | from changes.api.serializer import Serializer, register
from changes.models import Source
@register(Source)
class SourceSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.patch_id:
patch = {
'id': instance.patch_id.hex,
}
else:
... | from changes.api.serializer import Serializer, register
from changes.models import Source
@register(Source)
class SourceSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.patch_id:
patch = {
'id': instance.patch_id.hex,
}
else:
... | Add data to Source serialization | Add data to Source serialization
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes | ---
+++
@@ -17,4 +17,5 @@
'patch': patch,
'revision': instance.revision,
'dateCreated': instance.date_created,
+ 'tails_data': dict(instance.data),
} |
50367a2d73c395a85bb7dae058f9435be6ad7c36 | vtimshow/__init__.py | vtimshow/__init__.py | #!/usr/bin/env python3
# Module imports
import logging
import os
import vitables
_defaults = dict(
AUTHOR = "Keith F Prussing",
AUTHOR_EMAIL = "kprussing74@gmail.com",
LICENSE = "MIT",
PLUGIN_CLASS = "VtImageViewer",
PLUGIN_NAME = "Image Viewer",
COMMENT = "Display data sets as images",
V... | #!/usr/bin/env python3
# Module imports
import logging
import os
import vitables
_defaults = dict(
AUTHOR = "Keith F Prussing",
AUTHOR_EMAIL = "kprussing74@gmail.com",
LICENSE = "MIT",
PLUGIN_CLASS = "VtImageViewer",
PLUGIN_NAME = "Image Viewer",
COMMENT = "Display data sets as images",
V... | Add method to log to console | Add method to log to console
Add a method to set the GUI logging window to be the stream handler for
my plug in.
| Python | mit | kprussing/vtimshow | ---
+++
@@ -31,3 +31,28 @@
from vtimshow.vtimageviewer import VtImageViewer
+def _setup_logger(name):
+ """
+ Add the GUI's logging window as a stream handler.
+
+ By default, the stream logger is removed during the invocation of
+ ``vitables``. The logging window in the GUI is a stream handler for
... |
70167a8cb73673e1e904fbeb8a50b3de9d4fc1ae | server.py | server.py | from fickle import API
from fickle.classifier import GenericSVMClassifier
backend = GenericSVMClassifier()
app = API(__name__, backend)
if __name__ == '__main__':
host = '0.0.0.0'
port = int(os.environ.get('PORT', 5000))
debug = bool(os.environ.get('FICKLE_DEBUG'))
app.run(host = host, port = port, d... | from fickle import API
from fickle.classifier import GenericSVMClassifier
backend = GenericSVMClassifier()
app = API(__name__, backend)
if __name__ == '__main__':
import os
host = '0.0.0.0'
port = int(os.environ.get('PORT', 5000))
debug = bool(os.environ.get('FICKLE_DEBUG'))
app.run(host = host, ... | Fix run section with import statement | Fix run section with import statement
| Python | mit | norbert/fickle | ---
+++
@@ -6,6 +6,7 @@
app = API(__name__, backend)
if __name__ == '__main__':
+ import os
host = '0.0.0.0'
port = int(os.environ.get('PORT', 5000))
debug = bool(os.environ.get('FICKLE_DEBUG')) |
67b86cb3ddfb7c9e95ebed071ba167472276cc29 | utils/decorators/require.py | utils/decorators/require.py | import requests
from functools import wraps
from flask import request, current_app
from utils.decorators.signature import sign
def require(resource_namespace, permissions, resource_id=None):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if request.method == 'GET':
paylo... | import json
import requests
from functools import wraps
from flask import request, current_app
from utils.decorators.signature import sign
from utils.exceptions import HttpUnauthorized
def require(resource_namespace, permissions, resource_id=None):
def decorator(f):
@wraps(f)
def decorated_function(*args, ... | Check for permission in apq | Check for permission in apq
| Python | apache-2.0 | PressLabs/lithium | ---
+++
@@ -1,9 +1,11 @@
+import json
import requests
from functools import wraps
from flask import request, current_app
from utils.decorators.signature import sign
+from utils.exceptions import HttpUnauthorized
def require(resource_namespace, permissions, resource_id=None):
def decorator(f):
@@ -14,6 +... |
e2be9eb27d6fc7cfa424cbf908347796ab595526 | groundstation/broadcast_announcer.py | groundstation/broadcast_announcer.py | import socket
import logger
from groundstation.broadcast_socket import BroadcastSocket
import logger
log = logger.getLogger(__name__)
class BroadcastAnnouncer(BroadcastSocket):
def __init__(self, port):
super(BroadcastAnnouncer, self).__init__()
self._addr = '255.255.255.255', port
self._n... | import socket
import logger
from sockets.broadcast_socket import BroadcastSocket
import logger
log = logger.getLogger(__name__)
class BroadcastAnnouncer(BroadcastSocket):
def __init__(self, port):
super(BroadcastAnnouncer, self).__init__()
self._addr = '255.255.255.255', port
self._name = ... | Fix an import path bug masked by remaining .pyc files | Fix an import path bug masked by remaining .pyc files
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | ---
+++
@@ -1,6 +1,6 @@
import socket
import logger
-from groundstation.broadcast_socket import BroadcastSocket
+from sockets.broadcast_socket import BroadcastSocket
import logger
log = logger.getLogger(__name__) |
f859964c3d8d193da92fb521f4a696a28ef9452a | cisco_olt_http/tests/test_operations.py | cisco_olt_http/tests/test_operations.py |
import os
import pytest
from cisco_olt_http import operations
from cisco_olt_http.client import Client
@pytest.fixture
def data_dir():
return os.path.abspath(
os.path.join(os.path.dirname(__file__), 'data'))
def test_get_data():
client = Client('http://base-url')
show_equipment_op = operations.... |
import os
import pytest
import requests
from cisco_olt_http import operations
from cisco_olt_http.client import Client
@pytest.fixture
def data_dir():
return os.path.abspath(
os.path.join(os.path.dirname(__file__), 'data'))
def test_get_data():
client = Client('http://base-url')
show_equipment_... | Use mock instead of own class | Use mock instead of own class
| Python | mit | beezz/cisco-olt-http-client,Vnet-as/cisco-olt-http-client | ---
+++
@@ -1,6 +1,7 @@
import os
import pytest
+import requests
from cisco_olt_http import operations
from cisco_olt_http.client import Client
@@ -20,11 +21,9 @@
class TestOperationResult:
- def test_ok_response(self, data_dir):
+ def test_ok_response(self, data_dir, mocker):
- class Resp... |
580974cedceecea71e32f0cba1daf4dccb7e4736 | 2018/unif/unifier.py | 2018/unif/unifier.py | # Python 3.6
class Expr:
pass
class App(Expr):
def __init__(self, fname, args=()):
self.fname = fname
self.args = args
def __str__(self):
return '{0}({1})'.format(self.fname, ','.join(map(str, self.args)))
class Var(Expr):
def __init__(self, name):
self.name = name
... | # Python 3.6
class Expr:
pass
class App(Expr):
def __init__(self, fname, args=()):
self.fname = fname
self.args = args
def __str__(self):
return '{0}({1})'.format(self.fname, ','.join(map(str, self.args)))
class Var(Expr):
def __init__(self, name):
self.name = name
... | Add more skeleton function code and TODOs | Add more skeleton function code and TODOs
| Python | unlicense | eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog | ---
+++
@@ -27,3 +27,12 @@
def __str__(self):
return self.value
+
+
+# TODO: implement these
+def parse_expr(s):
+ """Parses an expression in 's' into an Expr."""
+ pass
+
+
+# Need a bindings map to pass around for unify |
37da0285ac6b08994700952e04278e1049577745 | yanico/config.py | yanico/config.py | # Copyright 2015-2016 Masayuki Yamamoto
#
# 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 agree... | # Copyright 2015-2016 Masayuki Yamamoto
#
# 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 agree... | Add docstring into user_path function | Add docstring into user_path function
Describe dependnce for constants and environments.
| Python | apache-2.0 | ma8ma/yanico | ---
+++
@@ -20,4 +20,8 @@
def user_path():
+ """Return user configuration filepath.
+
+ The filepath depends home directory and CONFIG_FILENAME constants.
+ """
return os.path.join(os.path.expanduser('~'), CONFIG_FILENAME) |
956d68b6e29b1e319d043945393db3825b5167d1 | dask/compatibility.py | dask/compatibility.py | from __future__ import absolute_import, division, print_function
import sys
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
if PY3:
import builtins
from queue import Queue, Empty
from itertools import zip_longest
from io import StringIO, BytesIO
from urllib.request import urlopen
... | from __future__ import absolute_import, division, print_function
import sys
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
if PY3:
import builtins
from queue import Queue, Empty
from itertools import zip_longest
from io import StringIO, BytesIO
from urllib.request import urlopen
... | Allow for tuple-based args in map also | Allow for tuple-based args in map also
| Python | bsd-3-clause | blaze/dask,blaze/dask,mrocklin/dask,gameduell/dask,wiso/dask,mraspaud/dask,PhE/dask,cowlicks/dask,wiso/dask,dask/dask,PhE/dask,ContinuumIO/dask,jakirkham/dask,mraspaud/dask,jakirkham/dask,pombredanne/dask,jayhetee/dask,jayhetee/dask,ssanderson/dask,dask/dask,mikegraham/dask,clarkfitzg/dask,jcrist/dask,pombredanne/dask,... | ---
+++
@@ -16,9 +16,9 @@
unicode = str
long = int
def apply(func, args, kwargs=None):
- if not isinstance(args, list) and kwargs is None:
+ if not isinstance(args, list) and not isinstance(args, tuple) and kwargs is None:
return func(args)
- elif not isinstance(args, ... |
39e038373b0691f14605a5aec3f917b5cee40091 | django_google_charts/charts.py | django_google_charts/charts.py | import six
import json
from django.utils.html import format_html, mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, ... | import json
from django.utils import six
from django.utils.html import format_html, mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls)._... | Use django's bundled and customised version of six | Use django's bundled and customised version of six
| Python | mit | danpalmer/django-google-charts,danpalmer/django-google-charts | ---
+++
@@ -1,6 +1,6 @@
-import six
import json
+from django.utils import six
from django.utils.html import format_html, mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible |
08a3874f826d46528f049318af67b9a39922604c | functionaltests/api/test_versions.py | functionaltests/api/test_versions.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Red Hat, 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 applicabl... | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Red Hat, 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 applicabl... | Fix minor bug in test_get_root_discovers_v1 | Fix minor bug in test_get_root_discovers_v1
Invoke json method to get response body instead of referring it.
Change-Id: I5af060b75b14f2b9322099d8a658c070b056cee2
| Python | apache-2.0 | gilbertpilz/solum,ed-/solum,ed-/solum,julienvey/solum,gilbertpilz/solum,devdattakulkarni/test-solum,gilbertpilz/solum,stackforge/solum,devdattakulkarni/test-solum,ed-/solum,stackforge/solum,ed-/solum,openstack/solum,gilbertpilz/solum,julienvey/solum,openstack/solum | ---
+++
@@ -22,7 +22,7 @@
def test_get_root_discovers_v1(self):
r = requests.get('http://127.0.0.1:9777')
self.assertEqual(r.status_code, 200)
- body = r.json
+ body = r.json()
self.assertEqual(len(body), 1)
v1 = body[0]
self.assertEqual(v1['id'], 'v1.0'... |
92ca956dc8f4229a1c427cb24843c7fe3baef405 | tests/integration/test_parked.py | tests/integration/test_parked.py | """Parked check integration test."""
def test_parked_query(webapp):
"""Test the parked API against our own domain."""
request = webapp.get('/api/parked/dnstwister.report')
assert request.status_code == 200
assert request.json == {
u'domain': u'dnstwister.report',
u'domain_... | """Parked check integration test."""
def test_parked_query(webapp):
"""Test the parked API against our own domain."""
request = webapp.get('/api/parked/dnstwister.report')
assert request.status_code == 200
assert request.json == {
u'domain': u'dnstwister.report',
u'domain_... | Test for parked check against unresolvable domain | Test for parked check against unresolvable domain
| Python | unlicense | thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister | ---
+++
@@ -18,3 +18,14 @@
u'score_text': u'Possibly',
u'url': u'http://localhost:80/api/parked/dnstwister.report'
}
+
+
+def test_parked_query_on_broken_domain(webapp):
+ """Test the parked API against a domain that doesn't exist."""
+ request = webapp.get('/api/parked/there-is-little-ch... |
388149ead0ed3f4e5439301fa23e21050773e309 | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.8.2"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.9.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.9.0 | Increment version number to 0.9.0
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.8.2"
+__version__ = "0.9.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
8005d43146669e98d921bb36c4afd5dffb08e2e3 | Tests/varLib/featureVars_test.py | Tests/varLib/featureVars_test.py | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.varLib.featureVars import (
overlayFeatureVariations)
def test_explosion(n = 10):
conds = []
for i in range(n):
end = i / n
start = end - 1.
region = [{'axis': (start, ... | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.varLib.featureVars import (
overlayFeatureVariations)
def test_explosion(n = 10):
conds = []
for i in range(n):
end = i / n
start = end - 1.
region = [{'axis': (start, ... | Enable test now that it passes | [varLib.featureVars] Enable test now that it passes
| Python | mit | googlefonts/fonttools,fonttools/fonttools | ---
+++
@@ -13,8 +13,7 @@
subst = {'g%.2g'%start: 'g%.2g'%end}
conds.append((region, subst))
overlaps = overlayFeatureVariations(conds)
- # XXX Currently fails for n > 2!
- #assert len(overlaps) == 2 * n - 1, overlaps
+ assert len(overlaps) == 2 * n - 1, overlaps
return conds, ove... |
cf13e81d2e41608bfc8e22d9e1f669382a5bdfc6 | indra/preassembler/make_wm_ontmap.py | indra/preassembler/make_wm_ontmap.py | import sys
from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file as mht
from indra.sources.sofia.make_sofia_tsv import make_file as mst
from indra.java_vm import autoclass
eidos_package = 'org.clulab.wm.eidos'
if __name__ == '__main__':
sofia_ont_path = sys.argv[1]
hume_path =... | import sys
import os
from os.path import join, dirname, abspath
from indra import preassembler
from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file as mht
from indra.sources.sofia.make_sofia_tsv import make_file as mst
from indra.java_vm import autoclass
eidos_package = 'org.clulab.wm... | Save ontology map in script | Save ontology map in script
| Python | bsd-2-clause | sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/indra | ---
+++
@@ -1,4 +1,7 @@
import sys
+import os
+from os.path import join, dirname, abspath
+from indra import preassembler
from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file as mht
from indra.sources.sofia.make_sofia_tsv import make_file as mst
@@ -8,7 +11,7 @@
if __name__ ==... |
40624e155ff3ec9012942744b5c09d91164d5756 | src/neuroglancer_scripts/__init__.py | src/neuroglancer_scripts/__init__.py | # Copyright (c) 2018 Forschungszentrum Juelich GmbH
# Author: Yann Leprince <y.leprince@fz-juelich.de>
#
# This software is made available under the MIT licence, see LICENCE.txt.
"""Conversion of images to the Neuroglancer pre-computed format.
.. todo:: introduction to the high-level APIs
"""
# Version used by setup... | # Copyright (c) 2018 Forschungszentrum Juelich GmbH
# Author: Yann Leprince <y.leprince@fz-juelich.de>
#
# This software is made available under the MIT licence, see LICENCE.txt.
"""Conversion of images to the Neuroglancer pre-computed format.
.. todo:: introduction to the high-level APIs
"""
# Version used by setup... | Set the version to 0.2.0 | Set the version to 0.2.0
| Python | mit | HumanBrainProject/neuroglancer-scripts | ---
+++
@@ -8,5 +8,21 @@
.. todo:: introduction to the high-level APIs
"""
-# Version used by setup.py and docs/conf.py
-__version__ = "0.2.0.dev0"
+# Version used by setup.py and docs/conf.py (parsed with a regular expression).
+#
+# Release checklist (based on https://packaging.python.org/):
+# 1. Ensure that ... |
4b98e89e306aa04c4b3c1df254209f59f61d4f2a | tt_dailyemailblast/send_backends/sync.py | tt_dailyemailblast/send_backends/sync.py | from .. import email
def sync_daily_email_blasts(blast):
for l in blast.recipients_lists.all():
l.send(blast)
def sync_recipients_list(recipients_list, blast):
for r in recipients_list.recipientss.all():
r.send(recipients_list, blast)
def sync_recipient(recipient, recipients_list, blast):
... | from .. import email
def sync_daily_email_blasts(blast):
for l in blast.recipient_lists.all():
l.send(blast)
def sync_recipients_list(recipients_list, blast):
for r in recipients_list.recipientss.all():
r.send(recipients_list, blast)
def sync_recipient(recipient, recipients_list, blast):
... | Fix there was no such thing as blast.recipients_lists | Fix there was no such thing as blast.recipients_lists
| Python | apache-2.0 | texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast | ---
+++
@@ -2,7 +2,7 @@
def sync_daily_email_blasts(blast):
- for l in blast.recipients_lists.all():
+ for l in blast.recipient_lists.all():
l.send(blast)
|
7c38eae5a07e07789713baf5ab3aaea772e76422 | routes.py | routes.py | from flask import Flask, render_template, redirect
import psycopg2
import os
import urlparse
app = Flask(__name__)
# def connectDB(wrapped):
# def inner(*args, **kwargs):
# api_token = os.environ["API_TOKEN"]
# urlparse.uses_netloc.append("postgres")
# url = urlparse.urlparse(os.environ["... | from flask import Flask, render_template, redirect, request
import psycopg2
from functools import wraps
import os
import urlparse
app = Flask(__name__)
def connectDB(wrapped):
@wraps(wrapped)
def inner(*args, **kwargs):
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.envir... | Add decorator to connect to database | Add decorator to connect to database
| Python | mit | AlexMathew/csipy-home | ---
+++
@@ -1,27 +1,28 @@
-from flask import Flask, render_template, redirect
+from flask import Flask, render_template, redirect, request
import psycopg2
+from functools import wraps
import os
import urlparse
+
app = Flask(__name__)
-# def connectDB(wrapped):
-# def inner(*args, **kwargs):
-# a... |
79978bd00fc4834b01f7473cc5b7b8407abec51c | Lib/test/test_nis.py | Lib/test/test_nis.py | import nis
verbose = 0
if __name__ == '__main__':
verbose = 1
maps = nis.maps()
try:
for nismap in maps:
if verbose:
print nismap
mapping = nis.cat(nismap)
for k, v in mapping.items():
if verbose:
print ' ', k, v
if not k:
continue
if nis.match(k, nismap) <> v:
print "NIS match... | import nis
verbose = 0
if __name__ == '__main__':
verbose = 1
maps = nis.maps()
done = 0
for nismap in maps:
if verbose:
print nismap
mapping = nis.cat(nismap)
for k, v in mapping.items():
if verbose:
print ' ', k, v
if not k:
continue
if nis.match(k, nismap) <> v:
print "NIS mat... | Rewrite without using try-except to break out of two loops. | Rewrite without using try-except to break out of two loops.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -5,21 +5,22 @@
verbose = 1
maps = nis.maps()
-try:
- for nismap in maps:
+done = 0
+for nismap in maps:
+ if verbose:
+ print nismap
+ mapping = nis.cat(nismap)
+ for k, v in mapping.items():
if verbose:
- print nismap
- mapping = nis.cat(nismap)
- for k, v in mapping.items():
- ... |
4bd0637ad181c5ded8c6e5fa9ae79ab607b70aeb | geokey_dataimports/__init__.py | geokey_dataimports/__init__.py | """Main initialisation for extension."""
VERSION = (0, 2, 2)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_dataimports',
'Data Imports',
display_admin=True,
superuser=False,
version=__version__
)
excep... | """Main initialisation for extension."""
VERSION = (0, 3, 0)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_dataimports',
'Data Imports',
display_admin=True,
superuser=False,
version=__version__
)
excep... | Increment minor version number ahead of release. | Increment minor version number ahead of release. | Python | mit | ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports | ---
+++
@@ -1,6 +1,6 @@
"""Main initialisation for extension."""
-VERSION = (0, 2, 2)
+VERSION = (0, 3, 0)
__version__ = '.'.join(map(str, VERSION))
|
b624552af638652147ca8b5e49ca109a4723dca1 | MoMMI/Modules/development.py | MoMMI/Modules/development.py | from discord import Message
from typing import re as typing_re
from MoMMI.commands import command
from MoMMI.master import master
from MoMMI.server import MChannel
@command("reload", "reload", roles=["owner"])
async def reload(channel: MChannel, match: typing_re.Match, message: Message):
await master.reload_module... | from discord import Message
from typing import re as typing_re
from MoMMI.commands import command
from MoMMI.master import master
from MoMMI.server import MChannel
from MoMMI.role import MRoleType
@command("reload", "reload", roles=[MRoleType.OWNER])
async def reload(channel: MChannel, match: typing_re.Match, message:... | Fix dev commands using string roles. | Fix dev commands using string roles.
| Python | mit | PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI | ---
+++
@@ -3,12 +3,13 @@
from MoMMI.commands import command
from MoMMI.master import master
from MoMMI.server import MChannel
+from MoMMI.role import MRoleType
-@command("reload", "reload", roles=["owner"])
+@command("reload", "reload", roles=[MRoleType.OWNER])
async def reload(channel: MChannel, match: typing... |
a003a7b0d52365c5f5976c7382bc1daf2f5960ac | glitter_news/search_indexes.py | glitter_news/search_indexes.py | # -*- coding: utf-8 -*-
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model... | # -*- coding: utf-8 -*-
from django.utils import timezone
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return Post
def index_queryset(self, using=No... | Fix the queryset for news indexing | Fix the queryset for news indexing
| Python | bsd-2-clause | blancltd/glitter-news | ---
+++
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
+from django.utils import timezone
from haystack import indexes
from .models import Post
@@ -12,8 +13,5 @@
return Post
def index_queryset(self, using=None):
- return self.get_model().objects.select_related().filter(
- published=T... |
bd6b969b85a1c8df7cf8d6da7b93f5c94cf8a180 | sum-of-multiples/sum_of_multiples.py | sum-of-multiples/sum_of_multiples.py | def sum_of_multiples(limit, factors):
return sum(filter(lambda n: n < limit,
{f*i for i in range(1, limit) for f in factors}))
| def sum_of_multiples(limit, factors):
return sum({n for f in factors for n in range(f, limit, f)})
| Use more optimal method of getting multiples | Use more optimal method of getting multiples
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,3 +1,2 @@
def sum_of_multiples(limit, factors):
- return sum(filter(lambda n: n < limit,
- {f*i for i in range(1, limit) for f in factors}))
+ return sum({n for f in factors for n in range(f, limit, f)}) |
cfa0b71f056c88f14f79f4f47a169ade9ce08096 | serrano/resources/base.py | serrano/resources/base.py | from restlib2.resources import Resource
from avocado.models import DataContext
class BaseResource(Resource):
param_defaults = {}
def get_params(self, request):
params = request.GET.copy()
for param, default in self.param_defaults.items():
params.setdefault(param, default)
... | from restlib2.resources import Resource
from avocado.models import DataContext, DataView
class BaseResource(Resource):
param_defaults = {}
def get_params(self, request):
params = request.GET.copy()
for param, default in self.param_defaults.items():
params.setdefault(param, default... | Add method to get the most appropriate DataView | Add method to get the most appropriate DataView | Python | bsd-2-clause | rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano | ---
+++
@@ -1,5 +1,5 @@
from restlib2.resources import Resource
-from avocado.models import DataContext
+from avocado.models import DataContext, DataView
class BaseResource(Resource):
@@ -37,3 +37,30 @@
pass
return DataContext()
+
+ def get_view(self, request):
+ params = s... |
c5aa1c7ee17313e3abe156c2bfa429f124a451d5 | bc125csv/__init__.py | bc125csv/__init__.py | """
bc125csv - Channel import and export tool for the Uniden BC125AT, UBC125XLT
and UBC126AT.
Copyright (c) 2015, fdev.nl. All rights reserved.
Released under the MIT license.
Uniden and Bearcat are registered trademarks of Uniden America Corporation.
This application and its author are not affiliated with or endors... | """
bc125csv - Channel import and export tool for the Uniden BC125AT, UBC125XLT
and UBC126AT.
Copyright (c) 2015, fdev.nl. All rights reserved.
Released under the MIT license.
Uniden and Bearcat are registered trademarks of Uniden America Corporation.
This application and its author are not affiliated with or endors... | Call main when run directly | Call main when run directly
| Python | mit | fdev/bc125csv | ---
+++
@@ -17,3 +17,6 @@
# Expose main function for setup.py console_scripts
from bc125csv.handler import main
+
+if __name__ == "__main__":
+ main() |
d6b9be8145316f6f90e47bb3a55c861f993a375a | tweetyr.py | tweetyr.py | #!/usr/bin/env python
# -*- coding: UTF-8
'''
A simple twitter client that posts current weather to twitter
'''
import tweepy
import json
from urllib2 import urlopen
import os
root =os.path.dirname(os.path.abspath(__file__))
conf = json.loads(file(root+'/twitterconfig.json').read())
auth = tweepy.OAuthHandler(conf['... | #!/usr/bin/env python
# -*- coding: UTF-8
'''
A simple twitter client that posts current weather to twitter
'''
import tweepy
import json
from urllib2 import urlopen
import os
root = os.path.dirname(os.path.abspath(__file__))
conf = json.loads(file(root+'/twitterconfig.json').read())
auth = tweepy.OAuthHandler(conf['... | Add geo info to status update | Add geo info to status update
| Python | bsd-3-clause | torhve/Amatyr,torhve/Amatyr,torhve/Amatyr | ---
+++
@@ -8,14 +8,14 @@
from urllib2 import urlopen
import os
-root =os.path.dirname(os.path.abspath(__file__))
-
+root = os.path.dirname(os.path.abspath(__file__))
conf = json.loads(file(root+'/twitterconfig.json').read())
auth = tweepy.OAuthHandler(conf['consumerkey'], conf['consumersecret'])
auth.set_ac... |
00ddeefdcdacb811f5e665a91139e165d7217f84 | week1/poc_2048_merge_template.py | week1/poc_2048_merge_template.py | """
Merge function for 2048 game.
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
l = len(line)
s1 = [0]*l
j = 0
for i in range(l):
if l[i] != 0:
s1[j] = l[i]
return []
a = [2,0,2,4]
print merge(a) | """
Merge function for 2048 game.
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
l = len(line)
s1 = [0]*l
j = 0
for i in range(l):
if line[i] != 0:
s1[j] = line[i]
j += 1
return s1
a = [2,0,2,4]
print (merge(a)) | Modify the correct merge 1 fct | Modify the correct merge 1 fct
| Python | mit | Crescent-Saturn/Principles-of-Computing | ---
+++
@@ -10,11 +10,11 @@
s1 = [0]*l
j = 0
for i in range(l):
- if l[i] != 0:
- s1[j] = l[i]
-
- return []
+ if line[i] != 0:
+ s1[j] = line[i]
+ j += 1
+ return s1
a = [2,0,2,4]
-print merge(a)
+print (merge(a)) |
dafde564f3ea18655b1e15f410df70d05b3eb8f5 | beets/util/collections.py | beets/util/collections.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | Add __future__ imports to a new module | Add __future__ imports to a new module
| Python | mit | mosesfistos1/beetbox,ibmibmibm/beets,mosesfistos1/beetbox,MyTunesFreeMusic/privacy-policy,artemutin/beets,jackwilsdon/beets,sampsyo/beets,pkess/beets,xsteadfastx/beets,shamangeorge/beets,diego-plan9/beets,MyTunesFreeMusic/privacy-policy,jackwilsdon/beets,beetbox/beets,sampsyo/beets,beetbox/beets,madmouser1/beets,beetbo... | ---
+++
@@ -12,8 +12,11 @@
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
-"""Custom collections classes
+
+"""Custom collections classes.
"""
+
+from __future__ import division, absolute_import, print_function
class Identi... |
c178e9aba40f6cf775dce5badf60cff9acd9e908 | boardinghouse/__init__.py | boardinghouse/__init__.py | """
"""
__version__ = '0.1'
__release__ = '0.1a2'
def inject_app_defaults():
try:
import settings as app_settings
from django.conf import settings, global_settings
from django.core.exceptions import ImproperlyConfigured
except ImportError:
return
for key in dir(app_settings... | """
"""
__version__ = '0.1'
__release__ = '0.1a2'
def inject_app_defaults():
"""
Automatically inject the default settings for this app.
If settings has already been configured, then we need to add
our defaults to that (if not overridden), and in all cases we
also want to inject our settings i... | Document where we got settings injection from. | Document where we got settings injection from.
| Python | bsd-3-clause | schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse | ---
+++
@@ -4,6 +4,18 @@
__release__ = '0.1a2'
def inject_app_defaults():
+ """
+ Automatically inject the default settings for this app.
+
+ If settings has already been configured, then we need to add
+ our defaults to that (if not overridden), and in all cases we
+ also want to inject our se... |
f8ae44cb19584a2b7d08b08dc4f32651acfe90f9 | core/templatetags/tags.py | core/templatetags/tags.py | from core.models import Comment, Tag
from django import template
register = template.Library()
#May want to ditch this for a middleware that passes in the comments object so that I can do the manipulations in the actual template
@register.simple_tag
def recent_comments():
comments = Comment.objects.select_r... | from core.models import Comment, Tag
from django import template
register = template.Library()
#May want to ditch this for a middleware that passes in the comments object so that I can do the manipulations in the actual template
@register.simple_tag
def recent_comments():
comments = Comment.objects.select_r... | Remove website from recent comments | Remove website from recent comments
| Python | bsd-2-clause | mburst/burstolio,mburst/burstolio,mburst/burstolio | ---
+++
@@ -13,8 +13,6 @@
for comment in comments:
if not comment.name:
comment.name = "Anonymous"
- if comment.website:
- output += '<li><a href="' + comment.website + '">' + comment.name + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title... |
d7ed79ec53279f0fea0881703079a1c5b82bf938 | _settings.py | _settings.py | # Configuration settings
# ID of HPO to validate (see resources/hpo.csv)
hpo_id = 'hpo_id'
# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'
# sprint number being validated against
sprint_num = 0
# Submissions and logs stored here
# For more examples and requirements see http://docs.sqlalchemy... | # Configuration settings
# ID of HPO to validate (see resources/hpo.csv)
hpo_id = 'hpo_id'
# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'
# sprint number being validated against
sprint_num = 0
# Submissions and logs stored here
# Note: Connecting to MSSQL from *nix may require FreeTDS confi... | Add comment regarding freetds config | Add comment regarding freetds config
| Python | mit | cumc-dbmi/pmi_sprint_reporter | ---
+++
@@ -10,5 +10,6 @@
sprint_num = 0
# Submissions and logs stored here
+# Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY)
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/p... |
703ff26008525bce769b137fafe51ac080a6af81 | plyer/platforms/ios/compass.py | plyer/platforms/ios/compass.py | '''
iOS Compass
---------------------
'''
from plyer.facades import Compass
from pyobjus import autoclass
class IosCompass(Compass):
def __init__(self):
super(IosCompass, self).__init__()
self.bridge = autoclass('bridge').alloc().init()
self.bridge.motionManager.setMagnetometerUpdateInte... | '''
iOS Compass
-----------
'''
from plyer.facades import Compass
from pyobjus import autoclass
class IosCompass(Compass):
def __init__(self):
super(IosCompass, self).__init__()
self.bridge = autoclass('bridge').alloc().init()
self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1)... | Add iOS implementation to get uncalibrated values | Add iOS implementation to get uncalibrated values
| Python | mit | kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer | ---
+++
@@ -1,6 +1,6 @@
'''
iOS Compass
----------------------
+-----------
'''
from plyer.facades import Compass
@@ -13,18 +13,30 @@
super(IosCompass, self).__init__()
self.bridge = autoclass('bridge').alloc().init()
self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1)
+ ... |
74d402684d4c949bfc69b9fa5e34f5f560339da7 | api/caching/tasks.py | api/caching/tasks.py | import urlparse
import requests
from celery.utils.log import get_task_logger
from api.base import settings
logger = get_task_logger(__name__)
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
def ban_url(url):
timeout = 0.5... | import urlparse
import requests
import logging
from api.base import settings
logger = logging.getLogger(__name__)
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
def ban_url(url):
timeout = 0.5 # 500ms timeout for bans
... | Switch from celery task logger to logger | Switch from celery task logger to logger
| Python | apache-2.0 | doublebits/osf.io,aaxelb/osf.io,aaxelb/osf.io,Nesiehr/osf.io,wearpants/osf.io,aaxelb/osf.io,doublebits/osf.io,samchrisinger/osf.io,zamattiac/osf.io,asanfilippo7/osf.io,HalcyonChimera/osf.io,rdhyee/osf.io,abought/osf.io,cwisecarver/osf.io,RomanZWang/osf.io,chrisseto/osf.io,emetsger/osf.io,brianjgeiger/osf.io,laurenrever... | ---
+++
@@ -1,11 +1,10 @@
import urlparse
import requests
-from celery.utils.log import get_task_logger
-
+import logging
from api.base import settings
-logger = get_task_logger(__name__)
+logger = logging.getLogger(__name__)
def get_varnish_servers():
# TODO: this should get the varnish servers from ... |
52a07b32eb499d74b1770a42ac0851be71da8288 | polygraph/types/object_type.py | polygraph/types/object_type.py | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
self.name = getattr(meta, 'name', None)
self... | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... | Modify ObjectType to derive description from docstring | Modify ObjectType to derive description from docstring
| Python | mit | polygraph-python/polygraph | ---
+++
@@ -2,6 +2,8 @@
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
+
+from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
@@ -20,10 +22,12 @@
super().__init__(only, exclude, prefix, strict,
... |
3cccb20cb9de803867084cab47f43401bf044e63 | backend/sponsors/models.py | backend/sponsors/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from ordered_model.models import OrderedModel
class SponsorLevel(OrderedModel):
name = models.CharField(_("name"), max_length=20)
conference = models.ForeignKey(
"confer... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from ordered_model.models import OrderedModel
class SponsorLevel(OrderedModel):
name = models.CharField(_("name"), max_length=20)
conference = models.ForeignKey(
"confer... | Fix sponsor level name in the django admin | Fix sponsor level name in the django admin
| Python | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -12,6 +12,9 @@
verbose_name=_("conference"),
related_name="sponsor_levels",
)
+
+ def __str__(self):
+ return self.name
class Meta(OrderedModel.Meta):
unique_together = ["name", "conference"] |
9db490d5d175f108231cc87afd87a593359837e8 | app/views.py | app/views.py | import os
from flask import render_template, jsonify, request
from app import app
import pymysql as mdb
con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1')
@app.route('/')
@app.route('/index')
def index():
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FROM A... | import os
from flask import render_template, jsonify, request
from app import app
import pymysql as mdb
@app.route('/')
@app.route('/index')
def index():
con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1')
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FRO... | Fix the disconnect after 8 hours bug. | Fix the disconnect after 8 hours bug.
| Python | mit | jbwhit/hammer-pricer,jbwhit/hammer-pricer | ---
+++
@@ -3,11 +3,10 @@
from app import app
import pymysql as mdb
-con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1')
-
@app.route('/')
@app.route('/index')
def index():
+ con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1')
with con:
cur = con.cursor(mdb.cursors.Di... |
d90dadca57437def08416638267f2b2db2e7fe3f | pytest_raises/pytest_raises.py | pytest_raises/pytest_raises.py | # -*- coding: utf-8 -*-
import sys
import pytest
class ExpectedException(Exception):
pass
class ExpectedMessage(Exception):
pass
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
outcome = yield
raises_marker = item.get_marker('raises')
if raises_marker:
exception = ra... | # -*- coding: utf-8 -*-
import sys
import pytest
class ExpectedException(Exception):
pass
class ExpectedMessage(Exception):
pass
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
outcome = yield
raises_marker = item.get_closest_marker('raises')
if raises_marker:
except... | Update marker call for pytest 3.6+ | Update marker call for pytest 3.6+
| Python | mit | Authentise/pytest-raises,Authentise/pytest-raises | ---
+++
@@ -15,7 +15,7 @@
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
outcome = yield
- raises_marker = item.get_marker('raises')
+ raises_marker = item.get_closest_marker('raises')
if raises_marker:
exception = raises_marker.kwargs.get('exception')
exception ... |
b16c49cfd6a0ee659e4493ef959e0483e93d350a | os_client_config/defaults.py | os_client_config/defaults.py | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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 appli... | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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 appli... | Add default versions for trove and ironic | Add default versions for trove and ironic
Change-Id: Ib7af38664cfbe75c78c70693117f1193c4beb7e6
| Python | apache-2.0 | openstack/python-openstacksdk,stackforge/python-openstacksdk,redhat-openstack/os-client-config,dtroyer/python-openstacksdk,openstack/os-client-config,dtroyer/python-openstacksdk,switch-ch/os-client-config,stackforge/python-openstacksdk,dtroyer/os-client-config,openstack/python-openstacksdk | ---
+++
@@ -14,7 +14,9 @@
_defaults = dict(
auth_type='password',
+ baremetal_api_version='1',
compute_api_version='2',
+ database_api_version='1.0',
floating_ip_source='neutron',
identity_api_version='2',
image_api_use_tasks=False, |
c5bfe6f408163267a16b8137e5871943657fb211 | conftest.py | conftest.py | from __future__ import absolute_import
pytest_plugins = [
'sentry.utils.pytest'
]
def pytest_configure(config):
from django.conf import settings
settings.INSTALLED_APPS += ('sentry_jira',)
| from __future__ import absolute_import
import os
os.environ.setdefault('DB', 'sqlite')
pytest_plugins = [
'sentry.utils.pytest'
]
def pytest_configure(config):
from django.conf import settings
settings.INSTALLED_APPS += ('sentry_jira',)
| Fix tests to run against sqlite | Fix tests to run against sqlite
| Python | bsd-3-clause | getsentry/sentry-jira,thurloat/sentry-jira,thurloat/sentry-jira,getsentry/sentry-jira | ---
+++
@@ -1,4 +1,7 @@
from __future__ import absolute_import
+
+import os
+os.environ.setdefault('DB', 'sqlite')
pytest_plugins = [
'sentry.utils.pytest' |
389330f4cd1d49ab8fdcfa9554046dedbc5dcffc | plugins/Views/SimpleView/__init__.py | plugins/Views/SimpleView/__init__.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
... | Hide simple view by default | Hide simple view by default
It is an example implementation, most actual applications would probably
use something with more features.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -16,7 +16,8 @@
"api": 2
},
"view": {
- "name": i18n_catalog.i18nc("@item:inmenu", "Simple")
+ "name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
+ "visible": False
}
}
|
87778eec6425c9bc8ae80f6ad8a0264986d1e7c1 | api/base/views.py | api/base/views.py | from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
# TODO: Use user serializer
current_... | from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
... | Use UserSerializer to serialize current user in the root response | Use UserSerializer to serialize current user in the root response
| Python | apache-2.0 | HarryRybacki/osf.io,cosenal/osf.io,jeffreyliu3230/osf.io,leb2dg/osf.io,erinspace/osf.io,aaxelb/osf.io,Ghalko/osf.io,chennan47/osf.io,abought/osf.io,saradbowman/osf.io,barbour-em/osf.io,TomHeatwole/osf.io,ZobairAlijan/osf.io,dplorimer/osf,DanielSBrown/osf.io,alexschiller/osf.io,samanehsan/osf.io,reinaH/osf.io,RomanZWang... | ---
+++
@@ -2,6 +2,7 @@
from rest_framework.response import Response
from .utils import absolute_reverse
+from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
@@ -9,15 +10,14 @@
if request.user and not request.user.is_anonymous():
user = request.us... |
d9b804f72e54ffc9cb0f1cef8ce74aef1079ef76 | tosec/management/commands/tosecscan.py | tosec/management/commands/tosecscan.py | import os
import hashlib
from tosec.models import Rom
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC')
... | import os
import hashlib
from tosec.models import Rom, Game
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC'... | Print report on imported TOSEC sets | Print report on imported TOSEC sets
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website | ---
+++
@@ -1,6 +1,6 @@
import os
import hashlib
-from tosec.models import Rom
+from tosec.models import Rom, Game
from django.core.management.base import BaseCommand
@@ -14,17 +14,31 @@
if not os.path.exists(dest):
os.makedirs(dest)
self.stdout.write("Scanning %s" % directory)
-... |
6beefdaf46e3febbb106bd72da58ed62fc1349f0 | scripts/graph/wavefront_obj.py | scripts/graph/wavefront_obj.py | import numpy as np
def readObj(filename):
vert = []
face = []
with open(filename, 'r') as file:
for line in file:
l = line.split()
if len(l) > 0:
if l[0] == 'v':
vert.append(l[1:])
elif l[0] == 'f':
face.append(l[1:])
return (np.array(vert, np.double), np.a... | import numpy as np
def readObj(filename):
vert = []
face = []
with open(filename, 'r') as file:
for line in file:
l = line.split()
if len(l) > 0:
if l[0] == 'v':
vert.append(l[1:])
elif l[0] == 'f':
face.append(l[1:])
return (np.array(vert, np.double), np.a... | Fix wavefront obj face index. | Fix wavefront obj face index.
| Python | bsd-2-clause | gergondet/RBDyn,gergondet/RBDyn,gergondet/RBDyn,gergondet/RBDyn,jrl-umi3218/RBDyn,jrl-umi3218/RBDyn,jrl-umi3218/RBDyn,gergondet/RBDyn,jrl-umi3218/RBDyn | ---
+++
@@ -13,5 +13,5 @@
elif l[0] == 'f':
face.append(l[1:])
- return (np.array(vert, np.double), np.array(face, np.int))
+ return (np.array(vert, np.double), np.array(face, np.int) - 1)
|
dc377e246e65db8257298eb604c032313d8a113e | propertyfrontend/__init__.py | propertyfrontend/__init__.py | import os, logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from raven.contrib.flask import Sentry
from lrutils import dateformat
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.jinja_env.filters['dateformat'] = dateformat
if app.config.get('BASIC_AUTH_USERNAME'... | import os, logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from raven.contrib.flask import Sentry
from lrutils import dateformat
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
app.j... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/property-frontend-alpha,LandRegistry/property-frontend-alpha,LandRegistry/property-frontend-alpha,LandRegistry/property-frontend-alpha | ---
+++
@@ -7,6 +7,9 @@
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
+
+from werkzeug.contrib.fixers import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
app.jinja_env.filters['dateformat'] = dateformat
|
05db0c3dc6affdc3938d45195fb807be78ae5ff1 | dit/math/__init__.py | dit/math/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Mathematical tools for dit.
"""
from __future__ import absolute_import
# Global random number generator
import numpy as np
prng = np.random.RandomState()
# Set the error level to ignore...for example: log2(0).
np.seterr(all='ignore')
del np
from .equal import close,... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Mathematical tools for dit.
"""
from __future__ import absolute_import
# Global random number generator
import numpy as np
prng = np.random.RandomState()
# Set the error level to ignore...for example: log2(0).
np.seterr(all='ignore')
del np
from .equal import close,... | Make perturb_pmf available in dit.math. | Make perturb_pmf available in dit.math.
| Python | bsd-3-clause | Autoplectic/dit,chebee7i/dit,chebee7i/dit,Autoplectic/dit,Autoplectic/dit,Autoplectic/dit,Autoplectic/dit,dit/dit,dit/dit,chebee7i/dit,dit/dit,dit/dit,chebee7i/dit,dit/dit | ---
+++
@@ -19,6 +19,7 @@
from .ops import get_ops, LinearOperations, LogOperations
from .fraction import approximate_fraction
from .sigmaalgebra import sigma_algebra, is_sigma_algebra, atom_set
+from .perturb import perturb_pmf
from . import aitchison
from . import combinatorics |
5a7f88a7d033a8005d09792d62827689d6d5230d | mox3/fixture.py | mox3/fixture.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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://... | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# Unles... | Remove vim header from source files | Remove vim header from source files
trivialfix
Change-Id: I6ccd551bc5cec8f5a682502b0a6e99a6d02cad3b
| Python | apache-2.0 | openstack/mox3 | ---
+++
@@ -1,5 +1,3 @@
-# vim: tabstop=4 shiftwidth=4 softtabstop=4
-
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
# |
6692476cc7523516275f4512c32b0378574210bf | django_tenants/routers.py | django_tenants/routers.py | from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_migrate(self, db, app_label, model_name=None, **hints):
# the imports below need to be ... | from django.conf import settings
from django.apps import apps as django_apps
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def app_in_list(self, app_label, apps_list):
"""
... | Fix check of an app's presence in INSTALLED_APPS | Fix check of an app's presence in INSTALLED_APPS
In TenantSyncRouter, the logic to check whether an app is a tenant app or shared app was too simplistic. Django 1.7 allows two ways to add an app to INSTALLED_APPS. 1) By specifying the app's name, and 2) By specifying the dotted path to the app's AppConfig's class. Thi... | Python | mit | sigma-geosistemas/django-tenants,tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants,sigma-geosistemas/django-tenants | ---
+++
@@ -1,4 +1,5 @@
from django.conf import settings
+from django.apps import apps as django_apps
class TenantSyncRouter(object):
@@ -7,21 +8,33 @@
depending if we are syncing the shared apps or the tenant apps.
"""
+ def app_in_list(self, app_label, apps_list):
+ """
+ Is 'app_... |
3749294ae008c8bda7de9ea538d3d64d5a21c8f4 | driller/CGCSimProc.py | driller/CGCSimProc.py | import angr
import simuvex
class DrillerTransmit(simuvex.SimProcedure):
'''
CGC's transmit simprocedure which supports errors
'''
def run(self, fd, buf, count, tx_bytes):
if self.state.mode == 'fastpath':
# Special case for CFG generation
self.state.store_mem(tx_bytes,... | import angr
import simuvex
class DrillerTransmit(simuvex.SimProcedure):
'''
CGC's transmit simprocedure which supports errors
'''
def run(self, fd, buf, count, tx_bytes):
if self.state.mode == 'fastpath':
# Special case for CFG generation
self.state.store_mem(tx_bytes,... | Disable CGC simprocedures, it's unhelpful at the moment | Disable CGC simprocedures, it's unhelpful at the moment
| Python | bsd-2-clause | shellphish/driller | ---
+++
@@ -38,4 +38,5 @@
return transmit_return
-simprocedures = [("transmit", DrillerTransmit)]
+# disable simprocedures for CGC
+simprocedures = [] |
cb49f6d3f0ecb367fd76afe2e98c55e48ba1128f | bin/gephi-mock.py | bin/gephi-mock.py | #!/usr/bin/env python
#
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | #!/usr/bin/env python3
#
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
... | Switch to python3 specifically in gephi mock script. | Switch to python3 specifically in gephi mock script.
Can't change the docker image to make python==python3 right now because we need python2 on the image as it is used in the older branches that still support that version. CTR
| Python | apache-2.0 | apache/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,... | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
#
# Licensed to the Apache Software Foundation (ASF) under one |
b7971d68256b23646de1ef648181da5ceacd67f8 | scipy/constants/tests/test_codata.py | scipy/constants/tests/test_codata.py |
import warnings
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
... |
import warnings
import codata
import constants
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = fin... | Add very basic tests for codata and constants. | ENH: Add very basic tests for codata and constants.
| Python | bsd-3-clause | WarrenWeckesser/scipy,arokem/scipy,aeklant/scipy,vhaasteren/scipy,lhilt/scipy,jseabold/scipy,fernand/scipy,e-q/scipy,nonhermitian/scipy,ndchorley/scipy,newemailjdm/scipy,scipy/scipy,grlee77/scipy,zerothi/scipy,FRidh/scipy,Shaswat27/scipy,trankmichael/scipy,mgaitan/scipy,vigna/scipy,woodscn/scipy,andyfaff/scipy,jonycgn/... | ---
+++
@@ -1,5 +1,8 @@
import warnings
+
+import codata
+import constants
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
@@ -26,5 +29,15 @@
'natural unit of length',
'natural unit of time']))
+
+def ... |
234e50c105b7d7d1e77e1c392200668891130840 | formish/__init__.py | formish/__init__.py | """
Base package to import top level modules
"""
from formish.forms import Form
from formish.validation import FieldError, FormError, FormishError
from formish.widgets import *
from formish.util import form_in_request
| """
Base package to import top level modules
"""
from formish.forms import Form
from formish.validation import FieldError, FormError, FormishError, NoActionError
from formish.widgets import *
from formish.util import form_in_request
| Add missing exception to package-level exports. | Add missing exception to package-level exports.
| Python | bsd-3-clause | ish/formish,ish/formish,ish/formish | ---
+++
@@ -2,7 +2,7 @@
Base package to import top level modules
"""
from formish.forms import Form
-from formish.validation import FieldError, FormError, FormishError
+from formish.validation import FieldError, FormError, FormishError, NoActionError
from formish.widgets import *
from formish.util import form_in... |
097cc817894c8bd05711f92916b184b88c108fb9 | decision/__init__.py | decision/__init__.py | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTR... | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
app.logger.debug("\nConfiguration\n%s\n" % app.config)
# Sentry exception rep... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/decision-alpha,LandRegistry/decision-alpha | ---
+++
@@ -5,6 +5,9 @@
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
+
+from werkzeug.contrib.fixers import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
app.logger.debug("\nConfiguration\n%s\n" % app.config)
|
8866a828e029c2db6439c16d49ba636e460fbf49 | go/apps/tests/base.py | go/apps/tests/base.py | from django.conf import settings
from vumi.tests.utils import FakeRedis
from go.base.tests.utils import VumiGoDjangoTestCase, declare_longcode_tags
from go.vumitools.tests.utils import CeleryTestMixIn
from go.vumitools.api import VumiApi
class DjangoGoApplicationTestCase(VumiGoDjangoTestCase, CeleryTestMixIn):
... | from django.conf import settings
from vumi.tests.utils import FakeRedis
from go.base.tests.utils import VumiGoDjangoTestCase, declare_longcode_tags
from go.vumitools.tests.utils import CeleryTestMixIn
from go.vumitools.api import VumiApi
class DjangoGoApplicationTestCase(VumiGoDjangoTestCase, CeleryTestMixIn):
... | Fix buglet introduced by longcode clean-up. | Fix buglet introduced by longcode clean-up.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -12,7 +12,7 @@
def setUp(self):
super(DjangoGoApplicationTestCase, self).setUp()
self.setup_api()
- self.declare_longcode_tags(self.api)
+ self.declare_longcode_tags()
self.setup_celery_for_tests()
def tearDown(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.