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 |
|---|---|---|---|---|---|---|---|---|---|
d6461896dec112caad81490e1a6d055a3d4c9a95 | db.py | db.py | """Handles database connection, and all that fun stuff.
@package ppbot
"""
from pymongo import MongoClient
from settings import *
client = MongoClient(MONGO_HOST, MONGO_PORT)
db = client[MONGO_DB]
| """Handles database connection, and all that fun stuff.
Adds a wrapper to pymongo.
@package ppbot
"""
from pymongo import mongo_client
from pymongo import database
from pymongo import collection
from settings import *
class ModuleMongoClient(mongo_client.MongoClient):
def __getattr__(self, name):
attr =... | Add custom wrapper code to pymongo for Modules | Add custom wrapper code to pymongo for Modules
| Python | mit | billyvg/piebot |
e87ac65b42b6390cee835deb180fc6cd2a814082 | invocations/checks.py | invocations/checks.py | """
Tasks for common project sanity-checking such as linting or type checking.
"""
from __future__ import unicode_literals
from invoke import task
@task(name="blacken", iterable=["folder"])
def blacken(c, line_length=79, folder=None, check=False):
"""
Run black on the current source tree (all ``.py`` files)... | """
Tasks for common project sanity-checking such as linting or type checking.
"""
from __future__ import unicode_literals
from invoke import task
@task(name="blacken", iterable=["folder"])
def blacken(c, line_length=79, folder=None, check=False, diff=False):
"""
Run black on the current source tree (all ``... | Add diff option to blacken and document params | Add diff option to blacken and document params
| Python | bsd-2-clause | pyinvoke/invocations |
2e6445bfda12e470fdc5c0b6aa725fd344c863f1 | drake/bindings/python/pydrake/test/testRBTCoM.py | drake/bindings/python/pydrake/test/testRBTCoM.py | from __future__ import print_function
import unittest
import numpy as np
import pydrake
import os.path
class TestRBTCoM(unittest.TestCase):
def testCoM0(self):
r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(),
"examples/Pendulum/Pendulum.urdf"))... | from __future__ import print_function
import unittest
import numpy as np
import pydrake
import os.path
class TestRBTCoM(unittest.TestCase):
def testCoM0(self):
r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(),
"examples/Pendulum/Pendulum.urdf"))... | Test CoM Jacobian with random configuration for shape, and then with 0 configuration for values | Test CoM Jacobian with random configuration for shape, and then with 0 configuration for values
| Python | bsd-3-clause | billhoffman/drake,billhoffman/drake,sheim/drake,sheim/drake,sheim/drake,sheim/drake,billhoffman/drake,billhoffman/drake,billhoffman/drake,sheim/drake,sheim/drake,sheim/drake,billhoffman/drake,billhoffman/drake,sheim/drake,billhoffman/drake |
e30629cba2bf09cf83e8e424a203793a5baf9b43 | remote.py | remote.py | import sublime, sublime_plugin | import sublime, sublime_plugin
class DiffListener(sublime_plugin.EventListener):
"""Listens for modifications to the view and gets the diffs using Operational Transformation"""
def __init___(self):
self.buffer = None
self.last_buffer = None
def on_modified_async(self, view):
"""Li... | Add a bunch of mostly-empty method stubs. | Add a bunch of mostly-empty method stubs.
| Python | mit | TeamRemote/remote-sublime,TeamRemote/remote-sublime |
6bbbc74ea4acda000c115d08801d2f6c677401da | lmod/__init__.py | lmod/__init__.py | import os
from subprocess import Popen, PIPE
LMOD_CMD = os.environ['LMOD_CMD']
LMOD_SYSTEM_NAME = os.environ.get('LMOD_SYSTEM_NAME', '')
def module(command, arguments=()):
cmd = [LMOD_CMD, 'python', '--terse', command]
cmd.extend(arguments)
result = Popen(cmd, stdout=PIPE, stderr=PIPE)
if command in ... | from os import environ
from subprocess import Popen, PIPE
LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '')
def module(command, arguments=()):
cmd = [environ['LMOD_CMD'], 'python', '--terse', command]
cmd.extend(arguments)
result = Popen(cmd, stdout=PIPE, stderr=PIPE)
if command in ('load', 'unl... | Remove LMOD_CMD global from module scope | Remove LMOD_CMD global from module scope
Declaring the variable at the module level
could cause problem when installing and
enabling the extension when Lmod was not
activated.
| Python | mit | cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod |
bb42fe14165806caf8a2386c49cb602dbf9ad391 | connectionless_service.py | connectionless_service.py | """
A Simple example for testing the SimpleServer Class. A simple connectionless
server. It is for studying purposes only.
"""
from simple.server import SimpleServer
__author__ = "Facundo Victor"
__license__ = "MIT"
__email__ = "facundovt@gmail.com"
def handle_message(sockets=None):
"""
Handle a simple UDP... | """
A Simple example for testing the SimpleServer Class. A simple connectionless
server. It is for studying purposes only.
"""
from simple.server import SimpleServer
__author__ = "Facundo Victor"
__license__ = "MIT"
__email__ = "facundovt@gmail.com"
def handle_message(sockets=None):
"""
Handle a simple UDP... | Fix python 2.4 connectionless service | Fix python 2.4 connectionless service
| Python | mit | facundovictor/non-blocking-socket-samples |
8fba76340daef349c45946183757ef463004492b | tests/unit/test_spec_set.py | tests/unit/test_spec_set.py | import unittest
class TestSpecSet(unittest.TestCase):
pass
| import unittest
from piptools.datastructures import SpecSet, Spec
class TestSpecSet(unittest.TestCase):
def test_adding_specs(self):
"""Adding specs to a set."""
specset = SpecSet()
specset.add_spec(Spec.from_line('Django>=1.3'))
assert 'Django>=1.3' in map(str, specset)
... | Add test cases for testing SpecSet. | Add test cases for testing SpecSet.
| Python | bsd-2-clause | suutari-ai/prequ,suutari/prequ,suutari/prequ |
fd99ef86dfca50dbd36b2c1a022cf30a0720dbea | scrapy/squeues.py | scrapy/squeues.py | """
Scheduler queues
"""
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).p... | """
Scheduler queues
"""
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).p... | Test for AttributeError when pickling objects (Python>=3.5) | Test for AttributeError when pickling objects (Python>=3.5)
Same "fix" as in e.g. https://github.com/joblib/joblib/pull/246
| Python | bsd-3-clause | YeelerG/scrapy,wenyu1001/scrapy,GregoryVigoTorres/scrapy,crasker/scrapy,jdemaeyer/scrapy,Parlin-Galanodel/scrapy,arush0311/scrapy,Digenis/scrapy,pablohoffman/scrapy,ArturGaspar/scrapy,kmike/scrapy,crasker/scrapy,eLRuLL/scrapy,wujuguang/scrapy,carlosp420/scrapy,darkrho/scrapy-scrapy,redapple/scrapy,carlosp420/scrapy,bar... |
b639c9f1c615ca73fd49c171344effb3718b2b77 | script.py | script.py | import ast
import click
from graphing.graph import FunctionGrapher
from parsing.parser import FileVisitor
@click.command()
@click.argument('code', type=click.File('rb'))
@click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file')
@click.option('--remove-bui... | import ast
import click
from graphing.graph import FunctionGrapher
from parsing.parser import FileVisitor
@click.command()
@click.argument('code', type=click.File('rb'))
@click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file')
@click.option('--remove-bui... | Add output file type option | Add output file type option
| Python | mit | LaurEars/codegrapher |
14756f5de831832a192a8a453e7e108be7ebcacd | components/includes/utilities.py | components/includes/utilities.py | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if ... | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if ... | Clean up, comments, liveness checking, robust data transfer | Clean up, comments, liveness checking, robust data transfer
| Python | bsd-2-clause | mavroudisv/Crux |
f118d1c3cb4752a20329a32d0d49fd9e46280bc3 | user/admin.py | user/admin.py | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'email',
'is_staff',
'is_superuser')
list_filter = (
'is_staff',
'is_superuser',
'profile__joined')
ordering ... | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'email',
'get_date_joined',
'is_staff',
'is_superuser')
list_filter = (
'is_staff',
'is_superuser',
'prof... | Add join date to UserAdmin list. | Ch23: Add join date to UserAdmin list.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
0bb7a3d468a70e57bb867678a7649e7ad736d39f | cms/utils/setup.py | cms/utils/setup.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from cms.utils.compat.dj import is_installed as app_is_installed
def validate_dependencies():
"""
Check for installed apps, their versions and configuration options
"""
if not app_is_installed('mptt'):
ra... | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from cms.utils.compat.dj import is_installed as app_is_installed
def validate_dependencies():
"""
Check for installed apps, their versions and configuration options
"""
if not app_is_installed('mptt'):
ra... | Patch get_models to ensure plugins are properly patched | Patch get_models to ensure plugins are properly patched
| Python | bsd-3-clause | robmagee/django-cms,chmberl/django-cms,astagi/django-cms,sephii/django-cms,philippze/django-cms,dhorelik/django-cms,cyberintruder/django-cms,evildmp/django-cms,cyberintruder/django-cms,takeshineshiro/django-cms,netzkolchose/django-cms,saintbird/django-cms,memnonila/django-cms,wuzhihui1123/django-cms,AlexProfi/django-cm... |
7456080d3f8d598728fe7a9ee96884db9e28a869 | tests/services/shop/conftest.py | tests/services/shop/conftest.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
from byceps.services.email import service as email_service
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
from byceps.services.email import service as email_service
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop... | Introduce factory for email config fixture | Introduce factory for email config fixture
This allows to create local fixtures that use email config with a
broader scope than 'function'.
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
be779b6b7f47750b70afa6f0aeb67b99873e1c98 | indico/modules/events/tracks/forms.py | indico/modules/events/tracks/forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Remove useless field descs, increase rows | Tracks: Remove useless field descs, increase rows
| Python | mit | DirkHoffmann/indico,pferreir/indico,OmeGak/indico,indico/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,OmeGak/indico,DirkHoffmann/indico,mic4ael/indico,mvidalgarcia/indico,OmeGak/indico,indico/indico,OmeGak/indico,indico/indico,ThiefMaster/indico,pferreir/indico,ThiefMaster/indico,ThiefMaster/indico,pfer... |
e47ede85f2001cc5c514951355ded1253b4c45f7 | notaro/apps.py | notaro/apps.py | from django.apps import AppConfig
from watson import search as watson
class NotaroConfig(AppConfig):
name = "notaro"
verbose_name = "Notizen"
def ready(self):
NoteModel = self.get_model("Note")
watson.register(NoteModel.objects.filter(published=True))
SourceModel = self.get_model... | from django.apps import AppConfig
from watson import search as watson
class NotaroConfig(AppConfig):
name = "notaro"
verbose_name = "Notizen"
def ready(self):
NoteModel = self.get_model("Note")
watson.register(NoteModel.objects.filter(published=True))
SourceModel = self.get_model... | Fix watson settings; add search for picture | Fix watson settings; add search for picture
| Python | bsd-3-clause | ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio |
c7efd5976f511200162610612fcd5b6f9b013a54 | dciclient/v1/utils.py | dciclient/v1/utils.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 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 applicable la... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 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 applicable la... | Fix TypeError exception when parsing json | Fix TypeError exception when parsing json
This change fixes the TypeError exception that is raised when it should
not while parsing json
File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode
obj, en... | Python | apache-2.0 | redhat-cip/python-dciclient,redhat-cip/python-dciclient |
d17f72112625d66169098d8cb8fb856e7fd93272 | knights/k_tags.py | knights/k_tags.py |
import ast
from .klass import build_method
from .library import Library
register = Library()
def parse_args(bits):
'''
Parse tag bits as if they're function args
'''
code = ast.parse('x(%s)' % bits, mode='eval')
return code.body.args, code.body.keywords
@register.tag(name='block')
def block(s... |
import ast
from .library import Library
register = Library()
@register.tag(name='block')
def block(parser, token):
token = token.strip()
parser.build_method(token, endnodes=['endblock'])
return ast.YieldFrom(
value=ast.Call(
func=ast.Attribute(
value=ast.Name(id='sel... | Update for parser class Add if/else tags | Update for parser class
Add if/else tags
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
ed24b2771d80b7043c052e076ae7384f976d92b7 | 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 |
09a96a308c7666defdc1377e207f9632b9bc9c7a | app.py | app.py | #!flask/bin/python
"""
Author: Swagger.pro
File: app.py
Purpose: runs the app!
"""
from swagip import app
app.config.from_object('config')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0')
| #!flask/bin/python
"""
Author: Swagger.pro
File: app.py
Purpose: runs the app!
"""
from swagip import app
app.config.from_object('config')
if __name__ == "__main__":
app.run()
| Remove debug and all host listener | Remove debug and all host listener
| Python | mit | thatarchguy/SwagIP,thatarchguy/SwagIP,thatarchguy/SwagIP |
23747dd111d72995942e9d218fc99ce4ec810266 | fingerprint/fingerprint_agent.py | fingerprint/fingerprint_agent.py | class FingerprintAgent(object):
def __init__(self, request):
self.request = request
def detect_server_whorls(self):
vars = {}
# get cookie enabled
if self.request.cookies:
vars['cookie_enabled'] = 'Yes'
else:
vars['cookie_enabled'] = 'No'
... | class FingerprintAgent(object):
def __init__(self, request):
self.request = request
def detect_server_whorls(self):
vars = {}
# get cookie enabled
if self.request.cookies:
vars['cookie_enabled'] = 'Yes'
else:
vars['cookie_enabled'] = 'No'
... | Use unicode strings for 'no javascript' just so it's consistent with browser-retrieved values | Use unicode strings for 'no javascript' just so it's consistent with browser-retrieved values
| Python | agpl-3.0 | EFForg/panopticlick-python,EFForg/panopticlick-python,EFForg/panopticlick-python,EFForg/panopticlick-python |
ea8a78cb7d7cda7b597826a478cce3ab4b0a4b62 | django_nose_plugin.py | django_nose_plugin.py | from nose.plugins import Plugin
class DjangoNosePlugin(Plugin):
''' Adaptor that allows usage of django_nose package plugin from
the nosetests command line.
Imports and instantiates django_nose plugin after initialization
so that the django environment does not have to be configured
when running n... | from nose.plugins import Plugin
class DjangoNosePlugin(Plugin):
''' Adaptor that allows usage of django_nose package plugin from
the nosetests command line.
Imports and instantiates django_nose plugin after initialization
so that the django environment does not have to be configured
when running n... | Fix issue when running nosetests and django_nose is not required | Fix issue when running nosetests and django_nose is not required
| Python | mit | jenniferlianne/django_nose_adapter |
7a66b9fb3482778cd0efab692cbc535260bcad25 | publishconf.py | publishconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://dicasdejava.com.br'
RELATIVE_URLS = Fa... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://dicasdejava.com.br'
RELATIVE_URLS = Fa... | Remove minify plugin to test search. | Remove minify plugin to test search.
| Python | mit | gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br |
c6ffb39cc730809781e8dabff4458fd167e60123 | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<H1>Measure Anything</H1>'
if __name__ == '__main__':
app.run(debug=True) | from flask import Flask
from flask.ext.script import Manager
app = Flask(__name__)
manager = Manager(app)
@app.route('/')
def index():
return '<H1>Measure Anything</H1>'
if __name__ == '__main__':
manager.run() | Use flask-script so command line parameters can be used. | Use flask-script so command line parameters can be used.
| Python | mit | rahimnathwani/measure-anything |
8bc9d9dd548cb2e19a51fb33336695ca3925ba64 | tests/python/unittest/test_random.py | tests/python/unittest/test_random.py | import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
for i in range(5):
shape = (100 + i, 100 + i)
mx.random.seed(128)
ret1... | import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
shape = (100, 100)
mx.random.seed(128)
ret1 = mx.random.normal(mu, sigma, shape)
u... | Revert "Update random number generator test" | Revert "Update random number generator test"
This reverts commit b63bda37aa2e9b5251cf6c54d59785d2856659ca.
| Python | apache-2.0 | sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet |
0e66044b3949255be2653c0cffee53b003ea3929 | solum/api/controllers/v1/pub/trigger.py | solum/api/controllers/v1/pub/trigger.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 t... | # 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 t... | Fix pecan error message not available in body for Trigger.post | Fix pecan error message not available in body for Trigger.post
When a trigger_id resource is not found, the API returns a 202 status
code, the error message could not be added in the body of the request
because pecan.response.text was used instead of pecan.response.body.
Change-Id: I8b03210b5a2f2b5c0ea24bfc8149cca122... | Python | apache-2.0 | ed-/solum,stackforge/solum,ed-/solum,devdattakulkarni/test-solum,gilbertpilz/solum,ed-/solum,openstack/solum,gilbertpilz/solum,ed-/solum,devdattakulkarni/test-solum,openstack/solum,gilbertpilz/solum,stackforge/solum,gilbertpilz/solum |
2add55f78d6b5efb097f8a4d089b2eced80d0882 | chrome/common/extensions/docs/server2/fake_host_file_system_provider.py | chrome/common/extensions/docs/server2/fake_host_file_system_provider.py | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from mock_file_system import MockFileSystem
from test_file_system import TestFileSystem
from third_party.json_schema_compiler.memoize i... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from mock_file_system import MockFileSystem
from test_file_system import TestFileSystem
from third_party.json_schema_compiler.memoize import memoize
class F... | Remove shebang line from non-executable .py file. | Remove shebang line from non-executable .py file.
Fixes checkperms failure on the main waterfall:
http://build.chromium.org/p/chromium.chromiumos/builders/Linux%20ChromiumOS%20Full/builds/30316/steps/check_perms/logs/stdio
/b/build/slave/Linux_ChromiumOS/build/src/chrome/common/extensions/docs/server2/fake_host_file_... | Python | bsd-3-clause | dednal/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,TheTyp... |
96c14567ee54033a11bf1f8bc3b3eb0058c092f7 | manoseimas/compatibility_test/admin.py | manoseimas/compatibility_test/admin.py | from django.contrib import admin
from manoseimas.compatibility_test.models import CompatTest
from manoseimas.compatibility_test.models import Topic
from manoseimas.compatibility_test.models import TopicVoting
from manoseimas.compatibility_test.models import Argument
from manoseimas.compatibility_test.models import Tes... | from django.contrib import admin
from manoseimas.compatibility_test import models
class VotingInline(admin.TabularInline):
model = models.TopicVoting
raw_id_fields = [
'voting',
]
class ArgumentInline(admin.TabularInline):
model = models.Argument
class TopicAdmin(admin.ModelAdmin):
li... | Fix really strange bug about conflicting models | Fix really strange bug about conflicting models
The bug:
Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ... ERROR
======================================================================
ERROR: Failure... | Python | agpl-3.0 | ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt |
48b6bb91537d9daecca2bc112f5e06dc9b530f09 | scripts/c2s-info.py | scripts/c2s-info.py | #!/usr/bin/env python
"""
Summarize dataset.
Examples:
c2s info data.pck
"""
import sys
from argparse import ArgumentParser
from pickle import dump
from scipy.io import savemat
from numpy import corrcoef, mean
from c2s import load_data
def main(argv):
parser = ArgumentParser(argv[0], description=__doc__)
parse... | #!/usr/bin/env python
"""
Summarize dataset.
Examples:
c2s info data.pck
"""
import sys
from argparse import ArgumentParser
from pickle import dump
from scipy.io import savemat
from numpy import corrcoef, mean, unique
from c2s import load_data
def main(argv):
parser = ArgumentParser(argv[0], description=__doc__... | Print a little bit more info. | Print a little bit more info.
| Python | mit | lucastheis/c2s,jonasrauber/c2s |
d08d78460d0f7143b90a5157c4f5450bb062ec75 | im2sim.py | im2sim.py | import argparse
import PIL
from PIL import Image
import subprocess
import os
import glob
def get_image(filename):
p = Image.open(filename)
docker_image = p.info['im2sim_image']
return subprocess.call('docker pull {}'.format(docker_image), shell=True)
print('Pulled docker image {}'.format(docker_image)... | import argparse
import PIL
from PIL import Image
import subprocess
import os
import glob
def get_image(filename):
p = Image.open(filename)
docker_image = p.info['im2sim_image']
return subprocess.call('docker pull {}'.format(docker_image), shell=True)
print('Pulled docker image {}'.format(docker_image)... | Make script consistent with instructions. | Make script consistent with instructions.
| Python | mit | IanHawke/im2sim |
ea860743e0ba4538714d9fe5476b4807cf75ed35 | sourcer/__init__.py | sourcer/__init__.py | from .terms import *
from .parser import *
__all__ = [
'Alt',
'And',
'Any',
'AnyChar',
'AnyInst',
'Bind',
'Content',
'End',
'Expect',
'ForwardRef',
'InfixLeft',
'InfixRight',
'Left',
'LeftAssoc',
'List',
'Literal',
'Middle',
'Not',
'Operation... | from .terms import (
Alt,
And,
Any,
AnyChar,
AnyInst,
Bind,
Content,
End,
Expect,
ForwardRef,
InfixLeft,
InfixRight,
Left,
LeftAssoc,
List,
Literal,
Middle,
Not,
Operation,
OperatorPrecedence,
Opt,
Or,
ParseError,
ParseResul... | Replace the __all__ specification with direct imports. | Replace the __all__ specification with direct imports.
| Python | mit | jvs/sourcer |
0ebf51994a73fdc7c4f13b274fc41bef541eea52 | deflect/widgets.py | deflect/widgets.py | from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard `... | from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard `... | Hide the option set from incompatible browsers | Hide the option set from incompatible browsers
| Python | bsd-3-clause | jbittel/django-deflect |
97c0f23c676de7e726e938bf0b61087834cf9fd9 | netbox/tenancy/api/serializers.py | netbox/tenancy/api/serializers.py | from rest_framework import serializers
from extras.api.serializers import CustomFieldSerializer
from tenancy.models import Tenant, TenantGroup
#
# Tenant groups
#
class TenantGroupSerializer(serializers.ModelSerializer):
class Meta:
model = TenantGroup
fields = ['id', 'name', 'slug']
class Te... | from rest_framework import serializers
from extras.api.serializers import CustomFieldSerializer
from tenancy.models import Tenant, TenantGroup
#
# Tenant groups
#
class TenantGroupSerializer(serializers.ModelSerializer):
class Meta:
model = TenantGroup
fields = ['id', 'name', 'slug']
class Te... | Add description field to TenantSerializer | Add description field to TenantSerializer
This might be just an oversight. Other data models do include the description in their serialisers. The API produces the description field with this change. | Python | apache-2.0 | digitalocean/netbox,snazy2000/netbox,digitalocean/netbox,snazy2000/netbox,Alphalink/netbox,snazy2000/netbox,lampwins/netbox,Alphalink/netbox,snazy2000/netbox,Alphalink/netbox,lampwins/netbox,lampwins/netbox,digitalocean/netbox,digitalocean/netbox,lampwins/netbox,Alphalink/netbox |
7b1766a6f07d468f1830871bfe2cdc1aaa29dcbf | examples/client.py | examples/client.py | """
Cross-process log tracing: HTTP client.
"""
from __future__ import unicode_literals
import sys
import requests
from eliot import Logger, to_file, start_action
to_file(sys.stdout)
logger = Logger()
def request(x, y):
with start_action(logger, "http_request", x=x, y=y) as action:
task_id = action.seri... | """
Cross-process log tracing: HTTP client.
"""
from __future__ import unicode_literals
import sys
import requests
from eliot import Logger, to_file, start_action
to_file(sys.stdout)
logger = Logger()
def remote_divide(x, y):
with start_action(logger, "http_request", x=x, y=y) as action:
task_id = actio... | Address review comment: Better function name. | Address review comment: Better function name.
| Python | apache-2.0 | ScatterHQ/eliot,ScatterHQ/eliot,ClusterHQ/eliot,iffy/eliot,ScatterHQ/eliot |
6e6383037fc86beba36f16e9beb89e850ba24649 | oauth_access/models.py | oauth_access/models.py | import datetime
from django.db import models
from django.contrib.auth.models import User
class UserAssociation(models.Model):
user = models.ForeignKey(User)
service = models.CharField(max_length=75, db_index=True)
identifier = models.CharField(max_length=255, db_index=True)
token = models.CharF... | import datetime
from django.db import models
from django.contrib.auth.models import User
class UserAssociation(models.Model):
user = models.ForeignKey(User)
service = models.CharField(max_length=75, db_index=True)
identifier = models.CharField(max_length=255, db_index=True)
token = models.CharF... | Handle case when token has a null expires | Handle case when token has a null expires
| Python | bsd-3-clause | eldarion/django-oauth-access,eldarion/django-oauth-access |
9d02fcd251cc2f954e559794507e1b052d8bef3c | tests/test_compile_samples.py | tests/test_compile_samples.py | import os.path
import pytest
import rain.compiler as C
def ls(*path):
path = os.path.join(*path)
for file in os.listdir(path):
yield os.path.join(path, file)
def lsrn(*path, recurse=False):
for file in ls(*path):
if os.path.isfile(file) and file.endswith('.rn') and not file.endswith('_pkg.rn'):
yi... | import os.path
import pytest
import rain.compiler as C
def ls(*path):
path = os.path.join(*path)
for file in os.listdir(path):
yield os.path.join(path, file)
def lsrn(*path, recurse=False):
for file in ls(*path):
if os.path.isfile(file) and file.endswith('.rn') and not file.endswith('_pkg.rn'):
yi... | Fix tests for new quiet attribute | tests: Fix tests for new quiet attribute
| Python | mit | philipdexter/rain,philipdexter/rain,philipdexter/rain,scizzorz/rain,philipdexter/rain,scizzorz/rain,scizzorz/rain,scizzorz/rain |
05dbb8055f4e1c61d04daf8324169c7834b5393b | tests/test_get_user_config.py | tests/test_get_user_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import pytest
@pytest.fixture(scope='function')
def back_up_rc(request):
"""
Back up an existing cookiecutter rc and restore it after the tes... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import os
import shutil
import pytest
@pytest.fixture(scope='function')
def back_up_rc(request):
"""
Back up an existing cookiecutter rc and ... | Remove self references from setup/teardown | Remove self references from setup/teardown
| Python | bsd-3-clause | nhomar/cookiecutter,audreyr/cookiecutter,vincentbernat/cookiecutter,cguardia/cookiecutter,luzfcb/cookiecutter,dajose/cookiecutter,vincentbernat/cookiecutter,dajose/cookiecutter,janusnic/cookiecutter,atlassian/cookiecutter,jhermann/cookiecutter,0k/cookiecutter,agconti/cookiecutter,cguardia/cookiecutter,venumech/cookiecu... |
384e7076f8c07f6192f11a813569540ddc98cc0c | kmeans.py | kmeans.py | import numpy as np
class KMeans(object):
def __init__(self, clusters, init=None):
self.clusters = clusters
self.init = init
self.centroids = np.array([])
self.partition = np.array([])
def cluster(self, dataset):
# Randomly choose initial set of centroids if undefined
... | import numpy as np
class KMeans:
def __init__(self, clusters, init=None):
self.clusters = clusters
self.init = init
self.centroids = None
self.partition = None
def cluster(self, dataset):
# Randomly choose initial set of centroids if undefined
if not self.init:
... | Use numpy.random.choice in place of numpy.random.randint. | Use numpy.random.choice in place of numpy.random.randint.
Allows sampling without replacement; hence, removing the possibility
of choosing equal initial centroids.
| Python | mit | kubkon/kmeans |
ad42c66676cc8b7778a4020fff3402bc100f212c | material/admin/__init__.py | material/admin/__init__.py | default_app_config = 'material.admin.apps.MaterialAdminConfig' | default_app_config = 'material.admin.apps.MaterialAdminConfig'
try:
from . import modules
admin = modules.Admin()
except ImportError:
"""
Ok, karenina is not installed
""" | Add module declaration for karenina | Add module declaration for karenina
| Python | bsd-3-clause | Axelio/django-material,MonsterKiller/django-material,refnode/django-material,lukasgarcya/django-material,2947721120/django-material,afifnz/django-material,afifnz/django-material,sourabhdattawad/django-material,MonsterKiller/django-material,koopauy/django-material,koopauy/django-material,thiagoramos-luizalabs/django-mat... |
b2badddd5fb58d6928bdfce84e88951e190f15fb | 02/test_move.py | 02/test_move.py | from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
... | from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
... | Add tests for alternate number pad. | Add tests for alternate number pad.
| Python | mit | machinelearningdeveloper/aoc_2016 |
2a0a29effa48caf5d95ed892d85cee235ebe1624 | lamvery/utils.py | lamvery/utils.py | # -*- coding: utf-8 -*-
import os
import sys
import re
import shlex
import subprocess
from termcolor import cprint
ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$')
def previous_alias(alias):
return '{}-pre'.format(alias)
def parse_env_args(env):
if not isinstance(env, list):
retu... | # -*- coding: utf-8 -*-
import os
import sys
import re
import shlex
import subprocess
ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$')
def previous_alias(alias):
return '{}-pre'.format(alias)
def parse_env_args(env):
if not isinstance(env, list):
return None
ret = {}
for... | Fix error when import lamvery in function | Fix error when import lamvery in function
| Python | mit | marcy-terui/lamvery,marcy-terui/lamvery |
ce59932d485440c592abbacc16c1fc32a7cde6e2 | jktest/testcase.py | jktest/testcase.py |
import unittest
from jktest.config import TestConfig
from jktest.jkind import JKind
from jktest.results import ResultList
class TestCase( unittest.TestCase ):
def assertTrue( self, expr, msg = None ):
super( TestCase, self ).assertTrue( expr, msg )
class JKTestCase( unittest.TestCase ):
# class JKTestC... |
import unittest
from jktest.config import TestConfig
from jktest.jkind import JKind
from jktest.results import ResultList
class TestCase( unittest.TestCase ):
def assertTrue( self, expr, msg = None ):
super( TestCase, self ).assertTrue( expr, msg )
class JKTestCase( unittest.TestCase ):
# class JKTestC... | Add prints for output formatting | Add prints for output formatting
| Python | bsd-3-clause | agacek/jkindRegression,pr-martin/jkindRegression |
07bcbe76f33cb4354cb90744f46c5528169183e3 | launch_pyslvs.py | launch_pyslvs.py | # -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
try:
from core.info.info import show_info, Pyslvs_Splash
args = show_info()
from PyQt5.QtWi... | # -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
try:
from core.info.info import show_info, Pyslvs_Splash
args = show_info()
from PyQt5.QtWi... | Change the Error show in command window. | Change the Error show in command window.
| Python | agpl-3.0 | 40323230/Pyslvs-PyQt5,KmolYuan/Pyslvs-PyQt5,KmolYuan/Pyslvs-PyQt5 |
79dd3b4d0bd1fb331558892b5d29b223d4022657 | feedhq/urls.py | feedhq/urls.py | from django.conf import settings
from django.conf.urls.defaults import url, patterns, include
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse, HttpResponsePermanentRedirect
from ratelimitbackend import admin
admin.autod... | from django.conf import settings
from django.conf.urls.defaults import url, patterns, include
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse, HttpResponsePermanentRedirect
from ratelimitbackend import admin
admin.autod... | Make sure to import the user monkeypatch before anything else that touches it | Make sure to import the user monkeypatch before anything else that touches it
| Python | bsd-3-clause | rmoorman/feedhq,vincentbernat/feedhq,vincentbernat/feedhq,rmoorman/feedhq,rmoorman/feedhq,rmoorman/feedhq,feedhq/feedhq,vincentbernat/feedhq,vincentbernat/feedhq,feedhq/feedhq,feedhq/feedhq,rmoorman/feedhq,feedhq/feedhq,vincentbernat/feedhq,feedhq/feedhq |
b7d0d81bd6030abfee5b3993d42e02896e8c0b50 | edpwd/random_string.py | edpwd/random_string.py | # -*- coding: utf-8
import random, string
def random_string(length,
letters=True,
digits=True,
punctuation=False,
whitespace=False):
""" Returns a random string """
chars = ''
if letters:
chars += string.ascii_letters
if digits:
chars += string.digits
... | # -*- coding: utf-8
from random import choice
import string
def random_string(length,
letters=True,
digits=True,
punctuation=False,
whitespace=False):
""" Returns a random string """
chars = ''
if letters:
chars += string.ascii_letters
if digits:
chars +... | Revert "Use random.sample() rather than reinventing it." | Revert "Use random.sample() rather than reinventing it."
My wrong. sample() doesn't allow repeating characters, so it's not
exactly the same.
| Python | bsd-2-clause | tampakrap/edpwd |
cb39c1edf395f7da1c241010fc833fe512fa74ac | bcbio/distributed/clargs.py | bcbio/distributed/clargs.py | """Parsing of command line arguments into parallel inputs.
"""
def to_parallel(args, module="bcbio.distributed"):
"""Convert input arguments into a parallel dictionary for passing to processing.
"""
ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None),
... | """Parsing of command line arguments into parallel inputs.
"""
def to_parallel(args, module="bcbio.distributed"):
"""Convert input arguments into a parallel dictionary for passing to processing.
"""
ptype, cores = _get_cores_and_type(args.numcores,
getattr(args, "para... | Fix for bcbio-nextgen-vm not passing the local_controller option. | Fix for bcbio-nextgen-vm not passing the local_controller option.
| Python | mit | brainstorm/bcbio-nextgen,brainstorm/bcbio-nextgen,vladsaveliev/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,brainstorm/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,chapmanb/bcbio-nextgen,a113n/bcbio-nextgen,cha... |
99884ec3e960fa7b73e10a6969c455de6eca542b | src/ggrc_workflows/migrations/versions/20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py | src/ggrc_workflows/migrations/versions/20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py |
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revision = '19a67dc67c3'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('cycle_tas... |
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revision = '19a67dc67c3'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('cycle_tas... | Update migration to fix existing CycleTaskGroupObjects | Update migration to fix existing CycleTaskGroupObjects
| Python | apache-2.0 | NejcZupec/ggrc-core,hasanalom/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,vladan-m/ggrc-core,plamut/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-cor... |
18204d7e508052cfabc58bc58e4bb21be13fbd00 | src/webapp/tasks.py | src/webapp/tasks.py | from uwsgidecorators import spool
import database as db
from database.model import Team
from geotools import simple_distance
from geotools.routing import MapPoint
@spool
def get_aqua_distance(args):
team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first()
if team is None:
return
... | import database as db
from database.model import Team
from geotools import simple_distance
from geotools.routing import MapPoint
try:
from uwsgidecorators import spool
except ImportError as e:
def spool(fn):
def nufun(*args, **kwargs):
raise e
return nufun
@spool
def get_aqua_dist... | Raise import errors for uwsgi decorators only if the task is called. | Raise import errors for uwsgi decorators only if the task is called.
| Python | bsd-3-clause | janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system |
7f0b561625b94c6fa6b14dab4bbe02fa28d38bfa | statement_format.py | statement_format.py | import pandas as pd
def fn(row):
if row['Type'] == 'DIRECT DEBIT':
return 'DD'
if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME':
return 'BP'
if row['Amount (GBP)'] < 0:
return 'SO'
raise Exception('Unintended state')
df = pd.read_csv('statement.csv')
... | import pandas as pd
def fn(row):
if row['Type'] == 'DIRECT DEBIT':
return 'DD'
if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME':
return 'BP'
if row['Amount (GBP)'] < 0:
return 'SO'
raise Exception('Unintended state')
df = pd.read_csv('statement.csv')
... | Correct numbers. Now to format output | Correct numbers. Now to format output
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit |
05f220d6090be58ee465b6f30d01e14079bcbeba | corehq/messaging/scheduling/scheduling_partitioned/dbaccessors.py | corehq/messaging/scheduling/scheduling_partitioned/dbaccessors.py |
def save_schedule_instance(instance):
instance.save()
| from corehq.sql_db.util import (
get_object_from_partitioned_database,
save_object_to_partitioned_database,
run_query_across_partitioned_databases,
)
from datetime import datetime
from django.db.models import Q
def get_schedule_instance(schedule_instance_id):
from corehq.messaging.scheduling.schedulin... | Add functions for processing ScheduleInstances | Add functions for processing ScheduleInstances
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
fbe446727b35680e747c74816995f6b7912fffeb | syslights_server.py | syslights_server.py | #!/usr/bin/env python3
import sys
import time
import glob
import serial
import psutil
CPU_INTERVAL = 0.5
CONNECT_TIMEOUT = 2
BAUD = 4800
def update_loop(conn):
while True:
load = psutil.cpu_percent(interval=CPU_INTERVAL)
scaled_load = int(load * 10)
message = str(scaled_load).encode('asc... | #!/usr/bin/env python3
import sys
import time
import glob
import serial
import psutil
CPU_INTERVAL = 0.5
CONNECT_TIMEOUT = 2
BAUD = 4800
def update_loop(conn):
while True:
load = psutil.cpu_percent(interval=CPU_INTERVAL)
scaled_load = int(load * 10)
message = str(scaled_load).encode('asc... | Fix error handling in server | Fix error handling in server
| Python | mit | swarmer/syslights |
5e0e0e792ca36b7a6daea3931e5333d5d6f28281 | pygout/cmdline.py | pygout/cmdline.py | import sys
def main(argv=sys.argv):
raise NotImplementedError
| import sys
import argparse
import pygments.styles
from pygout.application import find_apps
class _ListStyles(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
styles = sorted(pygments.styles.get_all_styles())
parser.exit(0, '\n'.join(styles) + '\n')
class _ListApp... | Add argument parsing for 'pygout' command | Add argument parsing for 'pygout' command
| Python | bsd-3-clause | alanbriolat/PygOut |
76b47fec3b24410f875db96b3404c47d4c3634cb | sheepdog_tables/__init__.py | sheepdog_tables/__init__.py | __version__ = '1.2.0'
try:
from django.conf import settings
getattr(settings, 'dummy_attr', 'dummy_value')
_LOAD_PACKAGES = True
except:
# Just running sdist, we think
_LOAD_PACKAGES = False
if _LOAD_PACKAGES:
from mixins import (TablesMixin, EditTablesMixin, FilteredListView,
... | __version__ = '1.2.0'
try:
from django.conf import settings
getattr(settings, 'dummy_attr', 'dummy_value')
_LOAD_PACKAGES = True
except:
# Just running sdist, we think
_LOAD_PACKAGES = False
if _LOAD_PACKAGES:
from mixins import TablesMixin, EditTablesMixin, FilteredListView
from column im... | Fix import error after removal of old csv table mixin | Fix import error after removal of old csv table mixin
| Python | bsd-3-clause | SheepDogInc/sheepdog_tables,SheepDogInc/sheepdog_tables |
660cd7526c1aad6632446b1af5ae286b5383b52c | tests/commands/load/test_load_cnv_report_cmd.py | tests/commands/load/test_load_cnv_report_cmd.py | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | Fix code style issues with Black | Fix code style issues with Black
| Python | bsd-3-clause | Clinical-Genomics/scout,Clinical-Genomics/scout,Clinical-Genomics/scout |
51c5e4e1e670f52584c157330a9a3b910be92d57 | runtests.py | runtests.py | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitema... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitema... | Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS. | Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
| Python | mit | simonluijk/django-localeurl,jmagnusson/django-localeurl |
d18ff01e737155eca2cb6c765291e6239328b003 | scipy/lib/_numpy_compat.py | scipy/lib/_numpy_compat.py | """Functions copypasted from newer versions of numpy.
"""
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from scipy.lib._version import NumpyVersion
if NumpyVersion(np.__version__) > '1.7.0.dev':
_assert_warns = np.testing.assert_warns
else:
def _assert_... | """Functions copypasted from newer versions of numpy.
"""
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from scipy.lib._version import NumpyVersion
if NumpyVersion(np.__version__) > '1.7.0.dev':
_assert_warns = np.testing.assert_warns
else:
def _assert_... | Add a 'count_nonzero' function to use with numpy 1.5.1. | MAINT: Add a 'count_nonzero' function to use with numpy 1.5.1.
| Python | bsd-3-clause | perimosocordiae/scipy,andyfaff/scipy,aman-iitj/scipy,jakevdp/scipy,dominicelse/scipy,zerothi/scipy,zxsted/scipy,matthewalbani/scipy,anielsen001/scipy,zxsted/scipy,WillieMaddox/scipy,endolith/scipy,cpaulik/scipy,anielsen001/scipy,woodscn/scipy,bkendzior/scipy,gef756/scipy,mdhaber/scipy,futurulus/scipy,Stefan-Endres/scip... |
be922ce28931c101a245aa4b5b0f74c31c23cc60 | tests/test_group.py | tests/test_group.py | from unittest import TestCase
class GroupTestCase(TestCase):
def get_persons(self):
pass | from unittest import TestCase
from address_book import Person, Group
class GroupTestCase(TestCase):
def get_persons(self):
john_person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
['+79834772053'],
... | Test the ability to add and get all persons in the group | Test the ability to add and get all persons in the group
| Python | mit | dizpers/python-address-book-assignment |
be4d21b5486f3bba5a4d844015d3d35630ac7d03 | udata/auth/forms.py | udata/auth/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask_security.forms import RegisterForm
from udata.forms import fields
from udata.forms import validators
class ExtendedRegisterForm(RegisterForm):
first_name = fields.StringField(
'First Name', [validators.Required('First name is requ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask_security.forms import RegisterForm
from udata.forms import fields
from udata.forms import validators
from udata.i18n import lazy_gettext as _
class ExtendedRegisterForm(RegisterForm):
first_name = fields.StringField(
_('First name'... | Apply i18n to First and Last name in registration form | Apply i18n to First and Last name in registration form
| Python | agpl-3.0 | etalab/udata,etalab/udata,etalab/udata,opendatateam/udata,opendatateam/udata,opendatateam/udata |
12728f6b924a3d45f78b3955cb9fcb563db6a81f | pida_abc_type.py | pida_abc_type.py | from abc import ABCMeta, abstractmethod
class IdaTypes:
__metaclass__ = ABCMeta
@abstractmethod
def decode(self, data):
raise NotImplementedError()
@abstractmethod
def get_name(self):
raise NotImplementedError()
@abstractmethod
def get_type(self):
raise NotImplem... | from abc import ABCMeta, abstractmethod
class IdaTypes:
__metaclass__ = ABCMeta
@abstractmethod
def decode(self, data):
raise NotImplementedError()
@abstractmethod
def get_type(self):
raise NotImplementedError()
| Delete abstract method get name | Delete abstract method get name
| Python | mit | goodwinxp/ATFGenerator,goodwinxp/ATFGenerator,goodwinxp/ATFGenerator |
e421a3cfd9ecfe05aa21b2b3da792f7ab824727d | experimental/db/remove_property.py | experimental/db/remove_property.py | """ Remove a property from the datastore.
How to use:
$ cd experimental/db/
$ PYTHONPATH=. remote_api_shell.py -s homeawesomation.appspot.com
> import remove_property
"""
from google.appengine.api import namespace_manager
from google.appengine.ext import db
class Base(db.Expando): pass
def remove(namespace, field):... | """ Remove a property from the datastore.
How to use:
$ cd experimental/db/
$ PYTHONPATH=. remote_api_shell.py -s homeawesomation.appspot.com
> import remove_property
"""
from google.appengine.api import namespace_manager
from google.appengine.ext import db
class Base(db.Expando): pass
def remove(namespace, field):... | Fix datastore delete field script. | Fix datastore delete field script.
| Python | mit | tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation |
1fac10d27f00322e34c3b89527c32b1dcb02decd | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an inte... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an inte... | Support Stylus blocks in Vue single-file components | Support Stylus blocks in Vue single-file components
| Python | mit | jackbrewer/SublimeLinter-contrib-stylint |
33b5e210ffc32f9f7b3764e1f6f3d54e1f040783 | changes/flow.py | changes/flow.py | import logging
from plumbum import local, CommandNotFound
from changes.changelog import generate_changelog
from changes.packaging import build_package, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change
from changes.verification import run_tests
from changes... | import logging
import click
from changes.changelog import generate_changelog
from changes.config import project_config, store_settings
from changes.packaging import build_distributions, install_package, upload_package, install_from_pypi
from changes.vcs import tag_and_push, commit_version_change, create_github_releas... | Add github releases to publishing | Add github releases to publishing
| Python | mit | goldsborough/changes |
bca298cc9942005f3ab6c74359a52a4c410a5231 | manage.py | manage.py | from flask.ext.script import Manager
from flask.ext.alembic import ManageMigrations
import os
from starter import app, db
from starter.users.models import user_datastore
manager = Manager(app)
manager.add_command("migrate", ManageMigrations())
@manager.command
def add_admin(email, password):
user = user_datast... | from flask.ext.script import Manager
from flask.ext.alembic import ManageMigrations
import os
from starter import app, db
from starter.users.models import user_datastore
manager = Manager(app)
manager.add_command("migrate", ManageMigrations())
@manager.command
def add_admin(email, password):
user = user_datast... | Update config file with updated project name | Update config file with updated project name
| Python | mit | litnimax/flask-starter,andrewsnowden/flask-starter,wenxer/flask-starter,andrewsnowden/flask-starter,litnimax/flask-starter,litnimax/flask-starter,wenxer/flask-starter,andrewsnowden/flask-starter,wenxer/flask-starter |
6aec2246389934bca253a2fcd18f3ac24525c670 | molvs/utils.py | molvs/utils.py | # -*- coding: utf-8 -*-
"""
molvs.utils
~~~~~~~~~~~
This module contains miscellaneous utility functions.
:copyright: Copyright 2014 by Matt Swain.
:license: MIT, see LICENSE file for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
impor... | # -*- coding: utf-8 -*-
"""
molvs.utils
~~~~~~~~~~~
This module contains miscellaneous utility functions.
:copyright: Copyright 2014 by Matt Swain.
:license: MIT, see LICENSE file for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
impor... | Fix izip import for python3 | Fix izip import for python3
| Python | mit | mcs07/MolVS |
d99ad3de00ec8bb9b3a36de5f50bd4f48a08cbb1 | test/acceptance/test_cli_vital.py | test/acceptance/test_cli_vital.py | import unittest
from pathlib import Path
import subprocess
class TestVintDoNotDiedWhenLintingVital(unittest.TestCase):
def assertVintStillAlive(self, cmd):
try:
got_output = subprocess.check_output(cmd,
stderr=subprocess.STDOUT,
... | import unittest
from pathlib import Path
import subprocess
class TestVintDoNotDiedWhenLintingVital(unittest.TestCase):
def assertVintStillAlive(self, cmd):
try:
got_output = subprocess.check_output(cmd,
stderr=subprocess.STDOUT,
... | Fix false-negative test caused by using fallbacked assertNotRegex | Fix false-negative test caused by using fallbacked assertNotRegex
| Python | mit | Kuniwak/vint,RianFuro/vint,Kuniwak/vint,RianFuro/vint |
ba722635f13350c4b1e04aeab0838c923deb1985 | feeds/middlewares.py | feeds/middlewares.py | import logging
from scrapy.spidermiddlewares.httperror import HttpError
logger = logging.getLogger(__name__)
class FeedsHttpErrorMiddleware:
@classmethod
def from_crawler(cls, crawler):
return cls()
def process_spider_exception(self, response, exception, spider):
if isinstance(exceptio... | import logging
from scrapy.spidermiddlewares.httperror import HttpError
logger = logging.getLogger(__name__)
class FeedsHttpErrorMiddleware:
@classmethod
def from_crawler(cls, crawler):
return cls()
def process_spider_exception(self, response, exception, spider):
if isinstance(exceptio... | Use log level info for HTTP statuses 500, 502, 503, 504. | Use log level info for HTTP statuses 500, 502, 503, 504.
These status codes are usually induced by overloaded sites, updates, short
downtimes, etc. and are not that relevant.
| Python | agpl-3.0 | Lukas0907/feeds,Lukas0907/feeds,nblock/feeds,nblock/feeds |
150dad224dd985762714b73e9a91d084efb11e06 | ob_pipelines/sample.py | ob_pipelines/sample.py | import os
from luigi import Parameter
from ob_airtable import get_record_by_name, get_record
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
def get_samples(expt_id):
expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_k... | import os
from luigi import Parameter
from ob_airtable import AirtableClient
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
client = AirtableClient()
def get_samples(expt_id):
expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TA... | Update to match changes in ob-airtable | Update to match changes in ob-airtable
| Python | apache-2.0 | outlierbio/ob-pipelines,outlierbio/ob-pipelines,outlierbio/ob-pipelines |
af10bb6acd0a7f4f68d71662eca648ef51eba1c4 | src/lib/db/redismanager.py | src/lib/db/redismanager.py | import redis
import pickle
from .idatabasemanager import IDatabaseManager
class RedisManager(IDatabaseManager):
KEY_MESSAGE_QUEUE = 'message_queue'
def __init__(self, redis_url):
self.connection = redis.Redis.from_url(redis_url)
def queue_message(self, message):
serialized_message = pick... | import redis
import pickle
from .idatabasemanager import IDatabaseManager
class RedisManager(IDatabaseManager):
KEY_MESSAGE_QUEUE = 'message_queue'
def __init__(self, redis_url):
self.connection = redis.Redis.from_url(redis_url)
def queue_message(self, message):
serialized_message = pick... | Fix object serialization and deserialization in Redis Manager module. | Fix object serialization and deserialization in Redis Manager module.
| Python | mit | edonosotti/wechat-bot-skeleton-python |
c973068ada6fa5039a289719c852f06fe786c8fa | bucketeer/test/test_commit.py | bucketeer/test/test_commit.py | import unittest
import boto
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket
existing_bucket = 'bucket.exists'
def setUp(self):
# Create a bucket with one file
connection = boto.connect_s3()
bucket = connection.create_bucket(existing_bucket)
return
... | import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket, test_dir
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
def setUp(self):
# Create a bucket to test on existing bucket
connection = boto.connect_s3()
bucket = c... | Add create test file dir to setUp and tearDown | Add create test file dir to setUp and tearDown
May need to revisit and identify best place to put such a directory.
| Python | mit | mgarbacz/bucketeer |
d2ac548441523e2ed4d0ac824e5972ae48be3b19 | packages/Python/lldbsuite/test/lang/swift/closure_shortcuts/TestClosureShortcuts.py | packages/Python/lldbsuite/test/lang/swift/closure_shortcuts/TestClosureShortcuts.py | # TestAccelerateSIMD.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTR... | # TestClosureShortcuts.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CON... | Fix typo and run everywhere. | Fix typo and run everywhere. | Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb |
0dcc2a5865ed31618f63e9b152501cf8fbc201ac | doorman/main.py | doorman/main.py | import argparse
import os
from doorman import Doorman
parser = argparse.ArgumentParser(description='Doorman keeps your secret things')
parser.add_argument('-s', '--secret', action="store_true", dest="status", help='Hide all secret things')
parser.add_argument('-u', '--unsecret', action="store_false", dest="status", he... | import argparse
import os
from doorman import Doorman
DEFAULT_CONFIG_PATH = os.path.join(os.path.expanduser("~"), ".doormanrc")
DEFAULT_CONFIG = """[secrets]
test_secret =
[files]
test_secret =
"""
if not os.path.exists(DEFAULT_CONFIG_PATH):
with open(DEFAULT_CONFIG_PATH, "w") as f:
f.write(DEFAULT_CONFI... | Add default parameter and default config | Add default parameter and default config
| Python | mit | halitalptekin/doorman |
7fb46bc6fc2c5783569f869bf4855d1ed3709ccb | elmo/moon_tracker/forms.py | elmo/moon_tracker/forms.py | from django import forms
class BatchMoonScanForm(forms.Form):
data = forms.CharField(
widget=forms.Textarea(attrs={'class':'form-control monospace'}),
)
| from django import forms
import csv
from io import StringIO
class BatchMoonScanForm(forms.Form):
data = forms.CharField(
widget=forms.Textarea(attrs={'class':'form-control monospace'}),
)
def clean(self):
cleaned_data = super(BatchMoonScanForm, self).clean()
raw = StringIO(cleaned... | Add clean method for batch submission form. | Add clean method for batch submission form.
| Python | mit | StephenSwat/eve_lunar_mining_organiser,StephenSwat/eve_lunar_mining_organiser |
f4d7f7207cff82c38d6973dbef717bfc50345b32 | models.py | models.py | from django.db import models
class FandomHierarchy(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey('self')
class Image(models.Model):
pixel_width = models.IntegerField()
pixel_height = models.IntegerField()
name = models.CharField(max_length=100)
fandoms = models.ManyToManyFie... | from django.db import models
class FandomHierarchy(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey('self')
def __unicode__(self):
return "Fandom tree node %s" % self.name
class Image(models.Model):
pixel_width = models.IntegerField()
pixel_height = models.IntegerField()
name... | Add __unicode__ methods to model | Add __unicode__ methods to model
| Python | bsd-3-clause | willmurnane/store |
ce291ba622ae27e0bdb448fee26b37c9af4ffeb0 | example/urls.py | example/urls.py | from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
u... | from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comme... | Fix running the example project with Django 1.5 | Fix running the example project with Django 1.5
| Python | apache-2.0 | BangorUniversity/django-fluent-comments,PetrDlouhy/django-fluent-comments,mgpyh/django-fluent-comments,Afnarel/django-fluent-comments,django-fluent/django-fluent-comments,BangorUniversity/django-fluent-comments,PetrDlouhy/django-fluent-comments,BangorUniversity/django-fluent-comments,Afnarel/django-fluent-comments,djan... |
fc2d03b5ec8de233b61994b26d27214ada719d33 | humanize/__init__.py | humanize/__init__.py | VERSION = (0,5,1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = ['VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
'naturaldelta', 'intcomma', 'apnumber', 'fractional', 'naturalsize',
'activate', '... | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
'naturaldelta', 'intcomma', 'apnumber', 'fractional', '... | Add common __version__, same as VERSION | Add common __version__, same as VERSION
| Python | mit | jmoiron/humanize,jmoiron/humanize |
877a8fc9989644312b18c5eeeb6552f84350c182 | timed/redmine/admin.py | timed/redmine/admin.py | from django.contrib import admin
from timed.projects.admin import ProjectAdmin
from timed.projects.models import Project
from timed_adfinis.redmine.models import RedmineProject
admin.site.unregister(Project)
class RedmineProjectInline(admin.StackedInline):
model = RedmineProject
@admin.register(Project)
class... | from django.contrib import admin
from timed.projects.admin import ProjectAdmin
from timed.projects.models import Project
from timed_adfinis.redmine.models import RedmineProject
from timed_adfinis.subscription.admin import SubscriptionProjectInline
admin.site.unregister(Project)
class RedmineProjectInline(admin.Stac... | Add support subscriptions for parity with SSA portal | Add support subscriptions for parity with SSA portal
These includes:
* customer password
* subscription and packages
* orders
* import from timescout
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend |
59fef68bee92c45438a87336c92bce031de21139 | tests/test_utils.py | tests/test_utils.py |
from datetime import timedelta
from jose import utils
class TestUtils:
def test_total_seconds(self):
td = timedelta(seconds=5)
assert utils.timedelta_total_seconds(td) == 5
def test_long_to_base64(self):
assert utils.long_to_base64(0xDEADBEEF) == b'3q2-7w'
|
from datetime import timedelta
from jose import utils
class TestUtils:
def test_total_seconds(self):
td = timedelta(seconds=5)
assert utils.timedelta_total_seconds(td) == 5
def test_long_to_base64(self):
assert utils.long_to_base64(0xDEADBEEF) == b'3q2-7w'
assert utils.lon... | Add test for size parameter of long_to_base64. | Add test for size parameter of long_to_base64.
| Python | mit | mpdavis/python-jose |
554cedb2113f57799f0c62b42d6ff1b317c6100a | ingestors/support/image.py | ingestors/support/image.py | try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from PIL import Image
from PIL.Image import DecompressionBombWarning
from ingestors.exc import ProcessingException
class ImageSupport(object):
"""Provides helpers for image extraction."""
def parse_image(self, data... | try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from PIL import Image
from PIL.Image import DecompressionBombError as DBE
from PIL.Image import DecompressionBombWarning as DBW
from ingestors.exc import ProcessingException
class ImageSupport(object):
"""Provides helpe... | Handle decompression bomb errors as well as warnings. | Handle decompression bomb errors as well as warnings.
| Python | mit | alephdata/ingestors |
4117b767f48678542797d811cc1a8ea75f37c714 | saleor/account/migrations/0040_auto_20200415_0443.py | saleor/account/migrations/0040_auto_20200415_0443.py | # Generated by Django 3.0.5 on 2020-04-15 09:43
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
c... | # Generated by Django 3.0.5 on 2020-04-15 09:43
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
c... | Remove unused permission from db | Remove unused permission from db
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor |
080101d59490ca5f5b0b1208a9a11663cdfaf7a7 | results/views.py | results/views.py | # Create your views here.
| # Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from libs.parser import Parser
import os, settings
from plots.models import Md5Log, BenchmarkLogs, MachineInfo, RtAverage, RtMoss, RtBldg391, RtM35, RtSphflake, RtWorld, RtStar
def show_result(request, ... | Add show_result view that extracts data from the database for the file, and sends it on to the result.html template | Add show_result view that extracts data from the database for the file, and sends it on to the result.html template
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark |
0827ea6ef23e87461bb936684bc61bcc1cb6b42f | spider.py | spider.py | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... | Add XPath query to extract dataset name | Add XPath query to extract dataset name
| Python | mit | MaxLikelihood/CODE |
f8c61141e8466a408284f45ca331a2f6d87f9363 | django_extensions/settings.py | django_extensions/settings.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
REPLACEMENTS = getattr(settings, 'EXTENSIONS_REPLACEMENTS', {})
DEFAULT_SQLITE_ENGINES = (
'django.db.backends.sqlite3',
'django.db.backends.spatialite',
)
DEFAULT_MYSQL_ENGINES = (
'... | # -*- coding: utf-8 -*-
import os
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
REPLACEMENTS = getattr(settings, 'EXTENSIONS_REPLACEMENTS', {})
DEFAULT_SQLITE_ENGINES = (
'django.db.backends.sqlite3',
'django.db.backends.spatialite',
)
DEFAULT_MYSQL_ENGINES = (
'... | Add django-zero-downtime-migrations Postgres DB engine | Add django-zero-downtime-migrations Postgres DB engine
From the repo:
https://github.com/tbicr/django-pg-zero-downtime-migrations | Python | mit | django-extensions/django-extensions,django-extensions/django-extensions,django-extensions/django-extensions |
557f4129dc50acddd6c80d0a0679d8c82d5d9215 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Patrik,,,
# Copyright (c) 2015 Patrik,,,
#
# License: MIT
#
"""This module exports the Polylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Polylint(NodeLinter):
"""Provides an inte... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Patrik,,,
# Copyright (c) 2015 Patrik,,,
#
# License: MIT
#
"""This module exports the Polylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Polylint(NodeLinter):
"""Provides an inte... | Use proper flag for single file error reporting | Use proper flag for single file error reporting
"inputs-only" was changed to "no-recursion" before getting merged
| Python | mit | nomego/SublimeLinter-contrib-polylint |
53cca5180ec5ad04694ce28d0fc0d945004c33b3 | src/unifind.py | src/unifind.py | class UnionFind:
def __init__(self, it=None):
self.uf = {} if it is None else {i : i for i in it}
self.count = len(self.uf)
def __iter__(self):
return iter(self.uf.keys())
def __getitem__(self, key):
return self.uf[key]
def __setitem__(self, key, val):
if key ... | class UnionFind:
def __init__(self, it=None):
self.uf = {} if it is None else {i : i for i in it}
self.count = len(self.uf)
def __iter__(self):
return iter(self.uf.keys())
def __getitem__(self, key):
return self.uf[key]
def __setitem__(self, key, val):
if key ... | Fix QuickFind: stop relying on keys being integers | Fix QuickFind: stop relying on keys being integers
| Python | mit | all3fox/algos-py |
56cde7a0a93a733e0f2958837f935b1446214168 | tests/test_artefacts.py | tests/test_artefacts.py | import pytest
from plumbium import artefacts
def test_NiiGzImage_basename():
img = artefacts.NiiGzImage('foo.nii.gz')
assert img.basename == 'foo'
def test_NiiGzImage_bad_extension():
with pytest.raises(ValueError):
img = artefacts.NiiGzImage('foo.nii.gx')
| import pytest
from plumbium import artefacts
def test_Artefact_basename():
img = artefacts.Artefact('foo.nii.gz', '.nii.gz')
assert img.basename == 'foo'
def test_Artefact_repr():
img = artefacts.Artefact('foo.nii.gz', '.nii.gz')
assert repr(img) == "Artefact('foo.nii.gz')"
def test_NiiGzImage_bad... | Improve test coverage of artefact module | Improve test coverage of artefact module
| Python | mit | jstutters/Plumbium |
460bb04533b96e7812964553d9af0c5e25033f21 | rxet/helper.py | rxet/helper.py | from struct import unpack
def read_uint32(fileobj):
return unpack("I", fileobj.read(4))[0]
# read int as a big endian number
def read_uint32_BE(fileobj):
return unpack(">I", fileobj.read(4))[0] | from struct import unpack
def read_uint32(fileobj):
return unpack("I", fileobj.read(4))[0]
# read int as a big endian number
def read_uint32_BE(fileobj):
return unpack(">I", fileobj.read(4))[0]
def unpack_uint32(data, offset):
return unpack("I", data[offset:offset+4])[0] | Add unpacking of uint32 at an offset | Add unpacking of uint32 at an offset
| Python | mit | RenolY2/battalion-tools |
71100d859689a975c6a9bcb06bd5ec8dedbcc876 | preferences/views.py | preferences/views.py | from django.shortcuts import render
from django.views.generic.edit import FormView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.forms import PreferencesForm
class EmailRegistrationView(RegistrationView):
form_class ... | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.peopl... | Make view to handle saving and displaying of preferences form | Make view to handle saving and displaying of preferences form
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
05d2230015e085cba408474539f997f7fecd2f91 | tests/utils.py | tests/utils.py | # -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from os.path import abspath, dirname, join
TEST_DIR = abspath(dirname(__file__))
def load_snippet(file_name):
"""Helper to fetch in the content of a test snippet."""
file_path = ... | # -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from os.path import abspath, dirname, join
TEST_DIR = abspath(dirname(__file__))
def load_snippet(file_name):
"""Helper to fetch in the content of a test snippet."""
file_path = ... | Load articles/snippets as binary strings | Load articles/snippets as binary strings
| Python | bsd-2-clause | bookieio/breadability,bookieio/breadability |
b7e6e2d6665e5ec81bddcb77b33de6a2d2bc7807 | users/views.py | users/views.py | from rest_framework import generics
from django.contrib.auth.models import User
from users.serializers import UserSerializer
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Use... | from rest_framework import generics, permissions
from django.contrib.auth.models import User
from users.serializers import UserSerializer
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
p... | Add permission to edit user | Add permission to edit user
| Python | mit | OscaRoa/api-cats |
3d74cd5a02f1d5aefb98e4ef97a1ef458a6b79ea | IPython/zmq/__init__.py | IPython/zmq/__init__.py | #-----------------------------------------------------------------------------
# Copyright (C) 2010 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#------------------------------------------------... | #-----------------------------------------------------------------------------
# Copyright (C) 2010 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#------------------------------------------------... | Check for dev version of zmq per @minrk's request | Check for dev version of zmq per @minrk's request | Python | bsd-3-clause | ipython/ipython,ipython/ipython |
5cf4cd8b457bf3c6fa7b4f46b1ed4dfd542e5139 | scripts/lib/fontbuild/decomposeGlyph.py | scripts/lib/fontbuild/decomposeGlyph.py | def decomposeGlyph(glyph):
"""Moves the components of a glyph to its outline."""
font = glyph.getParent()
for component in glyph.components:
componentGlyph = font[component.baseGlyph]
for contour in componentGlyph:
contour = contour.copy()
contour.move(component.offs... | def decomposeGlyph(glyph):
"""Moves the components of a glyph to its outline."""
font = glyph.getParent()
for component in glyph.components:
componentGlyph = font[component.baseGlyph]
for contour in componentGlyph:
contour = contour.copy()
contour.scale(component.sca... | Move after scaling during decomposition. | Move after scaling during decomposition.
| Python | apache-2.0 | supriyantomaftuh/roboto,anthrotype/roboto,urandu/roboto,urandu/roboto,bowlofstew/roboto,googlefonts/roboto,moyogo/roboto,Cartman0/roboto,moyogo/roboto,Cartman0/roboto,supriyantomaftuh/roboto,googlefonts/roboto,anthrotype/roboto,bowlofstew/roboto |
95dab3dbd10ed923c3d37d29efda6ab8ee971c61 | plugin.py | plugin.py | import pre
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
import supybot.ircdb as ircdb
from supybot.commands import *
import supybot.irclib as irclib
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.ircutils as ircuti... | import pre
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
import supybot.ircdb as ircdb
from supybot.commands import *
import supybot.irclib as irclib
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.ircutils as ircuti... | Send PM to querying user (i think? bad docs.) | Send PM to querying user (i think? bad docs.)
| Python | mit | bcowdery/supybot-predb-plugin |
f41e46c0dd0b859cdcc88a2d3ae96fa01864445f | plugin.py | plugin.py | import os
import sublime
def plugin_loaded():
disable_native_php_package_completions()
def disable_native_php_package_completions():
completions_file = os.path.join(
sublime.packages_path(),
'PHP',
'PHP.sublime-completions'
)
if not os.path.isfile(completions_file):
... | import os
import sublime
def plugin_loaded():
# disable_native_php_package_completions
completions_file = os.path.join(sublime.packages_path(), 'PHP', 'PHP.sublime-completions')
if not os.path.isfile(completions_file):
os.makedirs(os.path.dirname(completions_file))
with open(completions_fil... | Remove fixes for sublime text backwards compatibility | Remove fixes for sublime text backwards compatibility
I'm not working around sublime text issues anymore.
| Python | bsd-3-clause | gerardroche/sublime-phpck |
26e26e50ddd8b64fd3206788ef1defbf337698e5 | app/urls.py | app/urls.py | # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Add ID support for subscription/ URLs. | Add ID support for subscription/ URLs.
| Python | agpl-3.0 | joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend |
ebfc7061f7515af3ec8b2f61bdbcf4a26c212095 | src/clarifai_client.py | src/clarifai_client.py | from clarifai.rest import ClarifaiApp
class Clarifai():
def __init__(self, api_id, api_secret):
self.api_id = api_id
self.api_secret = api_secret
self.app = ClarifaiApp(self.api_id, self.api_secret)
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/me... | from clarifai.rest import ClarifaiApp
class Clarifai():
def __init__(self, api_id, api_secret):
self.api_id = api_id
self.api_secret = api_secret
self.app = ClarifaiApp(self.api_id, self.api_secret)
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/me... | Test on clarifai is working and returns the tags | Test on clarifai is working and returns the tags
| Python | apache-2.0 | rlokc/PyCVTagger |
51222dd65133159c1fe65a51e8f2ce237d40edef | geotrek/outdoor/forms.py | geotrek/outdoor/forms.py | from crispy_forms.layout import Div
from geotrek.common.forms import CommonForm
from geotrek.outdoor.models import Site
class SiteForm(CommonForm):
geomfields = ['geom']
fieldslayout = [
Div(
'structure',
'name',
'description',
'eid',
)
]
... | from crispy_forms.layout import Div
from django import forms
from geotrek.common.forms import CommonForm
from geotrek.outdoor.models import Site, Practice, SitePractice
class SiteForm(CommonForm):
practices = forms.ModelMultipleChoiceField(
queryset=Practice.objects.all(),
widget=forms.CheckboxSel... | Add multiple choice of practices to Site form | Add multiple choice of practices to Site form
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek |
e93789084c03b2a566835006d6d5adaee3d4bbe6 | silk/globals.py | silk/globals.py | #!/usr/bin/env python
__all__ = []
try:
from silk.webdoc import css, html, node
__all__.extend(('css', 'html', 'node'))
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, ... | #!/usr/bin/env python
__all__ = []
try:
from silk.webdoc import css, html, node
__all__ += ['css', 'html', 'node']
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, Refer... | Use += to modify __all__, to appease flake8 | Use += to modify __all__, to appease flake8
| Python | bsd-3-clause | orbnauticus/silk |
0af35018fbdf2460d8890a7d7b4ad8246a3d121d | IPython/testing/__init__.py | IPython/testing/__init__.py | """Testing support (tools to test IPython itself).
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this so... | """Testing support (tools to test IPython itself).
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this so... | Allow any options to be passed through test function | Allow any options to be passed through test function
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
5ccadaae69f8011f16f7df7ae5711277931a94a8 | tests/testall.py | tests/testall.py | #!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') an... | #!/usr/bin/env python
import unittest, os, sys
for x in ['LANGUAGE', 'LANG']:
if x in os.environ:
del os.environ[x]
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_... | Clear $LANGUAGE before running tests | Clear $LANGUAGE before running tests
| Python | lgpl-2.1 | timdiels/0publish |
76f6497389d2e6588d91fbd7c24d2f368592140b | tests/utils.py | tests/utils.py | import bottle
import threading
import time as _time
def start_bottle_server(app, port, **kwargs):
server_thread = ServerThread(app, port, kwargs)
server_thread.daemon = True
server_thread.start()
_time.sleep(0.1)
class ServerThread(threading.Thread):
def __init__(self, app, port, server_kwargs):
... | import bottle
import threading
import socket
import time as _time
def start_bottle_server(app, port, **kwargs):
server_thread = ServerThread(app, port, kwargs)
server_thread.daemon = True
server_thread.start()
ok = False
for i in range(10):
try:
conn = socket.create_connect... | Test server existence via a socket connection | Test server existence via a socket connection
| Python | bsd-2-clause | p/webracer |
dc786699618e6ebc1206080d9c0fdb697d519668 | pydy/viz/server.py | pydy/viz/server.py | #!/usr/bin/env python
import os
import webbrowser
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
__all__ = ['run_server']
def run_server(port=8000,scene_file="Null"):
#change dir to static first.
os.chdir("static/")
HandlerClass = SimpleHTTPRequestHandler
ServerClass = ... | #!/usr/bin/env python
import os
import sys
import webbrowser
if sys.version_info < (3, 0):
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
else:
from http.server import SimpleHTTPRequestHandler
from http.server import HTTPServer
__all__ = ['run_server']
d... | Fix HTTPServer imports with Python 3 | Fix HTTPServer imports with Python 3
| Python | bsd-3-clause | Shekharrajak/pydy,Shekharrajak/pydy,skidzo/pydy,skidzo/pydy,oliverlee/pydy,Shekharrajak/pydy,oliverlee/pydy,skidzo/pydy,skidzo/pydy,Shekharrajak/pydy,oliverlee/pydy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.