commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
1648e071fe69ba159261f27e4b2d0e2b977d6d83 | zou/app/models/working_file.py | zou/app/models/working_file.py | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(db.String(250))
description = db.Col... | from sqlalchemy.orm import relationship
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(... | Add fields to working file model | Add fields to working file model
* Software
* List of output files generated
* Path used to store the working file
| Python | agpl-3.0 | cgwire/zou |
afb195b1ca647d776f29fbc1d68a495190caec59 | astropy/time/setup_package.py | astropy/time/setup_package.py | import os
import numpy
from distutils.extension import Extension
TIMEROOT = os.path.relpath(os.path.dirname(__file__))
def get_extensions():
time_ext = Extension(
name="astropy.time.sofa_time",
sources=[os.path.join(TIMEROOT, "sofa_time.pyx"), "cextern/sofa/sofa.c"],
include_dirs=[numpy.get_include()... | import os
from distutils.extension import Extension
TIMEROOT = os.path.relpath(os.path.dirname(__file__))
def get_extensions():
time_ext = Extension(
name="astropy.time.sofa_time",
sources=[os.path.join(TIMEROOT, "sofa_time.pyx"), "cextern/sofa/sofa.c"],
include_dirs=['numpy', 'cextern/sofa'],
la... | Fix remaining include_dirs that imported numpy ('numpy' gets replaced at build-time). This is necessary for egg_info to work. | Fix remaining include_dirs that imported numpy ('numpy' gets replaced at build-time). This is necessary for egg_info to work. | Python | bsd-3-clause | kelle/astropy,AustereCuriosity/astropy,joergdietrich/astropy,stargaser/astropy,astropy/astropy,bsipocz/astropy,bsipocz/astropy,kelle/astropy,larrybradley/astropy,StuartLittlefair/astropy,DougBurke/astropy,mhvk/astropy,stargaser/astropy,aleksandr-bakanov/astropy,tbabej/astropy,dhomeier/astropy,lpsinger/astropy,DougBurke... |
55d22f95301c4c96c42e30fa037df5bc957dc7b4 | incunafein/module/page/extensions/prepared_date.py | incunafein/module/page/extensions/prepared_date.py | from django.db import models
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
| from django.db import models
def get_prepared_date(cls):
return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
cls.add_to_class('get_prepared_date', get_prepared_date)
| Add a get prepared date method | Add a get prepared date method
Child pages won't necessarily have a prepared date and it makes sense to
use the parent date to avoid repetition.
| Python | bsd-2-clause | incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms |
0fdb33dc0da1aa953e91e71b0e0cfa75fca3d639 | skylines/views/__init__.py | skylines/views/__init__.py | from flask import redirect
from skylines import app
import skylines.views.i18n
import skylines.views.login
import skylines.views.search
from skylines.views.about import about_blueprint
from skylines.views.api import api_blueprint
from skylines.views.flights import flights_blueprint
from skylines.views.notifications ... | from flask import redirect, url_for
from skylines import app
import skylines.views.i18n
import skylines.views.login
import skylines.views.search
from skylines.views.about import about_blueprint
from skylines.views.api import api_blueprint
from skylines.views.flights import flights_blueprint
from skylines.views.notif... | Use url_for for base redirection | views: Use url_for for base redirection
| Python | agpl-3.0 | shadowoneau/skylines,Turbo87/skylines,snip/skylines,shadowoneau/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,RBE-Avionik/skylines,kerel-fs/skylines,Turbo87/skylines,snip/skylines,kerel-fs/skylines,skylines-project/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,skylines-project/skylines,RBE-... |
cc3ab3af17e30e7dd9991d68f01eaa4535b64e6b | djangae/models.py | djangae/models.py | from django.db import models
class CounterShard(models.Model):
count = models.PositiveIntegerField()
| from django.db import models
class CounterShard(models.Model):
count = models.PositiveIntegerField()
#Apply our django patches
from .patches import * | Patch update_contenttypes so that it's less likely to fail due to eventual consistency | Patch update_contenttypes so that it's less likely to fail due to eventual consistency
| Python | bsd-3-clause | nealedj/djangae,martinogden/djangae,grzes/djangae,stucox/djangae,asendecka/djangae,trik/djangae,trik/djangae,wangjun/djangae,armirusco/djangae,b-cannon/my_djae,jscissr/djangae,grzes/djangae,wangjun/djangae,chargrizzle/djangae,chargrizzle/djangae,leekchan/djangae,kirberich/djangae,martinogden/djangae,pablorecio/djangae,... |
776c3b0df6136606b8b7474418fd5d078457bd0a | test/persistence_test.py | test/persistence_test.py | from os.path import exists, join
import shutil
import tempfile
import time
from lwr.managers.queued import QueueManager
from lwr.managers.stateful import StatefulManagerProxy
from lwr.tools.authorization import get_authorizer
from .test_utils import TestDependencyManager
from galaxy.util.bunch import Bunch
def test... | from os.path import exists, join
import shutil
import tempfile
import time
from lwr.managers.queued import QueueManager
from lwr.managers.stateful import StatefulManagerProxy
from lwr.tools.authorization import get_authorizer
from .test_utils import TestDependencyManager
from galaxy.util.bunch import Bunch
from galax... | Fix another failing unit test (from metrics work). | Fix another failing unit test (from metrics work).
| Python | apache-2.0 | jmchilton/lwr,natefoo/pulsar,natefoo/pulsar,jmchilton/pulsar,galaxyproject/pulsar,jmchilton/pulsar,ssorgatem/pulsar,galaxyproject/pulsar,ssorgatem/pulsar,jmchilton/lwr |
3ee7d716f0eb3202ccf7ca213747eb903f9bb471 | __init__.py | __init__.py | from .Averager import Averager
from .Config import Config
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
from .String import string2time, time2string
from .Timer import Timer
from .UserInput import user_input
| from .Averager import Averager
from .Config import Config
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
from .String import string2time, time2string, time2levels, time2dir, time2fname
from .Timer import Timer
from .UserInput import user_input
| Add missing names to module namespace. | Add missing names to module namespace.
| Python | mit | vmlaker/coils |
c05fc3ae4d6ac0ed459150acf2c19fd892c2ea9f | bumblebee/modules/caffeine.py | bumblebee/modules/caffeine.py | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... | Add some basic error handling in case the executables don't exist | Add some basic error handling in case the executables don't exist
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status |
ffadde617db8ac3d0d5362b4a521dd4e9839710f | order/order_2_login_system_by_https.py | order/order_2_login_system_by_https.py | import json
import requests
""" Order 2: Login system by https
```
curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{
"credentials": {
"username": "admin",
"password": "a10"
}
}'
```
"""
class LoginSystemByHttps(object):
login_url = 'http://192.168.105... | import json
import requests
""" Order 2: Login system by https
This is the code which use curl to login system
```
curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{
"credentials": {
"username": "admin",
"password": "a10"
}
}'
```
"""
class LoginSystemByHt... | Order 2: Login system by https | [Order] Order 2: Login system by https
| Python | mit | flyingSprite/spinelle |
646a248d59f835264729b48a0116d51089f6113e | oscar/templatetags/currency_filters.py | oscar/templatetags/currency_filters.py | from decimal import Decimal as D, InvalidOperation
from django import template
from django.conf import settings
from babel.numbers import format_currency
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
value =... | from decimal import Decimal as D, InvalidOperation
from django import template
from django.conf import settings
from babel.numbers import format_currency
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
value =... | Replace broken babel documentation link | Replace broken babel documentation link
According to Babel's PyPI package page, http://babel.pocoo.org/docs/ is
the official documentation website.
| Python | bsd-3-clause | lijoantony/django-oscar,faratro/django-oscar,michaelkuty/django-oscar,MatthewWilkes/django-oscar,django-oscar/django-oscar,dongguangming/django-oscar,taedori81/django-oscar,pasqualguerrero/django-oscar,marcoantoniooliveira/labweb,faratro/django-oscar,Jannes123/django-oscar,binarydud/django-oscar,Jannes123/django-oscar,... |
315b581b9b0438389c7f4eb651d2893b805a2369 | translit.py | translit.py | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
reverse=True,
... | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
reverse=True,
... | Handle case when char is mapped to empty (removed) and table is inverted | Handle case when char is mapped to empty (removed) and table is inverted
| Python | mit | malexer/SublimeTranslit |
6f8f449316a71dd284d2661d206d88d35c01ea54 | TrevorNet/tests/test_idx.py | TrevorNet/tests/test_idx.py | from .. import idx
import os
def test__find_depth():
yield check__find_depth, 9, 0
yield check__find_depth, [1, 2], 1
yield check__find_depth, [[1, 2], [3, 6, 2]], 2
yield check__find_depth, [[[1,2], [2]]], 3
def check__find_depth(lst, i):
assert idx._find_dimensions(lst) == i
# these two are equ... | from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dime... | Update for python 3 and new idx design | Update for python 3 and new idx design
idx no longer writes to files, it only processes bytes
| Python | mit | tmerr/trevornet |
564075cbb66c6e79a6225d7f678aea804075b966 | api/urls.py | api/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'fbxnano.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url('^status$', TemplateView.as_view(template_name='api/status.html'), name=... | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from .views import StatusView
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'fbxnano.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url('^status$', StatusView.as_view(), name=... | Switch from generic TemplateView to new StatusView | Switch from generic TemplateView to new StatusView
| Python | mit | Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano |
e615e2ebf3f364ba093c48d6fb0c988f0b97bc13 | nyuki/workflow/tasks/__init__.py | nyuki/workflow/tasks/__init__.py | from .factory import FactoryTask
from .report import ReportTask
from .sleep import SleepTask
# Generic schema to reference a task ID
TASKID_SCHEMA = {
'type': 'string',
'description': 'task_id'
}
| from .factory import FactoryTask
from .report import ReportTask
from .sleep import SleepTask
# Generic schema to reference a task ID
TASKID_SCHEMA = {
'type': 'string',
'description': 'task_id',
'maxLength': 128
}
| Add maxlength to taskid schema | Add maxlength to taskid schema
| Python | apache-2.0 | gdraynz/nyuki,optiflows/nyuki,gdraynz/nyuki,optiflows/nyuki |
fe4ce6dfa26c60747b6024fa9f6d991aa3b95614 | scripts/codegen_driverwrappers/generate_driver_wrappers.py | scripts/codegen_driverwrappers/generate_driver_wrappers.py | #!/usr/bin/env python3
import sys
import json
import os
import jinja2
def render(tpl_path):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render()
n = len(sys.argv)
if ( n != 3 ):
sys.exit("The templat... | #!/usr/bin/env python3
import sys
import json
import os
import jinja2
def render(tpl_path):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './'),
keep_trailing_newline=True,
).get_template(filename).render()
n = len(sys.argv)
if ... | Fix trailing newline getting dropped | Fix trailing newline getting dropped
Signed-off-by: Gilles Peskine <f805f64266d288fc5467baa7be6cd0ff366f477b@arm.com>
| Python | apache-2.0 | Mbed-TLS/mbedtls,NXPmicro/mbedtls,NXPmicro/mbedtls,Mbed-TLS/mbedtls,NXPmicro/mbedtls,NXPmicro/mbedtls,ARMmbed/mbedtls,Mbed-TLS/mbedtls,ARMmbed/mbedtls,ARMmbed/mbedtls,Mbed-TLS/mbedtls,ARMmbed/mbedtls |
c264e4b19505bfb0ccebc1551c7b82e96b6a2882 | amqpy/tests/test_version.py | amqpy/tests/test_version.py | class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
readme = f.read().split('\n')
version_list = readme[3].split(':')[2].strip().split('.')
version_list = [int(i) for i in version_list]
readme_... | import re
def get_field(doc: str, name: str):
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
if match:
return match.group(1).strip()
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
... | Clean up test for version number | Clean up test for version number
A new function is implemented to cleanly extract the version field from the
README.rst field list.
| Python | mit | veegee/amqpy,gst/amqpy |
a7830d85c6966732e46da63903c04234d8d16c39 | admin/nodes/serializers.py | admin/nodes/serializers.py | import json
from website.util.permissions import reduce_permissions
from admin.users.serializers import serialize_simple_node
def serialize_node(node):
embargo = node.embargo
if embargo is not None:
embargo = node.embargo.end_date
return {
'id': node._id,
'title': node.title,
... | import json
from website.util.permissions import reduce_permissions
from admin.users.serializers import serialize_simple_node
def serialize_node(node):
embargo = node.embargo
if embargo is not None:
embargo = node.embargo.end_date
return {
'id': node._id,
'title': node.title,
... | Add date_registered to node serializer | Add date_registered to node serializer
[#OSF-7230]
| Python | apache-2.0 | mattclark/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,mattclark/osf.io,caseyrollins/osf.io,chennan47/osf.io,adlius/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,chennan47/osf.io,hmoco/osf.io,caneruguz/osf.io,mfra... |
f625cac0a49bafc96403f5b34c2e138f8d2cfbea | dev/lint.py | dev/lint.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
from flake8.engine import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if ... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import flake8
if flake8.__version_info__ < (3,):
from flake8.engine import get_style_guide
else:
from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.pat... | Add support for flake8 3.0 | Add support for flake8 3.0
| Python | mit | wbond/asn1crypto |
573718a17e5e2d3fe23b1c8cd128a9b46d6076e6 | example-theme.py | example-theme.py | # Supported 16 color values:
# 'h0' (color number 0) through 'h15' (color number 15)
# or
# 'default' (use the terminal's default foreground),
# 'black', 'dark red', 'dark green', 'brown', 'dark blue',
# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',
# 'light red', 'light green', 'yellow', 'light ... | # Supported 16 color values:
# 'h0' (color number 0) through 'h15' (color number 15)
# or
# 'default' (use the terminal's default foreground),
# 'black', 'dark red', 'dark green', 'brown', 'dark blue',
# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',
# 'light red', 'light green', 'yellow', 'light ... | Add link to defined colors to example theme | Add link to defined colors to example theme
| Python | mit | amigrave/pudb,albfan/pudb,amigrave/pudb,albfan/pudb |
b50b7143185131a81e84f0659ff6405317f7d36f | resolwe/flow/execution_engines/base.py | resolwe/flow/execution_engines/base.py | """Workflow execution engines."""
from resolwe.flow.engine import BaseEngine
class BaseExecutionEngine(BaseEngine):
"""A workflow execution engine."""
def evaluate(self, data):
"""Return the code needed to compute a given Data object."""
raise NotImplementedError
def get_expression_engin... | """Workflow execution engines."""
from resolwe.flow.engine import BaseEngine
class BaseExecutionEngine(BaseEngine):
"""A workflow execution engine."""
def evaluate(self, data):
"""Return the code needed to compute a given Data object."""
raise NotImplementedError
def get_expression_engin... | Return empty dictionary instead of None | Return empty dictionary instead of None
| Python | apache-2.0 | genialis/resolwe,genialis/resolwe |
b62f52a30404901ff3ffa7af90a3f1bdd7d05401 | project/hhlcallback/utils.py | project/hhlcallback/utils.py | # -*- coding: utf-8 -*-
import environ
env = environ.Env()
HOLVI_CNC = False
def get_holvi_singleton():
global HOLVI_CNC
if HOLVI_CNC:
return HOLVI_CNC
holvi_pool = env('HOLVI_POOL', default=None)
holvi_key = env('HOLVI_APIKEY', default=None)
if not holvi_pool or not holvi_key:
retu... | # -*- coding: utf-8 -*-
import holviapi.utils
def get_nordea_payment_reference(member_id, number):
base = member_id + 1000
return holviapi.utils.int2fin_reference(int("%s%s" % (base, number)))
| Remove copy-pasted code, add helper for making legacy reference number for payments | Remove copy-pasted code, add helper for making legacy reference number for payments
| Python | mit | HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum |
6f30aed2b5f157bb22c8761a92464302ec5d8911 | DebianChangesBot/utils/__init__.py | DebianChangesBot/utils/__init__.py | # -*- coding: utf-8 -*-
import email.quoprimime
def quoted_printable(val):
try:
if type(val) is str:
return email.quoprimime.header_decode(val)
else:
return unicode(email.quoprimime.header_decode(str(val)), 'utf-8')
except Exception, e:
# We ignore errors here.... | # -*- coding: utf-8 -*-
import email
import re
def header_decode(s):
def unquote_match(match):
s = match.group(0)
return chr(int(s[1:3], 16))
s = s.replace('_', ' ')
return re.sub(r'=\w{2}', unquote_match, s)
def quoted_printable(val):
try:
if type(val) is str:
sa... | Update header_decode to handle bare and non-bare quoted-printable chars | Update header_decode to handle bare and non-bare quoted-printable chars
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | agpl-3.0 | xtaran/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot |
b5b17c5152e969ed4e629a5df8dd296cde164f9b | polymer_states/__init__.py | polymer_states/__init__.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/. | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Link states
UP, DOWN = (0, 1), (0, -1)
LEFT, RIGHT = (-1, 0), (1, 0)
SLACK = (0, 0) | Add link states to polymer_states | Add link states to polymer_states
| Python | mpl-2.0 | szabba/applied-sims |
656c0a9b91ee6f6f3f9811b16ab75dc8003402ad | altair/examples/line_chart_with_generator.py | altair/examples/line_chart_with_generator.py | """
Line Chart with Sequence Generator
----------------------------------
This examples shows how to create multiple lines using the sequence generator.
"""
# category: line charts
import altair as alt
source = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')
alt.Chart(source).mark_line().transform_calculate(
... | """
Line Chart with Sequence Generator
----------------------------------
This examples shows how to create multiple lines using the sequence generator.
"""
# category: line charts
import altair as alt
source = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')
alt.Chart(source).mark_line().transform_calculate(
... | Modify generator example to use single calculation transform | DOC: Modify generator example to use single calculation transform
| Python | bsd-3-clause | jakevdp/altair,altair-viz/altair |
7319ac2eb5d31b14c731371a82102c90d8ec3979 | tests/test_reflection_views.py | tests/test_reflection_views.py | from sqlalchemy import MetaData, Table, inspect
from sqlalchemy.schema import CreateTable
from rs_sqla_test_utils.utils import clean, compile_query
def table_to_ddl(engine, table):
return str(CreateTable(table)
.compile(engine))
def test_view_reflection(redshift_engine):
table_ddl = "CREATE ... | from sqlalchemy import MetaData, Table, inspect
from sqlalchemy.schema import CreateTable
from rs_sqla_test_utils.utils import clean, compile_query
def table_to_ddl(engine, table):
return str(CreateTable(table)
.compile(engine))
def test_view_reflection(redshift_engine):
table_ddl = "CREATE ... | Add test for late-binding views | Add test for late-binding views
| Python | mit | sqlalchemy-redshift/sqlalchemy-redshift,sqlalchemy-redshift/sqlalchemy-redshift,graingert/redshift_sqlalchemy |
e051c915d72b76a189c16de6ff82bcebdab9f881 | caffe2/python/layers/__init__.py | caffe2/python/layers/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from importlib import import_module
import pkgutil
import sys
import inspect
from . import layers
def import_recursive(package, clsmembers):
"""
Takes a package... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from importlib import import_module
import pkgutil
import sys
from . import layers
def import_recursive(package):
"""
Takes a package and imports all modules un... | Allow to import subclasses of layers | Allow to import subclasses of layers
Summary:
We want it to be able to register children of layers who
are not direct children of ModelLayer.
This requires us to find subclasses of ModelLayer recursively.
Reviewed By: kittipatv, kennyhorror
Differential Revision: D5397120
fbshipit-source-id: cb1e03d72e3bedb960b1b86... | Python | apache-2.0 | Yangqing/caffe2,xzturn/caffe2,sf-wind/caffe2,pietern/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,davinwang/caffe2,sf-wind/caffe2,caffe2/caffe2,Yangqing/caffe2,bwasti/caffe2,Yangqing/caffe2,bwasti/caffe2,xzturn/caffe2,pietern/caffe2,davinwang/caffe2,bwasti/caffe2,bwasti/caffe2,sf-wind/caffe2,sf-wind/caffe2,bwa... |
b99770a7c55cd6951df872793a54bfa260b145f9 | basics/test/module-test.py | basics/test/module-test.py | from unittest import TestCase
from basics import BaseCharacter
from basics import BaseAttachment
class ModuleTest(TestCase):
def test_character_attach_attachment(self):
character = BaseCharacter().save()
attachment = BaseAttachment().save()
# Attachment should not be among the character... | from unittest import TestCase
from basics import BaseCharacter
from basics import BaseAttachment
from basics import BaseThing
class ModuleTest(TestCase):
def test_character_attach_attachment(self):
character = BaseCharacter().save()
attachment = BaseAttachment().save()
# Attachment shou... | Write test for container containment. | Write test for container containment.
| Python | apache-2.0 | JASchilz/RoverMUD |
b506b6796a8ed9e778f69ddc7718a8ea3b0f9e7a | flynn/__init__.py | flynn/__init__.py | # coding: utf-8
import flynn.decoder
import flynn.encoder
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
def dumps(obj):
return flynn.encoder.encode_str(obj)
def dumph(obj):
return "".join(hex(n)[2:].rjust(2, "0") for n in dumps(obj))
def load(s):
return flynn.decoder.decode(s)
def loads(s):
return ... | # coding: utf-8
import base64
import flynn.decoder
import flynn.encoder
__all__ = [
"decoder",
"encoder",
"dump",
"dumps",
"dumph",
"load",
"loads",
"loadh"
]
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
def dumps(obj):
return flynn.encoder.encode_str(obj)
def dumph(obj):
return base64.b16en... | Use base64 module to convert between bytes and base16 string | Use base64 module to convert between bytes and base16 string
| Python | mit | fritz0705/flynn |
7b71425a4434ac2544340d651f52c0d87ff37132 | web/impact/impact/v1/helpers/refund_code_helper.py | web/impact/impact/v1/helpers/refund_code_helper.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.models import RefundCode
from impact.v1.helpers.model_helper import(
INTEGER_ARRAY_FIELD,
INTEGER_FIELD,
ModelHelper,
PK_FIELD,
STRING_FIELD,
)
PROGRAMS_FIELD = {
"json-schema": {
"type": "array",
"items": {"ty... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.models import RefundCode
from impact.v1.helpers.model_helper import(
BOOLEAN_FIELD,
INTEGER_ARRAY_FIELD,
INTEGER_FIELD,
ModelHelper,
PK_FIELD,
STRING_FIELD,
)
PROGRAMS_FIELD = {
"json-schema": {
"type": "array",
... | Add Notes and Internal Fields | [AC-5291] Add Notes and Internal Fields
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api |
41fbd5b92ac04c3a4ca0e33204bb08b12a533052 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
07c3c7e00a4c2733a3233ff483797c798451a87f | apps/predict/mixins.py | apps/predict/mixins.py | """
Basic view mixins for predict views
"""
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .models import PredictDataset
class PredictMixin(object):
"""The baseline predict view"""
slug_field = 'md5'
@method_decorator(login_required)
... | """
Basic view mixins for predict views
"""
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .models import PredictDataset
class PredictMixin(object):
"""The baseline predict view"""
slug_field = 'md5'
@method_decorator(login_required)
... | Improve prefetch speed in predict listing pages | Improve prefetch speed in predict listing pages
| Python | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site |
324941bb4946cea19800fb1102035bd32e8028db | apps/profiles/views.py | apps/profiles/views.py | from django.views.generic import DetailView, UpdateView
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import User
class ProfileDetailView(DetailView):
'''
Dis... | from django.views.generic import DetailView, UpdateView
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import User
class ProfileDetailView(DetailView):
'''
Dis... | Use select_related in user profile detail view | Use select_related in user profile detail view
| Python | mit | SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas |
3e842228beba066000eac536635e7e9d4d87c8e2 | instruments/Instrument.py | instruments/Instrument.py | from traits.api import HasTraits
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items():
setattr(self, key, value)
| from traits.api import HasTraits, Bool
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items(... | Add enabled to top-level instrument class. | Add enabled to top-level instrument class.
| Python | apache-2.0 | Plourde-Research-Lab/PyQLab,rmcgurrin/PyQLab,calebjordan/PyQLab,BBN-Q/PyQLab |
cfe594ec7576ba36e93762981067ad02176a585e | instruments/Instrument.py | instruments/Instrument.py | from traits.api import HasTraits
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items():
setattr(self, key, value)
| from traits.api import HasTraits, Bool
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items(... | Add enabled to top-level instrument class. | Add enabled to top-level instrument class.
| Python | apache-2.0 | Plourde-Research-Lab/PyQLab,BBN-Q/PyQLab,calebjordan/PyQLab,rmcgurrin/PyQLab |
8beb6ddd2e58d6a3e54ab297d490c6650fb85a9d | logya/generate.py | logya/generate.py | # -*- coding: utf-8 -*-
import os
import shutil
from logya.core import Logya
from logya.fs import copytree
from logya.writer import DocWriter
class Generate(Logya):
"""Generate a Web site to deploy from current directory as source."""
def __init__(self, **kwargs):
super(self.__class__, self).__init... | # -*- coding: utf-8 -*-
import os
import shutil
from logya.core import Logya
from logya.fs import copytree
from logya.writer import DocWriter
class Generate(Logya):
"""Generate a Web site to deploy from current directory as source."""
def __init__(self, **kwargs):
super(self.__class__, self).__init_... | Add build and write function to make it easy to subclass Generate and overwrite build step | Add build and write function to make it easy to subclass Generate and overwrite build step
| Python | mit | elaOnMars/logya,elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya |
9971e5424b998f45e26b9da8288f20d641885043 | massa/__init__.py | massa/__init__.py | # -*- coding: utf-8 -*-
from flask import Flask, render_template, g
from flask.ext.appconfig import AppConfig
def create_app(configfile=None):
app = Flask('massa')
AppConfig(app, configfile)
@app.route('/')
def index():
return render_template('index.html')
from .container import build
... | # -*- coding: utf-8 -*-
from flask import Flask, render_template, g
from flask.ext.appconfig import AppConfig
from .container import build
from .api import bp as api
def create_app(configfile=None):
app = Flask('massa')
AppConfig(app, configfile)
@app.route('/')
def index():
return render_te... | Move import statements to the top. | Move import statements to the top. | Python | mit | jaapverloop/massa |
12c97be97a8816720899531b932be99743b6d90d | rest_framework_plist/__init__.py | rest_framework_plist/__init__.py | # -*- coding: utf-8 -*-
from distutils import version
__version__ = '0.2.0'
version_info = version.StrictVersion(__version__).version
| # -*- coding: utf-8 -*-
from distutils import version
__version__ = '0.2.0'
version_info = version.StrictVersion(__version__).version
from .parsers import PlistParser # NOQA
from .renderers import PlistRenderer # NOQA
| Make parser and renderer available at package root | Make parser and renderer available at package root
| Python | bsd-2-clause | lpomfrey/django-rest-framework-plist,pombredanne/django-rest-framework-plist |
3f7371c796a420cc077cf79b210d401c77b77815 | rest_framework/response.py | rest_framework/response.py | from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
class Response(SimpleTemplateResponse):
"""
An HttpResponse that allows it's data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None, headers=No... | from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
class Response(SimpleTemplateResponse):
"""
An HttpResponse that allows it's data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None, headers=No... | Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing | Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing
| Python | bsd-2-clause | kylefox/django-rest-framework,cyberj/django-rest-framework,vstoykov/django-rest-framework,wedaly/django-rest-framework,canassa/django-rest-framework,tomchristie/django-rest-framework,linovia/django-rest-framework,cheif/django-rest-framework,nhorelik/django-rest-framework,jpulec/django-rest-framework,James1345/django-re... |
eb763a7c7048b857d408825241ed3de6b68b88f6 | 1/sumofmultiplesof3and5.py | 1/sumofmultiplesof3and5.py | # Project Euler - Problem 1
sum = 0
for i in xrange(1, 1001):
if i % 3 == 0 or i % 5 == 0:
sum = sum + i
print "The sum is: {}".format(sum)
| # Project Euler - Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def main(limit):
sum = 0
for i in xrange(1, limit):
if i % 3 == 0 or i % 5 == 0:
... | Clean up problem 1 solution a bit. | Clean up problem 1 solution a bit.
| Python | mit | gregmojonnier/ProjectEuler |
d05c68b110e4adf5f411816196cf1f457e51951e | nbrmd/__init__.py | nbrmd/__init__.py | """R markdown notebook format for Jupyter
Use this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')
Use the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition
to the ipynb file.
Use the 'nbrmd' ... | """R markdown notebook format for Jupyter
Use this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')
Use the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition
to the ipynb file.
Use the 'nbrmd' ... | Allow import in case of missing notebook package | Allow import in case of missing notebook package | Python | mit | mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext |
e75cba739b92a7209cee87f66d2c8c9df3f97799 | bumper_kilt/scripts/run_kilt.py | bumper_kilt/scripts/run_kilt.py | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=9600,
... | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=38400,
... | Set parameters of serial class to match with kilt | Set parameters of serial class to match with kilt
| Python | mit | ipab-rad/rad_youbot_stack,ipab-rad/rad_youbot_stack,ipab-rad/rad_youbot_stack,ipab-rad/rad_youbot_stack |
be03e3d6c1323e8c750afc1d4e80997f3d9d52f3 | cyder/cydhcp/interface/dynamic_intr/forms.py | cyder/cydhcp/interface/dynamic_intr/forms.py | from django import forms
from cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface,
DynamicIntrKeyValue)
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.forms import RangeWizard
class DynamicInterfaceForm(RangeWizard, UsabilityF... | from django import forms
from cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface,
DynamicIntrKeyValue)
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.forms import RangeWizard
class DynamicInterfaceForm(RangeWizard, UsabilityF... | Reset range to be required in dynamic intr form | Reset range to be required in dynamic intr form
| Python | bsd-3-clause | akeym/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,zeeman/cyder,murrown/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,zeeman/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,zeeman/cyder |
f67abceeae7716cd385a308b26ce447e0277518f | tests/git_wrapper_integration_tests.py | tests/git_wrapper_integration_tests.py | import unittest
import util
from git_wrapper import GitWrapper
class GitWrapperIntegrationTest(util.RepoTestCase):
def test_paths(self):
self.open_tar_repo('project01')
assert('test_file.txt' in self.repo.paths)
assert('hello_world.rb' in self.repo.paths)
def test_stage(self):
... | import unittest
import util
from git_wrapper import GitWrapper
class GitWrapperIntegrationTest(util.RepoTestCase):
def test_paths(self):
self.open_tar_repo('project01')
assert('test_file.txt' in self.repo.paths)
assert('hello_world.rb' in self.repo.paths)
def test_stage(self):
... | Move external git folder integration tests to a separate class | Move external git folder integration tests to a separate class
| Python | mit | siu/git_repo |
feef7985133241c5e11622b0932d3eb629e7fbfe | craigschart/craigschart.py | craigschart/craigschart.py |
def main():
print('Hello, World.')
if __name__ == '__main__':
main()
| from bs4 import BeautifulSoup
import requests
def get_html():
r = requests.get('http://vancouver.craigslist.ca/search/cto?query=Expedition')
print(r.status_code)
print(r.text)
return r.text
def main():
html = get_html()
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())
mydivs ... | Add soup extraction of links in results page | Add soup extraction of links in results page
| Python | mit | supermitch/craigschart |
8c6b4396047736d5caf00ec30b4283ee7cdc793e | lighty/wsgi/decorators.py | lighty/wsgi/decorators.py | '''
'''
import functools
import operator
from .. import monads
def view(func, **constraints):
'''Functions that decorates a view. This function can also checks the
argument values
'''
func.is_view = True
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
if not funct... | '''
'''
import functools
import operator
from .. import monads
def view(func, **constraints):
'''Functions that decorates a view. This function can also checks the
argument values
'''
func.is_view = True
@functools.wraps(func)
@monads.handle_exception
def wrapper(*args, **kwargs):
... | Use exception handling with decorator | Use exception handling with decorator
| Python | bsd-3-clause | GrAndSE/lighty |
7ef1717f34360ae48f640439fd6d6706ae755e90 | functional_tests/base.py | functional_tests/base.py | from selenium import webdriver
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
class BrowserTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.PhantomJS()
self.browser.set_window_size(1024, 768)
def tearDown(s... | from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.chrome.options import Options
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
class BrowserTest(StaticLiveServerTestCase):
def setUp(self):
chrome_options = Options... | Use headless chrome for functional test | Use headless chrome for functional test
| Python | mit | essanpupil/cashflow,essanpupil/cashflow |
9fdea42df37c722aefb5e8fb7c04c45c06c20f17 | tests/test_client_users.py | tests/test_client_users.py | import pydle
from .fixtures import with_client
from .mocks import Mock
@with_client()
def test_user_creation(server, client):
client._create_user('WiZ')
assert 'WiZ' in client.users
assert client.users['WiZ']['nickname'] == 'WiZ'
@with_client()
def test_user_renaming(server, client):
client._create_u... | import pydle
from .fixtures import with_client
@with_client()
def test_client_same_nick(server, client):
assert client.is_same_nick('WiZ', 'WiZ')
assert not client.is_same_nick('WiZ', 'jilles')
assert not client.is_same_nick('WiZ', 'wiz')
@with_client()
def test_user_creation(server, client):
client.... | Extend client:users tests to renaming and synchronization. | tests: Extend client:users tests to renaming and synchronization.
| Python | bsd-3-clause | Shizmob/pydle |
b5fc673d44624dfddfbdd98c9806b7e7e2f67331 | simplekv/memory/memcachestore.py | simplekv/memory/memcachestore.py | #!/usr/bin/env python
# coding=utf8
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from .. import KeyValueStore
class MemcacheStore(KeyValueStore):
def __contains__(self, key):
try:
return key in self.mc
except TypeError:
rai... | #!/usr/bin/env python
# coding=utf8
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from .. import KeyValueStore
class MemcacheStore(KeyValueStore):
def __contains__(self, key):
try:
return key in self.mc
except TypeError:
rai... | Check if putting/getting was actually successful. | Check if putting/getting was actually successful.
| Python | mit | fmarczin/simplekv,fmarczin/simplekv,karteek/simplekv,mbr/simplekv,karteek/simplekv,mbr/simplekv |
f4c99f4a1b3e49e0768af1b4b6444ee33bef49ac | microauth/urls.py | microauth/urls.py | """microauth URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... | """microauth URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... | Add a missing route leading to the login page. | Add a missing route leading to the login page.
| Python | mit | microserv/microauth,microserv/microauth,microserv/microauth |
49f332149ae8a9a3b5faf82bc20b46dfaeb0a3ad | indra/sources/ctd/api.py | indra/sources/ctd/api.py | import pandas
from .processor import CTDChemicalDiseaseProcessor, \
CTDGeneDiseaseProcessor, CTDChemicalGeneProcessor
base_url = 'http://ctdbase.org/reports/'
urls = {
'chemical_gene': base_url + 'CTD_chem_gene_ixns.tsv.gz',
'chemical_disease': base_url + 'CTD_chemicals_diseases.tsv.gz',
'gene_disease... | import pandas
from .processor import CTDChemicalDiseaseProcessor, \
CTDGeneDiseaseProcessor, CTDChemicalGeneProcessor
base_url = 'http://ctdbase.org/reports/'
urls = {
'chemical_gene': base_url + 'CTD_chem_gene_ixns.tsv.gz',
'chemical_disease': base_url + 'CTD_chemicals_diseases.tsv.gz',
'gene_disease... | Refactor API to have single pandas load | Refactor API to have single pandas load
| Python | bsd-2-clause | sorgerlab/indra,bgyori/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,bgyori/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra |
71cdbeada7e11634e1168ca2e825167cbe87b4de | spacy/lang/de/norm_exceptions.py | spacy/lang/de/norm_exceptions.py | # coding: utf8
from __future__ import unicode_literals
# Here we only want to include the absolute most common words. Otherwise,
# this list would get impossibly long for German – especially considering the
# old vs. new spelling rules, and all possible cases.
_exc = {
"daß": "dass"
}
NORM_EXCEPTIONS = {}
for... | # coding: utf8
from __future__ import unicode_literals
# Here we only want to include the absolute most common words. Otherwise,
# this list would get impossibly long for German – especially considering the
# old vs. new spelling rules, and all possible cases.
_exc = {
"daß": "dass"
}
NORM_EXCEPTIONS = {}
for... | Revert "Also include lowercase norm exceptions" | Revert "Also include lowercase norm exceptions"
This reverts commit 70f4e8adf37cfcfab60be2b97d6deae949b30e9e.
| Python | mit | aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spa... |
cd944a2606159c8ea11ffe8075ce4ec186fd799c | tests/basic_test.py | tests/basic_test.py | import unittest
from either_or import either_or
class nxppyTests(unittest.TestCase):
"""Basic tests for the NXP Read Library python wrapper."""
def test_import(self):
"""Test that it can be imported"""
import nxppy
@either_or('detect')
def test_detect_mifare_present(self):
"""... | import unittest
from tests.either_or import either_or
class nxppyTests(unittest.TestCase):
"""Basic tests for the NXP Read Library python wrapper."""
def test_import(self):
"""Test that it can be imported"""
import nxppy
@either_or('detect')
def test_detect_mifare_present(self):
... | Update tests to use class-based interface | Update tests to use class-based interface
| Python | mit | AlterCodex/nxppy,Schoberm/nxppy,AlterCodex/nxppy,tuvaergun/nxppy,Schoberm/nxppy,tuvaergun/nxppy,Schoberm/nxppy,tuvaergun/nxppy,AlterCodex/nxppy |
eb03de241f3d47173381ee22f85b5cdf5d9c1fb4 | examples/monitoring/worker.py | examples/monitoring/worker.py | import random
import time
from os import getenv
from aiographite.aiographite import connect
from aiographite.protocol import PlaintextProtocol
GRAPHITE_HOST = getenv('GRAPHITE_HOST', 'localhost')
async def run(worker, *args, **kwargs):
value = random.randrange(10)
try:
connection = await connect(GRAPHI... | import random
import time
from os import getenv
from aiographite.aiographite import connect
from aiographite.protocol import PlaintextProtocol
GRAPHITE_HOST = getenv('GRAPHITE_HOST', 'localhost')
async def run(worker, *args, **kwargs):
value = random.randrange(10)
try:
connection = await connect(GRA... | Fix flake8 issues in examples | Fix flake8 issues in examples
| Python | apache-2.0 | aioworkers/aioworkers |
8396ac44d434a06c410c516b6109ec6ace030601 | examples/pyuv_cffi_example.py | examples/pyuv_cffi_example.py | """A simple example demonstrating basic usage of pyuv_cffi
This example creates a timer handle and a signal handle, then starts the loop. The timer callback is
run after 1 second, and repeating every 1 second thereafter. The signal handle registers a listener
for the INT signal and allows us to exit the loop by pressi... | """A simple example demonstrating basic usage of pyuv_cffi
This example creates a timer handle and a signal handle, then starts the loop. The timer callback is
run after 1 second, and repeating every 1 second thereafter. The signal handle registers a listener
for the INT signal and allows us to exit the loop by pressi... | Add inline comment regarding freeing resources | Add inline comment regarding freeing resources
| Python | mit | veegee/guv,veegee/guv |
c28ae7e4b0637a2c4db120d9add13d5589ddca40 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
try:
django... | #!/usr/bin/env python
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
... | Remove compat shim as it doesn't apply | Remove compat shim as it doesn't apply
| Python | mit | sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs |
0dddfcbdb46ac91ddc0bfed4482bce049a8593c2 | lazyblacksmith/views/blueprint.py | lazyblacksmith/views/blueprint.py | # -*- encoding: utf-8 -*-
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>')
def manufac... | # -*- encoding: utf-8 -*-
import config
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>... | Change region list to match config | Change region list to match config
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith |
563220ef19395201aed7f6392519f84db4ec7a77 | tests/test_midas.py | tests/test_midas.py | import datetime
from midas import mix
from midas.midas import estimate, forecast
def test_estimate(gdp_data, farmpay_data):
y, yl, x, yf, ylf, xf = mix.mix_freq(gdp_data.gdp, farmpay_data.farmpay, 3, 1, 1,
start_date=datetime.datetime(1985, 1, 1),
... | import datetime
import numpy as np
from midas import mix
from midas.midas import estimate, forecast
def test_estimate(gdp_data, farmpay_data):
y, yl, x, yf, ylf, xf = mix.mix_freq(gdp_data.gdp, farmpay_data.farmpay, 3, 1, 1,
start_date=datetime.datetime(1985, 1, 1),
... | Add assertion for forecast test | Add assertion for forecast test
| Python | mit | mikemull/midaspy |
1f9a11640463df94166be8dffa824e57485154f8 | tests/vaspy_test.py | tests/vaspy_test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFi... | Add test for animation file. | Add test for animation file.
| Python | mit | PytLab/VASPy,PytLab/VASPy |
b8a22c1dfe58802665231e8a82bb546bfd1dbbc8 | pybossa/sentinel/__init__.py | pybossa/sentinel/__init__.py | from redis import sentinel
class Sentinel(object):
def __init__(self, app=None):
self.app = app
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
... | from redis import sentinel
class Sentinel(object):
def __init__(self, app=None):
self.app = app
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
... | Use config redis database in sentinel connections | Use config redis database in sentinel connections
| Python | agpl-3.0 | inteligencia-coletiva-lsd/pybossa,geotagx/pybossa,jean/pybossa,PyBossa/pybossa,PyBossa/pybossa,stefanhahmann/pybossa,OpenNewsLabs/pybossa,OpenNewsLabs/pybossa,stefanhahmann/pybossa,Scifabric/pybossa,geotagx/pybossa,jean/pybossa,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa |
695dad10b6d27e2b45a7b98abad29b9d922b976f | pylisp/packet/ip/protocol.py | pylisp/packet/ip/protocol.py | '''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_he... | '''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties... | Split Protocol class in Protocol and ProtocolElement | Split Protocol class in Protocol and ProtocolElement
| Python | bsd-3-clause | steffann/pylisp |
a1c7773eb889ece3233b910c559b4e22ade3bb32 | timpani/settings.py | timpani/settings.py | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | Use setting validation function in setSettingValue | Use setting validation function in setSettingValue
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani |
ee99527185268ac386aad0c54056ac640c197e42 | dbmigrator/commands/init.py | dbmigrator/commands/init.py | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_d... | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_d... | Stop changing schema_migrations data if the table already exists | Stop changing schema_migrations data if the table already exists
| Python | agpl-3.0 | karenc/db-migrator |
30f03692eff862f1456b9c376c21fe8e57de7eaa | dbt/clients/agate_helper.py | dbt/clients/agate_helper.py |
import agate
DEFAULT_TYPE_TESTER = agate.TypeTester(types=[
agate.data_types.Number(),
agate.data_types.Date(),
agate.data_types.DateTime(),
agate.data_types.Boolean(),
agate.data_types.Text()
])
def table_from_data(data, column_names):
"Convert list of dictionaries into an Agate table"
... |
import agate
DEFAULT_TYPE_TESTER = agate.TypeTester(types=[
agate.data_types.Boolean(true_values=('true',),
false_values=('false',),
null_values=('null',)),
agate.data_types.Number(null_values=('null',)),
agate.data_types.TimeDelta(null_values=('nu... | Make the agate table type tester more restrictive on what counts as null/true/false | Make the agate table type tester more restrictive on what counts as null/true/false
| Python | apache-2.0 | analyst-collective/dbt,nave91/dbt,nave91/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,analyst-collective/dbt |
52fa6cff088e2032fc8a3a9d732bf8affb9bccae | config/template.py | config/template.py | DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
| DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
| Allow for representative view display with sample configuration | Allow for representative view display with sample configuration
| Python | mit | AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at |
068862dc72fa82ec35e7fabc6a0a99dc10f7f034 | octavia/common/service.py | octavia/common/service.py | # Copyright 2014 Rackspace
#
# 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 t... | # Copyright 2014 Rackspace
#
# 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 t... | Remove bad INFO log "Starting Octavia API server" | Remove bad INFO log "Starting Octavia API server"
This log is also display for health_manager and house_keeping service.
Api service already display "Starting API server on..." in INFO level.
Change-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b
| Python | apache-2.0 | openstack/octavia,openstack/octavia,openstack/octavia |
41c6b1820e8b23079d9098526854c9a60859d128 | gcloud_expenses/test_views.py | gcloud_expenses/test_views.py | import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_my_view(self):
from pyramid import testing
from .view... | import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_home_page(self):
from pyramid import testing
from .vi... | Fix test broken in rename. | Fix test broken in rename.
| Python | apache-2.0 | GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo |
769c83564d5f2272837c2fbea6d781110b71b8ca | main.py | main.py | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... | Fix trying to display result in case of not 2D vectors | Fix trying to display result in case of not 2D vectors
| Python | mit | vanashimko/k-means |
03430a5b0abbd051e878274a669edf5afaa656b3 | sc2/helpers/control_group.py | sc2/helpers/control_group.py | class ControlGroup(set):
def __init__(self, units):
super().__init__({unit.tag for unit in units})
def __hash__(self):
return hash(tuple(sorted(list(self))))
def select_units(self, units):
return units.filter(lambda unit: unit.tag in self)
def missing_unit_tags(self, units):
... | class ControlGroup(set):
def __init__(self, units):
super().__init__({unit.tag for unit in units})
def __hash__(self):
return hash(tuple(sorted(list(self))))
def select_units(self, units):
return units.filter(lambda unit: unit.tag in self)
def missing_unit_tags(self, units):
... | Add modification operations to control groups | Add modification operations to control groups
| Python | mit | Dentosal/python-sc2 |
6820de9ccdb7cc7263142108881cf98aab85adb1 | space-age/space_age.py | space-age/space_age.py | # File: space_age.py
# Purpose: Write a program that, given an age in seconds, calculates
# how old someone is in terms of a given planet's solar years.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Saturday 17 September 2016, 06:09 PM
class SpaceAge(object):
"""docstrin... | # File: space_age.py
# Purpose: Write a program that, given an age in seconds, calculates
# how old someone is in terms of a given planet's solar years.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Saturday 17 September 2016, 06:09 PM
class SpaceAge(object):
"""docstrin... | Add other planets age function | Add other planets age function
| Python | mit | amalshehu/exercism-python |
eb2b91d30244fd44b45ffc21b963256150b59152 | frappe/patches/v11_0/reload_and_rename_view_log.py | frappe/patches/v11_0/reload_and_rename_view_log.py | import frappe
def execute():
if frappe.db.exists('DocType', 'View log'):
frappe.reload_doc('core', 'doctype', 'view_log', force=True)
frappe.db.sql("INSERT INTO `tabView Log` SELECT * from `tabView log`")
frappe.delete_doc('DocType', 'View log')
frappe.reload_doc('core', 'doctype', 'view_log', force=True)
el... | import frappe
def execute():
if frappe.db.exists('DocType', 'View log'):
# for mac users direct renaming would not work since mysql for mac saves table name in lower case
# so while renaming `tabView log` to `tabView Log` we get "Table 'tabView Log' already exists" error
# more info https://stackoverflow.com/a/... | Fix rename view log patch for mac users | Fix rename view log patch for mac users
for mac users direct renaming would not work
since mysql for mac saves table name in lower case,
so while renaming `tabView log` to `tabView Log` we get
"Table 'tabView Log' already exists" error
# more info https://stackoverflow.com/a/44753093/5955589
https://dev.mysql.com/doc... | Python | mit | mhbu50/frappe,yashodhank/frappe,vjFaLk/frappe,adityahase/frappe,mhbu50/frappe,almeidapaulopt/frappe,saurabh6790/frappe,adityahase/frappe,vjFaLk/frappe,yashodhank/frappe,saurabh6790/frappe,frappe/frappe,frappe/frappe,vjFaLk/frappe,yashodhank/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,mhbu50/f... |
53c39934e19fdad7926a8ad7833cd1737b47cf58 | utilities/errors.py | utilities/errors.py | import os
import simulators
import numpy as np
import json
"""Calculate Errors on the Spectrum.
For a first go using an fixed SNR of 200 for all observations.
"""
def get_snrinfo(star, obs_num, chip):
"""Load SNR info from json file."""
snr_file = os.path.join(simulators.paths["spectra"], "detector_snrs.... | import os
import simulators
import numpy as np
import json
import warnings
"""Calculate Errors on the Spectrum.
For a first go using an fixed SNR of 200 for all observations.
"""
def get_snrinfo(star, obs_num, chip):
"""Load SNR info from json file."""
snr_file = os.path.join(simulators.paths["spectra"],... | Handle no snr information in snr file. (for fake simualtions mainly) | Handle no snr information in snr file. (for fake simualtions mainly)
| Python | mit | jason-neal/companion_simulations,jason-neal/companion_simulations |
f1cabc889dd93e26295501097ac9cbf90890a1cd | solvent/config.py | solvent/config.py | import yaml
import os
LOCAL_OSMOSIS = 'localhost:1010'
OFFICIAL_OSMOSIS = None
OFFICIAL_BUILD = False
WITH_OFFICIAL_OBJECT_STORE = True
CLEAN = False
def load(filename):
with open(filename) as f:
data = yaml.load(f.read())
if data is None:
raise Exception("Configuration file must not be empty... | import yaml
import os
LOCAL_OSMOSIS_IF_ROOT = 'localhost:1010'
LOCAL_OSMOSIS_IF_NOT_ROOT = 'localhost:1010'
LOCAL_OSMOSIS = None
OFFICIAL_OSMOSIS = None
OFFICIAL_BUILD = False
WITH_OFFICIAL_OBJECT_STORE = True
CLEAN = False
def load(filename):
with open(filename) as f:
data = yaml.load(f.read())
if d... | Select local osmosis depends if user is root, to avoid permission denied on /var/lib/osmosis | Bugfix: Select local osmosis depends if user is root, to avoid permission denied on /var/lib/osmosis
| Python | apache-2.0 | Stratoscale/solvent,Stratoscale/solvent |
967240f95edb300d731f24cfb259a1fe4f3bdae5 | webapp_health_monitor/management/commands/verify.py | webapp_health_monitor/management/commands/verify.py | import importlib
import sys
from django.apps import apps
from django.core.management.base import BaseCommand
from webapp_health_monitor.verification_suit import VerificationSuit
class Command(BaseCommand):
SUBMODULE_NAME = 'verificators'
def handle(self, *args, **options):
submodules = self._get_ve... | import importlib
import sys
from django.apps import apps
from django.core.management.base import BaseCommand
from webapp_health_monitor.verification_suit import VerificationSuit
class Command(BaseCommand):
SUBMODULE_NAME = 'verificators'
def handle(self, *args, **options):
submodules = self._get_ve... | Fix python2 django module importerror. | Fix python2 django module importerror.
| Python | mit | pozytywnie/webapp-health-monitor |
80529d5032b6728adcaad426310c30b5e6366ad4 | solution.py | solution.py | class Kiosk():
def __init__(self, visit_cost, location):
self.visit_cost = visit_cost
self.location = location
print 'initializing Kiosk'
#patient shold be Person
def visit(self, patient):
if not patient.location == self.location:
print 'patient not in correct lo... | class Kiosk():
def __init__(self, location, visit_cost, diabetes_threshold,
cardio_threshold):
self.location = location
self.visit_cost = visit_cost
self.diabetes_threshold = diabetes_threshold
self.cardio_threshold = cardio_threshold
#Initial cost to create kiosk... | Clean up and finish Kiosk class | Clean up and finish Kiosk class
There was some redundancy because I merged it poorly
| Python | bsd-3-clause | rkawauchi/IHK,rkawauchi/IHK |
be8344c2f796ecab60669630f4729c4ffa41c83b | web/impact/impact/v1/views/utils.py | web/impact/impact/v1/views/utils.py | def merge_data_by_id(data):
result = {}
for datum in data:
id = datum["id"]
item = result.get(id, {})
item.update(datum)
result[id] = item
return result.values()
def map_data(klass, query, order, data_keys, output_keys):
result = klass.objects.filter(query).order_by(ord... | def coalesce_dictionaries(data, merge_field="id"):
"Takes a sequence of dictionaries, merges those that share the
same merge_field, and returns a list of resulting dictionaries"
result = {}
for datum in data:
merge_id = datum[merge_field]
item = result.get(merge_id, {})
item.upda... | Rename merge_data_by_id, add doc-string, get rid of id as a local | [AC-4835] Rename merge_data_by_id, add doc-string, get rid of id as a local
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api |
028903036ac4bd3bf4a7b91ceda43a6c450f7e20 | pipeline_notifier/main.py | pipeline_notifier/main.py | import os
import cherrypy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
def run_server():
cherrypy.tree.graft(app, '/')
cherrypy.config.update({
'engine.autoreload_on': True,
'log.screen': True,
'server.socket_port': 8080,
... | import os
import cherrypy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
def run_server():
cherrypy.tree.graft(app, '/')
cherrypy.config.update({
'engine.autoreload_on': True,
'log.screen': True,
'server.socket_port': int(os.envir... | Use port from env if available | Use port from env if available
| Python | mit | pimterry/pipeline-notifier |
269474608221e35907896f5f618e69d6e5136388 | facepy/exceptions.py | facepy/exceptions.py | class FacepyError(Exception):
"""Base class for exceptions raised by Facepy."""
def __init__(self, message):
self.message = message
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
message = property(_get_message, _set_... | class FacepyError(Exception):
"""Base class for exceptions raised by Facepy."""
def __init__(self, message):
self.message = message
| Remove uneccessary getter and setter | Remove uneccessary getter and setter
| Python | mit | merwok-forks/facepy,jwjohns/facepy,jgorset/facepy,Spockuto/facepy,liorshahverdi/facepy,buzzfeed/facepy,jwjohns/facepy |
6d8b99b5e4dab49c5a2e90b07f02072c116a7367 | robots/models.py | robots/models.py | from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class File(models.Model):
site = models.OneToOneField(Site, verbose_name=_(u'site'))
content = models.TextField(_(u'file content'))
objects = models.Manager()
class Meta... | from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class File(models.Model):
site = models.OneToOneField(Site, verbose_name=_(u'site'))
content = models.TextField(_(u'file content'))
class Meta:
verbose_name = _(u'rob... | Remove unnecessary manager declaration from File model | Remove unnecessary manager declaration from File model
| Python | isc | trilan/lemon-robots,trilan/lemon-robots |
aae85883bb99ac15f6922506fa64c4492101b602 | utils/lit/tests/shared-output.py | utils/lit/tests/shared-output.py | # RUN: rm -rf %t && mkdir -p %t
# RUN: echo 'lit_config.load_config(config, "%{inputs}/shared-output/lit.cfg")' > %t/lit.site.cfg
# RUN: %{lit} %t
# RUN: FileCheck %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix=NEGATIVE %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix=OTHER %s < %t/Outp... | # RUN: rm -rf %t && mkdir -p %t
# RUN: echo 'lit_config.load_config(config, os.path.join("%{inputs}", "shared-output", "lit.cfg"))' > %t/lit.site.cfg
# RUN: %{lit} %t
# RUN: FileCheck %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix=NEGATIVE %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix... | Fix new test for systems that don't use / as os.path.sep | lit.py: Fix new test for systems that don't use / as os.path.sep
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@315773 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llv... |
5867a09fb43f8c4480d7aef89a200e952406a648 | dbaas/integrations/credentials/admin/__init__.py | dbaas/integrations/credentials/admin/__init__.py | # -*- coding:utf-8 -*-
from django.contrib import admin
from .. import models
admin.site.register(models.IntegrationType, )
admin.site.register(models.IntegrationCredential, )
| # -*- coding:utf-8 -*-
from django.contrib import admin
from .integration_credential import IntegrationCredentialAdmin
from .integration_type import IntegrationTypeAdmin
from .. import models
admin.site.register(models.IntegrationType, IntegrationTypeAdmin)
admin.site.register(models.IntegrationCredential, Integration... | Enable integration credential and integration type admin | Enable integration credential and integration type admin
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
c08c437b22982667e8ed413739147caec6c5d1ca | api/preprints/urls.py | api/preprints/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContrib... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContrib... | Add URL route for updating provider relationship | Add URL route for updating provider relationship
| Python | apache-2.0 | mluo613/osf.io,rdhyee/osf.io,samchrisinger/osf.io,leb2dg/osf.io,cslzchen/osf.io,chrisseto/osf.io,leb2dg/osf.io,binoculars/osf.io,mluo613/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,emetsger/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,icereval/osf.io,binocu... |
597f586d2cf42f31a0179efc7ac8441f33b3d637 | lib/mysql.py | lib/mysql.py | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._cursor = self._conn.cursor... | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._port = port
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._... | Define the port variable for reconnection | Define the port variable for reconnection | Python | mit | ImShady/Tubey |
999752ec378bbf6d3017f7afc964090c6871b7d4 | app/user_administration/tests.py | app/user_administration/tests.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
class LoginRequiredTest(TestCase):
def test_login_required(self):
response = self.client.get('/')
self.assertEqual(
response.status_code,
302,
msg="Login Required Va... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Clients
class LoginRequiredTest(TestCase):
def test_login_required(self):
response = self.client.get('/')
self.assertEqual(
r... | Add TestCase for ClientListView and ClientCreateView | Add TestCase for ClientListView and ClientCreateView
| Python | mit | rexhepberlajolli/RHChallenge,rexhepberlajolli/RHChallenge |
8b07dde78e753f6dce663481a68856024ed2fc49 | plutokore/__init__.py | plutokore/__init__.py | from .environments.makino import MakinoProfile
from .environments.king import KingProfile
from .jet import AstroJet
from . import luminosity
from . import plotting
from . import simulations
from . import helpers
from . import io
__all__ = [
'environments',
'luminosity',
'plotting',
'simulations',
... | from .environments.makino import MakinoProfile
from .environments.king import KingProfile
from .jet import AstroJet
from . import luminosity
from . import plotting
from . import simulations
from . import helpers
from . import io
from . import configuration
__all__ = [
'environments',
'luminosity',
'plotti... | Add configuration module to package exports | Add configuration module to package exports
| Python | mit | opcon/plutokore,opcon/plutokore |
fcd2328549dcec2986e3b972f1a8bcfb0cf2e21b | rst2pdf/utils.py | rst2pdf/utils.py | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (ca... | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... | Add unit support for spacers | Add unit support for spacers | Python | mit | pombreda/rst2pdf,liuyi1112/rst2pdf,pombreda/rst2pdf,liuyi1112/rst2pdf,rst2pdf/rst2pdf,rst2pdf/rst2pdf |
6b0167514bb41f877945b408638fab72873f2da8 | postgres_copy/__init__.py | postgres_copy/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.db import connection
from .copy_from import CopyMapping
from .copy_to import SQLCopyToCompiler, CopyToQuery
__version__ = '2.0.0'
class CopyQuerySet(models.QuerySet):
"""
Subclass of QuerySet that adds from_csv and to_csv m... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.db import connection
from .copy_from import CopyMapping
from .copy_to import SQLCopyToCompiler, CopyToQuery
__version__ = '2.0.0'
class CopyQuerySet(models.QuerySet):
"""
Subclass of QuerySet that adds from_csv and to_csv m... | Add CopyToQuerySet to available imports | Add CopyToQuerySet to available imports
| Python | mit | california-civic-data-coalition/django-postgres-copy |
639032215f7a51ca146810e8261448f4d0a318aa | downstream_node/models.py | downstream_node/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.startup import db
class Files(db.Model):
__tablename__ = 'files'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
filepath = db.Column('filepath', db.String())
class Challenges(db.Model):
__tablename__ = 'challenge... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.startup import db
class Files(db.Model):
__tablename__ = 'files'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
filepath = db.Column('filepath', db.String())
class Challenges(db.Model):
__tablename__ = 'challenge... | Add root seed to model | Add root seed to model
| Python | mit | Storj/downstream-node,Storj/downstream-node |
c11fd9f792afb71e01224f149121bc13a6a9bed8 | scripts/utils.py | scripts/utils.py | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSO... | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
json_dump_params = {
'ensure_ascii': False,
'in... | Use the OrderedDict class for JSON objects. | scripts: Use the OrderedDict class for JSON objects.
| Python | unlicense | thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap |
0e22a642526612ff9d19d1b421a1aacea4109f15 | pylearn2/datasets/hdf5.py | pylearn2/datasets/hdf5.py | """Objects for datasets serialized in HDF5 format (.h5)."""
import h5py
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
def __init__(self, filename, key):
with h5py.File(filename) as f:
d... | """Objects for datasets serialized in HDF5 format (.h5)."""
import h5py
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs):
"""
... | Support for targets in HDF5 datasets | Support for targets in HDF5 datasets
| Python | bsd-3-clause | alexjc/pylearn2,pombredanne/pylearn2,kose-y/pylearn2,TNick/pylearn2,lancezlin/pylearn2,theoryno3/pylearn2,aalmah/pylearn2,se4u/pylearn2,woozzu/pylearn2,daemonmaker/pylearn2,daemonmaker/pylearn2,goodfeli/pylearn2,JesseLivezey/pylearn2,nouiz/pylearn2,ddboline/pylearn2,CIFASIS/pylearn2,w1kke/pylearn2,lamblin/pylearn2,kast... |
b824cadfe61de19b5ff0f7391fe2b21b034c71b4 | readdata.py | readdata.py | import os,sys
import json
import csv
import soundfile as sf
from scipy.fftpack import dct
from features import mfcc,fbank,sigproc,logfbank
def parseJSON(directory, filename):
data=[]
jsonMeta=[]
#open all files that end with .json in <path> directory
#and store certain attributes
try:
json_... | import os,sys
import json
import csv
from yaafelib import *
def parseJSON(directory, filename):
data=[]
jsonMeta=[]
#open all files that end with .json in <path> directory
#and store certain attributes
try:
json_data=open(os.path.join(directory, filename))
except(IOError, RuntimeError )... | Use yaafe for feature extraction | Use yaafe for feature extraction
Right now we extract two features (mfcc and perceptual spread)
but there is a lot of work to be done on the feature extraction method
so this is probably going to change
| Python | mit | lOStres/JaFEM |
b0d9a11292b6d6b17fe8b72d7735d26c47599187 | linkatos/printer.py | linkatos/printer.py | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | Change iteration over a collection based on ags suggestion | refactor: Change iteration over a collection based on ags suggestion
| Python | mit | iwi/linkatos,iwi/linkatos |
bace1847cb9479bfeb271f38eef502f8d3ac240a | qipr/registry/forms/facet_form.py | qipr/registry/forms/facet_form.py | from registry.models import *
from operator import attrgetter
facet_Models = [
BigAim,
Category,
ClinicalArea,
ClinicalSetting,
Keyword,
SafetyTarget,
]
class FacetForm:
def __init__(self):
self.facet_categories = [model.__name__ for model in facet_Models]
for model in face... | from registry.models import *
from operator import attrgetter
facet_Models = [
BigAim,
ClinicalArea,
ClinicalSetting,
Keyword,
]
class FacetForm:
def __init__(self):
self.facet_categories = [model.__name__ for model in facet_Models]
for model in facet_Models:
models = l... | Remove facets from main registry project page | Remove facets from main registry project page
| Python | apache-2.0 | ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr |
4792515739c4ee671b86aeed39022ad8934d5d7c | artie/applications.py | artie/applications.py | import os
import re
import sys
import settings
triggers = set()
timers = set()
class BadApplicationError(Exception): pass
def trigger(expression):
def decorator(func):
triggers.add((re.compile(expression), func))
return decorator
def timer(time):
def decorator(func):
timers.add((time, f... | import os
import re
import sys
import settings
triggers = set()
timers = set()
class BadApplicationError(Exception): pass
def trigger(expression):
def decorator(func):
triggers.add((re.compile(expression), func))
return decorator
def timer(time):
def decorator(func):
timers.add((time, f... | Use `endswith` instead of string indeces. | Use `endswith` instead of string indeces.
| Python | mit | sumeet/artie |
46e1672bb0226ae8157d63a2d73edbfefcd644e9 | src/test/test_google_maps.py | src/test/test_google_maps.py | import unittest
import googlemaps
from pyrules2.googlemaps import driving_roundtrip
COP = 'Copenhagen, Denmark'
MAD = 'Madrid, Spain'
BER = 'Berlin, Germany'
LIS = 'Lisbon, Portugal'
KM = 1000
class Test(unittest.TestCase):
def setUp(self):
# TODO: Sane way to import key
with open('/Users/nhc/gi... | from os import environ
import unittest
import googlemaps
from pyrules2.googlemaps import driving_roundtrip
COP = 'Copenhagen, Denmark'
MAD = 'Madrid, Spain'
BER = 'Berlin, Germany'
LIS = 'Lisbon, Portugal'
KM = 1000
class Test(unittest.TestCase):
def setUp(self):
try:
key = environ['GOOGLE_M... | Move API key to environment variable | Move API key to environment variable
| Python | mit | mr-niels-christensen/pyrules |
51d1701bbc8b25bfd7b4f70c83fec7a46d965bef | fireplace/cards/brawl/decks_assemble.py | fireplace/cards/brawl/decks_assemble.py | """
Decks Assemble
"""
from ..utils import *
# Tarnished Coin
class TB_011:
play = ManaThisTurn(CONTROLLER, 1)
| """
Decks Assemble
"""
from ..utils import *
# Deckbuilding Enchant
class TB_010:
events = (
OWN_TURN_BEGIN.on(Discover(CONTROLLER, RandomCollectible())),
Play(CONTROLLER).on(Shuffle(CONTROLLER, Copy(Play.CARD))),
OWN_TURN_END.on(Shuffle(CONTROLLER, FRIENDLY_HAND))
)
# Tarnished Coin
class TB_011:
play = M... | Implement Decks Assemble brawl rules on the Deckbuilding Enchant | Implement Decks Assemble brawl rules on the Deckbuilding Enchant
| Python | agpl-3.0 | Ragowit/fireplace,NightKev/fireplace,beheh/fireplace,smallnamespace/fireplace,Ragowit/fireplace,jleclanche/fireplace,smallnamespace/fireplace |
3f4415bd551b52418a5999a1ea64e31d15097802 | framework/transactions/commands.py | framework/transactions/commands.py | # -*- coding: utf-8 -*-
from framework.mongo import database as proxy_database
def begin(database=None):
database = database or proxy_database
database.command('beginTransaction')
def rollback(database=None):
database = database or proxy_database
database.command('rollbackTransaction')
def commit... | # -*- coding: utf-8 -*-
from framework.mongo import database as proxy_database
from pymongo.errors import OperationFailure
def begin(database=None):
database = database or proxy_database
database.command('beginTransaction')
def rollback(database=None):
database = database or proxy_database
try:
... | Fix rollback transaction issue bby adding except for Operation Failure to rollback | Fix rollback transaction issue bby adding except for Operation Failure to rollback
| Python | apache-2.0 | erinspace/osf.io,doublebits/osf.io,brandonPurvis/osf.io,brandonPurvis/osf.io,kwierman/osf.io,GageGaskins/osf.io,hmoco/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,felliott/osf.io,cosenal/osf.io,abought/osf.io,kch8qx/osf.io,haoyuchen1992/osf.io,himanshuo/osf.io,sbt9uc/osf.io,bdyetton/prettychart,samchrisinger/osf.io,mon... |
43dca4ad969e44bb753c152e8f7768febea6fb68 | quantecon/__init__.py | quantecon/__init__.py | """
Import the main names to top level.
"""
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
from .estspec import smooth, periodogram, ar_periodogram
from .graph_tools import DiGraph
from .gridtools import cartesian, mlinspace
from .kalman import Kalman
from .lae i... | """
Import the main names to top level.
"""
try:
import numba
except:
raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.")
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
fr... | Add Check for numba in base anaconda distribution. If not found issue meaningful warning message | Add Check for numba in base anaconda distribution. If not found issue meaningful warning message
| Python | bsd-3-clause | oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py |
9d3d2beab6ec06ce13126b818029258a66f450f6 | babelfish/__init__.py | babelfish/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
__title__ = 'babelfish'
__version__ = '0.4.1'
__author__ = 'Antoine Bertin'
__license__ = 'BSD'
__copyright__ = 'Copyrig... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
__title__ = 'babelfish'
__version__ = '0.4.1'
__author__ = 'Antoine Bertin'
__license__ = 'BSD'
__copyright__ = 'Copyrig... | Add SCRIPT_MATRIX to babelfish module imports | Add SCRIPT_MATRIX to babelfish module imports
| Python | bsd-3-clause | Diaoul/babelfish |
2ad21d67ccde2e25ea5c6d64cdee36dbc6425cbc | construct/tests/test_mapping.py | construct/tests/test_mapping.py | import unittest
from construct import Flag
class TestFlag(unittest.TestCase):
def test_parse(self):
flag = Flag("flag")
self.assertTrue(flag.parse("\x01"))
def test_parse_flipped(self):
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
def te... | import unittest
from construct import Flag
class TestFlag(unittest.TestCase):
def test_parse(self):
flag = Flag("flag")
self.assertTrue(flag.parse("\x01"))
def test_parse_flipped(self):
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
def te... | Add a couple more Flag tests. | tests: Add a couple more Flag tests.
| Python | mit | riggs/construct,mosquito/construct,gkonstantyno/construct,MostAwesomeDude/construct,0000-bigtree/construct,riggs/construct,mosquito/construct,0000-bigtree/construct,gkonstantyno/construct,MostAwesomeDude/construct |
b2dd21b2240eec28881d6162f9e35b16df906219 | arris_cli.py | arris_cli.py | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... | Tweak formatting of argparse section to minimize lines extending past 80 chars. | Tweak formatting of argparse section to minimize lines extending past 80 chars.
| Python | mit | wolrah/arris_stats |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.