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
dcfb5116ba5f068afa354d063a4ab33bce853715
numba/sigutils.py
numba/sigutils.py
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): return isinstance(sig, (str, tuple)) def normalize_signature(sig): if isinstance(sig, str): return normalize_signature(parse_signature(sig)) elif isinstance(sig, tuple): ...
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): """ Return whether *sig* is a valid signature specification (for user-facing APIs). """ return isinstance(sig, (str, tuple, typing.Signature)) def normalize_signature(sig): ...
Add docstrings and fix failures
Add docstrings and fix failures
Python
bsd-2-clause
pitrou/numba,GaZ3ll3/numba,pitrou/numba,gdementen/numba,ssarangi/numba,gmarkall/numba,stonebig/numba,stonebig/numba,seibert/numba,GaZ3ll3/numba,gmarkall/numba,stonebig/numba,IntelLabs/numba,seibert/numba,pombredanne/numba,numba/numba,seibert/numba,jriehl/numba,pitrou/numba,numba/numba,stefanseefeld/numba,IntelLabs/numb...
ff28ca5797c4468dbe58d78d55b5df6b8878ac36
test_pep438.py
test_pep438.py
#!/usr/bin/env python import unittest import pep438 if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest import sys from io import StringIO from clint.textui import core import pep438 class patch_io(object): streams = ('stdout', 'stdin', 'stderr') def __init__(self): for stream in self.streams: setattr(self, stream, StringIO()) setattr(self...
Add a basic command line test
Add a basic command line test
Python
mit
treyhunner/pep438
b35e8fa3cde243aa444aa056d60f7a37b61e825b
tests/commands/test_usage.py
tests/commands/test_usage.py
import os import subprocess import pytest def test_list_subcommands_has_all_scripts(): """Tests if the output from running `fontbakery --list-subcommands` matches the fontbakery scripts within the bin folder.""" import fontbakery.commands commands_dir = os.path.dirname(fontbakery.commands.__file__) ...
import os import subprocess import pytest def test_list_subcommands_has_all_scripts(): """Tests if the output from running `fontbakery --list-subcommands` matches the fontbakery scripts within the bin folder.""" import fontbakery.commands commands_dir = os.path.dirname(fontbakery.commands.__file__) scri...
Add usage tests for check-ufo-sources and check-specification
Add usage tests for check-ufo-sources and check-specification
Python
apache-2.0
googlefonts/fontbakery,googlefonts/fontbakery,graphicore/fontbakery,graphicore/fontbakery,moyogo/fontbakery,graphicore/fontbakery,moyogo/fontbakery,moyogo/fontbakery,googlefonts/fontbakery
ab78faab8e3536c49f829ccbd71540a93485a7cb
website/jdevents/models.py
website/jdevents/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from mezzanine.core.models import Displayable, RichText class RepeatType(models.Model): DAILY = 'daily' WEEKLY = 'weekly', MONTHLY = 'monthly' REPEAT_CHOICES = ( (DAILY, _('Daily')), (WEEKLY, _('Weekl...
from django.db import models from django.utils.translation import ugettext_lazy as _ from mezzanine.core.models import Displayable, RichText class Event(Displayable, RichText): """ Main object for each event. Derives from Displayable, which by default - it is related to a certain Site ob...
Delete database support for repeated events.
Delete database support for repeated events. Events already support multiple occurences, and we will create an API to automatically add occurences in a repeating manner (every week, every month). Including event repeat data in database would make things a lot more complex.
Python
mit
jonge-democraten/website,jonge-democraten/website,jonge-democraten/website,jonge-democraten/website
f34a5d682832749dbf0011d162bf4c7c18892b45
zerver/apps.py
zerver/apps.py
import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations")...
import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations")...
Document the weird unused import for signal registration.
signals: Document the weird unused import for signal registration.
Python
apache-2.0
timabbott/zulip,tommyip/zulip,zulip/zulip,andersk/zulip,andersk/zulip,eeshangarg/zulip,kou/zulip,eeshangarg/zulip,eeshangarg/zulip,showell/zulip,brainwane/zulip,andersk/zulip,rishig/zulip,synicalsyntax/zulip,andersk/zulip,tommyip/zulip,hackerkid/zulip,kou/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,shubhamdhama/zu...
55e506489e93bad1d000acd747a272103e789a59
rml/element.py
rml/element.py
''' Representation of an element @param element_type: type of the element @param length: length of the element ''' import pkg_resources from rml.exceptions import ConfigException pkg_resources.require('cothread') from cothread.catools import caget class Element(object): def __init__(self, element_type, length, **...
''' Representation of an element @param element_type: type of the element @param length: length of the element ''' import pkg_resources from rml.exceptions import ConfigException pkg_resources.require('cothread') from cothread.catools import caget class Element(object): def __init__(self, element_type, length, **...
Add support for y field of a pv
Add support for y field of a pv
Python
apache-2.0
willrogers/pml,razvanvasile/RML,willrogers/pml
eab72cdb7e58b5398ace19c74569b1eb35ea91f8
toolbox/plugins/standard_object_features.py
toolbox/plugins/standard_object_features.py
from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["G...
from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["G...
Fix default region feature computation plugin
Fix default region feature computation plugin
Python
mit
chaubold/hytra,chaubold/hytra,chaubold/hytra
0b8075e8eb8fb52a9407bfa92d61e5a5363f8861
src/example/dump_camera_capabilities.py
src/example/dump_camera_capabilities.py
import pysony import fnmatch camera = pysony.SonyAPI() #camera = pysony.SonyAPI(QX_ADDR='http://192.168.122.1:8080/') mode = camera.getAvailableApiList() print "Available calls:" for x in (mode["result"]): for y in x: print y filtered = fnmatch.filter(x, "*Supported*") print "--" for x in filtered:...
import pysony import time import fnmatch print "Searching for camera" search = pysony.ControlPoint() cameras = search.discover() if len(cameras): camera = pysony.SonyAPI(QX_ADDR=cameras[0]) else: print "No camera found, aborting" quit() mode = camera.getAvailableApiList() # For those cameras which nee...
Add automatic searching capability. Note that camera may return different capabilities depending on its mode dial.
Add automatic searching capability. Note that camera may return different capabilities depending on its mode dial.
Python
mit
Bloodevil/sony_camera_api,mungewell/sony_camera_api,Bloodevil/sony_camera_api
3c3ceddf3c7d92e6e66017c0980102421e9bbe43
tests/test_integration.py
tests/test_integration.py
import os import types from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase)...
import os import types from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase)...
Use next to get the zone
Use next to get the zone
Python
mit
yola/pycloudflare,gnowxilef/pycloudflare
dbb15e4919c5d54d2e755cea700cc287bf164ad4
bom_data_parser/climate_data_online.py
bom_data_parser/climate_data_online.py
import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.convert_key(column)) df.co...
import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.convert_key(column)) df.co...
Handle just the zip file name when splitting
Handle just the zip file name when splitting This fixes a bug where the zip file name isn't correctly handled when splitting on the '.'. This causes a failure if passing a relative path (e.g '../'). Would also be a problem if directories had periods in their name.
Python
bsd-3-clause
amacd31/bom_data_parser,amacd31/bom_data_parser
e8030cfb3daee6b7e467f50a215fbffc5ef90223
api/preprint_providers/serializers.py
api/preprint_providers/serializers.py
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharFiel...
from rest_framework import serializers as ser from website.settings import API_DOMAIN from api.base.settings.defaults import API_BASE from api.base.serializers import JSONAPISerializer, LinksField class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'descri...
Add links field and related methods to link to a given provider's preprints from the preprint provider serializer
Add links field and related methods to link to a given provider's preprints from the preprint provider serializer
Python
apache-2.0
CenterForOpenScience/osf.io,icereval/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,adlius/osf.io,cwisecarver/osf.io,cslzchen/osf.io,erinspace/osf.io,mluo613/osf.io,mluo613/osf.io,mluo613/osf.io,caseyrollins/osf.io,rdhyee/osf.io,aaxelb/osf.io,monikagrabo...
9be04ea1030b423b7414dbd386ae2db2f4761f07
third_party/bunch/bunch/python3_compat.py
third_party/bunch/bunch/python3_compat.py
import platform _IS_PYTHON_3 = (platform.version() >= '3') identity = lambda x : x # u('string') replaces the forwards-incompatible u'string' if _IS_PYTHON_3: u = identity else: import codecs def u(string): return codecs.unicode_escape_decode(string)[0] # dict.iteritems(), dict.iterkeys() is als...
import sys _IS_PYTHON_3 = (sys.version[0] >= '3') identity = lambda x : x # u('string') replaces the forwards-incompatible u'string' if _IS_PYTHON_3: u = identity else: import codecs def u(string): return codecs.unicode_escape_decode(string)[0] # dict.iteritems(), dict.iterkeys() is also incompa...
Fix Python 3 version detection in bunch
Fix Python 3 version detection in bunch
Python
apache-2.0
mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher
dd171296a980dcc0349cf54b2afd6d2399cfb981
numba/tests/matmul_usecase.py
numba/tests/matmul_usecase.py
import sys try: import scipy.linalg.cython_blas has_blas = True except ImportError: has_blas = False import numba.unittest_support as unittest # The "@" operator only compiles on Python 3.5+. has_matmul = sys.version_info >= (3, 5) if has_matmul: code = """if 1: def matmul_usecase(x, y): ...
import sys try: import scipy.linalg.cython_blas has_blas = True except ImportError: has_blas = False import numba.unittest_support as unittest from numba.numpy_support import version as numpy_version # The "@" operator only compiles on Python 3.5+. # It is only supported by Numpy 1.10+. has_matmul = sys...
Fix test failure on Numpy 1.9 and Python 3.5
Fix test failure on Numpy 1.9 and Python 3.5 The "@" operator between arrays is only supported by Numpy 1.10+.
Python
bsd-2-clause
numba/numba,cpcloud/numba,stuartarchibald/numba,numba/numba,stefanseefeld/numba,gmarkall/numba,sklam/numba,stefanseefeld/numba,stefanseefeld/numba,jriehl/numba,IntelLabs/numba,seibert/numba,IntelLabs/numba,seibert/numba,stuartarchibald/numba,stonebig/numba,cpcloud/numba,sklam/numba,cpcloud/numba,stefanseefeld/numba,skl...
4e62f8292802aade03637dbbd05be56b9fad7d61
utils/snapshot_widgets.py
utils/snapshot_widgets.py
""" Alternative interact function that creates a single static figure that can be viewed online, e.g. on Github or nbviewer, or for use with nbconvert. """ from __future__ import print_function print("Will create static figures with single value of parameters") def interact(f, **kwargs): fargs = {} for key ...
""" Alternative interact function that creates a single static figure that can be viewed online, e.g. on Github or nbviewer, or for use with nbconvert. """ from __future__ import print_function print("Will create static figures with single value of parameters") def interact(f, **kwargs): fargs = {} for key ...
Use t=0.2 instead of t=0 for static widget output.
Use t=0.2 instead of t=0 for static widget output.
Python
bsd-3-clause
maojrs/riemann_book,maojrs/riemann_book,maojrs/riemann_book
6e5b13859b8a795b08189dde7ce1aab4cca18827
address/apps.py
address/apps.py
from django.apps import AppConfig class AddressConfig(AppConfig): """ Define config for the member app so that we can hook in signals. """ name = "address"
from django.apps import AppConfig class AddressConfig(AppConfig): """ Define config for the member app so that we can hook in signals. """ name = "address" default_auto_field = "django.db.models.AutoField"
Set default ID field to AutoField
:bug: Set default ID field to AutoField Resolves #168
Python
bsd-3-clause
furious-luke/django-address,furious-luke/django-address,furious-luke/django-address
2095b3f18926a9ab08faeae634f4f4653e4b7590
admin/manage.py
admin/manage.py
from freeposte import manager, db from freeposte.admin import models @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """...
from freeposte import manager, db from freeposte.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain...
Fix the admin creation command
Fix the admin creation command
Python
mit
kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io
87e5d0e5e92ed5f94e4238e73453934abc7835dd
src/tutorials/code/python/chat/5.py
src/tutorials/code/python/chat/5.py
from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop from functools import partial if __name__ == "__main__": chat = create(config) # Tell chat to authenticate with the beam server. It'll throw # a chatty.errors.NotAuthenticatedError if it fails. chat.authenticate(config.C...
from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop if __name__ == "__main__": chat = create(config) # Tell chat to authenticate with the beam server. It'll throw # a chatty.errors.NotAuthenticatedError if it fails. chat.authenticate(config.CHANNEL) # Han...
Replace partial with a function definition
Replace partial with a function definition Fix indentation, as well.
Python
mit
WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers
d3cc8fdbad2ca6888e33b119faae68d691ab291e
tests/system/test_lets-do-dns_script.py
tests/system/test_lets-do-dns_script.py
import os import subprocess from requests import get, delete def test_pre_authentication_hook(env): os.environ.update({ 'DO_API_KEY': env.key, 'DO_DOMAIN': env.domain, 'CERTBOT_DOMAIN': '%s.%s' % (env.hostname, env.domain), 'CERTBOT_VALIDATION': env.auth_token, }) record_i...
import os import subprocess from requests import get, delete, post def test_pre_authentication_hook(env): os.environ.update({ 'DO_API_KEY': env.key, 'DO_DOMAIN': env.domain, 'CERTBOT_DOMAIN': '%s.%s' % (env.hostname, env.domain), 'CERTBOT_VALIDATION': env.auth_token, }) re...
Test Post-Authentication Hook Process Works
Test Post-Authentication Hook Process Works This is my second system level test, and it's currently failing. My next steps are to work on the integration test, followed by a slew of unit tests to start testing driving the final design of the program to handle this second, and possibly final, piece.
Python
apache-2.0
Jitsusama/lets-do-dns
c96000a231d5bbf60a310e091b9895bfb249c115
conditional/blueprints/spring_evals.py
conditional/blueprints/spring_evals.py
from flask import Blueprint from flask import render_template from flask import request spring_evals_bp = Blueprint('spring_evals_bp', __name__) @spring_evals_bp.route('/spring_evals/') def display_spring_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ ...
from flask import Blueprint from flask import render_template from flask import request spring_evals_bp = Blueprint('spring_evals_bp', __name__) @spring_evals_bp.route('/spring_evals/') def display_spring_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ ...
FIx house meeting schema spring evals
FIx house meeting schema spring evals
Python
mit
ComputerScienceHouse/conditional,RamZallan/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional
d8cb207348a86b1bf9593f882a97eccdf48461df
lsv_compassion/model/invoice_line.py
lsv_compassion/model/invoice_line.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __open...
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __open...
Change child_name to related field.
Change child_name to related field.
Python
agpl-3.0
Secheron/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,MickSandoz/compassion-switzerland,ecino/compassion-switzerland,ndtran/compassion-switze...
f50f892e2ad2108342f53406ea86f65f89eeaafb
PythonScript/Helper/Helper.py
PythonScript/Helper/Helper.py
# This Python file uses the following encoding: utf-8 def main(): try: fileName = "MengZi_Traditional.md" filePath = "../../source/" + fileName content = None with open(filePath,'r') as file: content = file.read().decode("utf-8") content = content.replace(u"「",u'“...
# This Python file uses the following encoding: utf-8 def Convert(content): tradtionalToSimplified = { u"「":u"“", u"」":u"”", u"『":u"‘", u"』":u"’", } for key in tradtionalToSimplified: content = content.replace(key, tradtionalToSimplified[key]) return content ...
Use Convert() to simplify code
Use Convert() to simplify code
Python
mit
fan-jiang/Dujing
c2c488210b2c1ec3b1edfba1e510d228fa5e74d2
partner_communication_switzerland/migrations/12.0.1.1.2/post-migration.py
partner_communication_switzerland/migrations/12.0.1.1.2/post-migration.py
from openupgradelib import openupgrade def migrate(cr, installed_version): if not installed_version: return # Update data openupgrade.load_xml( cr, "partner_communication_switzerland", "data/onboarding_process.xml")
from openupgradelib import openupgrade def migrate(cr, installed_version): if not installed_version: return # Copy start_date over onboarding_start_date cr.execute(""" UPDATE recurring_contract SET onboarding_start_date = start_date WHERE is_first_sponsorship = true ""...
Include migration for current runnning onboarding processes
Include migration for current runnning onboarding processes
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland
049e21dd2d4e90120bfe297696cffa5000028854
dynd/benchmarks/benchmark_arithmetic.py
dynd/benchmarks/benchmark_arithmetic.py
import numpy as np from dynd import nd, ndt from benchrun import Benchmark, clock class ArithemticBenchmark(Benchmark): parameters = ('size',) size = [100000, 10000000] def run(self, size): a = nd.uniform(dst_tp = ndt.type('{} * float64'.format(size))) b = nd.uniform(dst_tp = ndt.type('{} * float64'.f...
import numpy as np from dynd import nd, ndt from benchrun import Benchmark, clock class ArithmeticBenchmark(Benchmark): parameters = ('size',) size = [100000, 10000000, 100000000] def run(self, size): a = nd.uniform(dst_tp = ndt.type('{} * float64'.format(size))) b = nd.uniform(dst_tp = ndt.type('{} *...
Add one bigger size to arithmetic benchmark
Add one bigger size to arithmetic benchmark
Python
bsd-2-clause
michaelpacer/dynd-python,insertinterestingnamehere/dynd-python,pombredanne/dynd-python,pombredanne/dynd-python,cpcloud/dynd-python,ContinuumIO/dynd-python,michaelpacer/dynd-python,izaid/dynd-python,michaelpacer/dynd-python,insertinterestingnamehere/dynd-python,izaid/dynd-python,mwiebe/dynd-python,izaid/dynd-python,mwie...
a34a34c1bf897b5681e7a421ea53ca5e9d065ab8
src/zeit/cms/tagging/testing.py
src/zeit/cms/tagging/testing.py
# Copyright (c) 2011 gocept gmbh & co. kg # See also LICENSE.txt import mock import zeit.cms.tagging.tag class TaggingHelper(object): """Mixin for tests which need some tagging infrastrucutre.""" def get_tag(self, code): tag = zeit.cms.tagging.tag.Tag(code, code) tag.disabled = False ...
# Copyright (c) 2011 gocept gmbh & co. kg # See also LICENSE.txt import mock import zeit.cms.tagging.tag class TaggingHelper(object): """Mixin for tests which need some tagging infrastrucutre.""" def get_tag(self, code): tag = zeit.cms.tagging.tag.Tag(code, code) return tag def setup_ta...
Remove superfluous variable ('disabled' is a concept of zeit.intrafind and doesn't belong here)
Remove superfluous variable ('disabled' is a concept of zeit.intrafind and doesn't belong here)
Python
bsd-3-clause
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
cf7086620df23d8af15f7c9898edf39f64965549
dbaas/workflow/steps/util/region_migration/check_instances_status.py
dbaas/workflow/steps/util/region_migration/check_instances_status.py
# -*- coding: utf-8 -*- import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0020 LOG = logging.getLogger(__name__) class DecreaseTTL(BaseStep): def __unicode__(self): return "Checking instances status..." def do(...
# -*- coding: utf-8 -*- import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0020 from drivers.base import ConnectionError LOG = logging.getLogger(__name__) class CheckInstancesStatus(BaseStep): def __unicode__(self): ...
Add step to check instances status
Add step to check instances status
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
c416c998d73e27713fd57ec97c70bacb2390f8c9
DashDoc.py
DashDoc.py
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax ...
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def camel_case(word): return ''.join(w.capitalize() if i > 0 else w for i, w in enume...
Use Dash's new CamelCase convention to lookup words that contain whitespace
Use Dash's new CamelCase convention to lookup words that contain whitespace - Example: converting "create table" into "createTable" will lookup "CREATE TABLE"
Python
apache-2.0
farcaller/DashDoc
0ce491e39b4cb866b2b749692dbaed8cb1cf6dac
plots/views.py
plots/views.py
# Create your views here. from django.template import RequestContext from django.shortcuts import render_to_response from django.utils import simplejson from django.http import HttpResponse, Http404 from .models import BenchmarkLogs, MachineInfo def rawdata(request, type): if type == "AvgVGRvsProcessor": def dr...
# Create your views here. from django.template import RequestContext from django.shortcuts import render_to_response from django.utils import simplejson from django.http import HttpResponse, Http404 from .models import BenchmarkLogs, MachineInfo def rawdata(request, type): #if type == "AvgVGRvsProcessor": ret...
Add a stub return to ensure the project builds.
Add a stub return to ensure the project builds.
Python
bsd-2-clause
ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark
02f77babc6195426fdb5c495d44ede6af6fbec8f
mangopaysdk/entities/userlegal.py
mangopaysdk/entities/userlegal.py
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonT...
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonT...
Add LegalRepresentativeProofOfIdentity to legal user
Add LegalRepresentativeProofOfIdentity to legal user
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
732fb749247c94fe0dbf3b98ca691d139970bc48
tests/doctests/test_doctests.py
tests/doctests/test_doctests.py
import os import doctest import unittest DOCTEST_FILES = [] for root, dirs, files in os.walk("."): if ".hg%s" % os.path.sep not in root: for f in files: if f.endswith(".doctest"): DOCTEST_FILES.append(f) DOCTEST_FILES = ["../../README.txt", "../../lib/restler/__init__.py"] + ...
import os import doctest import unittest DOCTEST_FILES = [] for root, dirs, files in os.walk("."): if ".hg%s" % os.path.sep not in root: for f in files: if f.endswith(".doctest"): DOCTEST_FILES.append(f) DOCTEST_FILES = ["../../lib/restler/__init__.py"] + DOCTEST_FILES print ...
Fix broken (doc) test looking for the removed README.txt
Fix broken (doc) test looking for the removed README.txt
Python
mit
xuru/substrate,xuru/substrate,xuru/substrate
c32118b2157e6c2cfd435461ee23edfa79aa917e
api/__init__.py
api/__init__.py
import ConfigParser from peewee import * config = ConfigParser.RawConfigParser() config.read('server.conf') database = SqliteDatabase('gallery.db') from collection import CollectionModel from album import AlbumModel from user import UserModel, UserResource from photo import PhotoModel database.create_tables([Photo...
import ConfigParser from peewee import * config = ConfigParser.RawConfigParser() config.read('server.conf') database = SqliteDatabase('gallery.db', threadlocals=True) from collection import CollectionModel from album import AlbumModel from user import UserModel, UsersResource from photo import PhotoModel database....
Set local threads to true for peewee
Set local threads to true for peewee
Python
unlicense
karousel/karousel
8c5f317a090a23f10adcc837645bd25a8b5626f8
shap/models/_model.py
shap/models/_model.py
import numpy as np from .._serializable import Serializable, Serializer, Deserializer class Model(Serializable): """ This is the superclass of all models. """ def __init__(self, model=None): """ Wrap a callable model as a SHAP Model object. """ if isinstance(model, Model): ...
import numpy as np from .._serializable import Serializable, Serializer, Deserializer from torch import Tensor class Model(Serializable): """ This is the superclass of all models. """ def __init__(self, model=None): """ Wrap a callable model as a SHAP Model object. """ if isinstan...
Check SHAP Model call type
Check SHAP Model call type
Python
mit
slundberg/shap,slundberg/shap,slundberg/shap,slundberg/shap
1ab4e03a0925deb57a7eafab2043d55f480988f1
misc/toml_to_json.py
misc/toml_to_json.py
#!/usr/bin/env python # Takes in toml, dumps it out as json # Run pip install toml to install the toml module import json import sys import toml fh = open(sys.argv[1]) try: data = toml.load(fh) except toml.TomlDecodeError, e: print e sys.exit(1) print json.dumps(data, indent=4, sort_keys=True)
#!/usr/bin/env python3 # Takes in toml, dumps it out as json # Run pip install toml to install the toml module import json import sys import toml if len(sys.argv) > 1: fh = open(sys.argv[1]) else: fh = sys.stdin try: data = toml.load(fh) except toml.TomlDecodeError as e: print(e) sys.exit(1) print...
Switch toml to json script to python 3
Switch toml to json script to python 3
Python
mit
mivok/tools,mivok/tools,mivok/tools,mivok/tools
9dbaf58fd3dc9c3c976afcbf264fa6cfff09a7a0
django_prometheus/migrations.py
django_prometheus/migrations.py
from django.db import connections from django.db.backends.dummy.base import DatabaseWrapper from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ...
from django.db import connections from django.db.backends.dummy.base import DatabaseWrapper from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django...
Fix the import of MigrationExecutor to be lazy.
Fix the import of MigrationExecutor to be lazy. MigrationExecutor checks at import time whether apps are all loaded. This doesn't work as they are usually not if your app is imported by adding it to INSTALLED_APPS. Importing the MigrationExecutor locally solves this problem as ExportMigration is only called once the d...
Python
apache-2.0
obytes/django-prometheus,korfuri/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus
746c06ba70cd2854a86ea8bc45fc8e3e6192f67c
app.py
app.py
# coding: utf-8 import os import time from twython import Twython import requests APP_KEY = os.environ.get('APP_KEY') APP_SECRET = os.environ.get('APP_SECRET') OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN') OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OA...
# coding: utf-8 import os import time from twython import Twython import requests APP_KEY = os.environ.get('APP_KEY') APP_SECRET = os.environ.get('APP_SECRET') OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN') OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OA...
Add hashtag for currency name and symbol
Add hashtag for currency name and symbol
Python
mit
erickgnavar/coinstats
07c40f2c47c81843c8fd183f8fad7e489fb2d814
sirius/LI_V00/record_names.py
sirius/LI_V00/record_names.py
from . import families as _families def get_record_names(subsystem=None): """Return a dictionary of record names for given subsystem each entry is another dictionary of model families whose values are the indices in the pyaccel model of the magnets that belong to the family. The magnet models ca be s...
from . import families as _families def get_record_names(subsystem=None): """Return a dictionary of record names for given subsystem each entry is another dictionary of model families whose values are the indices in the pyaccel model of the magnets that belong to the family. The magnet models ca be s...
Change linac mode pv to fake pvs
Change linac mode pv to fake pvs
Python
mit
lnls-fac/sirius
26c725d3e6b1d5737a0efcbcd2371ff066a13a86
tests/test_utils.py
tests/test_utils.py
from expert_tourist.utils import gmaps_url_to_coords from tests.tests import BaseTestConfig class TestUtils(BaseTestConfig): def test_url_to_coords(self): url = 'http://maps.google.co.cr/maps?q=9.8757875656828,-84.03733452782035' lat, long = gmaps_url_to_coords(url) self.assertEqual(lat, 9...
from unittest import TestCase from expert_tourist.utils import gmaps_url_to_coords class TestUtils(TestCase): def test_url_to_coords(self): url = 'http://maps.google.co.cr/maps?q=9.8757875656828,-84.03733452782035' lat, long = gmaps_url_to_coords(url) self.assertEqual(lat, 9.875787565682...
Refactor test to implement 87ceac3 changes
Refactor test to implement 87ceac3 changes
Python
mit
richin13/expert-tourist
b2aba5cbdfbe59fee7bc595298a732c9aa1f9b51
tests/test_utils.py
tests/test_utils.py
"""Tests for the ``utils`` module.""" from mock import patch, Mock as mock from nose.tools import * from facepy import * patch = patch('requests.session') def mock(): global mock_request mock_request = patch.start()().request def unmock(): patch.stop() @with_setup(mock, unmock) def test_get_applicati...
"""Tests for the ``utils`` module.""" from mock import patch, Mock as mock from nose.tools import * from facepy import * patch = patch('requests.session') def mock(): global mock_request mock_request = patch.start()().request def unmock(): patch.stop() @with_setup(mock, unmock) def test_get_applicati...
Make test_get_application_access_token_raises_error compatible with Python < 2.7
Make test_get_application_access_token_raises_error compatible with Python < 2.7
Python
mit
merwok-forks/facepy,jwjohns/facepy,jgorset/facepy,Spockuto/facepy,liorshahverdi/facepy,jwjohns/facepy,buzzfeed/facepy
34e2cf61bf686542f21bc8d840f17b13ca137fe3
Main.py
Main.py
"""Main Module of PDF Splitter""" import argparse from PyPDF2 import PdfFileWriter from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages parser = \ argparse.ArgumentParser( description='Split all the pages of multiple PDF files in a directory by document number' ) parser.a...
"""Main Module of PDF Splitter""" import argparse import os from PyPDF2 import PdfFileWriter from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages parser = \ argparse.ArgumentParser( description='Split all the pages of multiple PDF files in a directory by document number' ...
Use flush and fsync to ensure data is written to disk
Use flush and fsync to ensure data is written to disk
Python
mit
shunghsiyu/pdf-processor
727f1de69a3f2211d97a2c5ed412eacb90d11619
cov/templatetags/cov_tag.py
cov/templatetags/cov_tag.py
from django import template from ..models import Covoiturage from django.utils import timezone register = template.Library() @register.inclusion_tag('cov/cov_block.html', takes_context=True) def get_cov(context, nb): list_cov = Covoiturage.objects.select_related('poster').all().filter(good_until__gte=timezone.now())...
from django import template from ..models import Covoiturage from django.utils import timezone register = template.Library() @register.inclusion_tag('cov/cov_block.html', takes_context=True) def get_cov(context, nb): return { 'cov' : Covoiturage.objects.select_related('poster').filter( good_until...
Fix : cov list is fetch in one queries (before it was fetched twice)
Fix : cov list is fetch in one queries (before it was fetched twice)
Python
agpl-3.0
rezometz/paiji2,rezometz/paiji2,rezometz/paiji2
c1dfbc8e8b3ae29436c584d906636ea541dfb6a8
apps/storybase_asset/embedable_resource/__init__.py
apps/storybase_asset/embedable_resource/__init__.py
import re from exceptions import UrlNotMatched class EmbedableResource(object): resource_providers = [] @classmethod def register(cls, provider_cls): cls.resource_providers.append(provider_cls) @classmethod def get_html(cls, url): for provider_cls in cls.resource_providers: ...
import re from exceptions import UrlNotMatched class EmbedableResource(object): resource_providers = [] @classmethod def register(cls, provider_cls): cls.resource_providers.append(provider_cls) @classmethod def get_html(cls, url): for provider_cls in cls.resource_providers: ...
Allow embedding of Google Docs by URL
Allow embedding of Google Docs by URL
Python
mit
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
8f7623c4b09d85c09327c37030fa2328e77853b1
qfbv.py
qfbv.py
from config import * class QFBV: def preamble(self): print "(set-logic QF_BV)" print "" # Enumerate all the variables, for each match round. for i in range(NUMROUNDS): for j in range(NUMMATCHES): for k in range(NUMSLOTS): print "(declare-fun {0} () (_ BitVec {1}))".format(self.project(i, j, k), ...
from config import * import re class QFBV: def preamble(self): print "(set-logic QF_BV)" print "" # Enumerate all the variables, for each match round. for i in range(NUMROUNDS): for j in range(NUMMATCHES): for k in range(NUMSLOTS): print "(declare-fun {0} () (_ BitVec {1}))".format(self.project(...
Read variable data for qf_bv
Read variable data for qf_bv
Python
bsd-2-clause
jmorse/numbness
626c74d727140646d6123e2d86a828401d87abe0
spam.py
spam.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from sklearn.cross_validation import train_test_split from spam.common import DATASET_META from spam.common.utils import get_file_path_list from spam.preprocess import Preprocess file_path_list = get_file_path_list(DATASET_META) # transform list of tuple into two list ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd from sklearn.cross_validation import train_test_split from spam.common import DATASET_META from spam.common.utils import get_file_path_list from spam.preprocess import preprocess file_path_list = get_file_path_list(DATASET_META) # transform list of ...
Add pandas to generate csv.
Add pandas to generate csv.
Python
mit
benigls/spam,benigls/spam
987eb13b24fcb6b89b9bbe08a9bc73f40b85538c
onirim/card/_door.py
onirim/card/_door.py
from onirim.card._base import ColorCard from onirim.card._location import LocationKind def _openable(door_card, card): """Check if the door can be opened by another card.""" return card.kind == LocationKind.key and door_card.color == card.color def _may_open(door_card, content): """Check if the door may ...
from onirim.card._base import ColorCard from onirim.card._location import LocationKind def _is_openable(door_card, card): """Check if the door can be opened by another card.""" return card.kind == LocationKind.key and door_card.color == card.color def _may_open(door_card, content): """Check if the door ...
Remove key while opening a door
Remove key while opening a door
Python
mit
cwahbong/onirim-py
d7343ac93dbfb62b3f425711b8df9929a1d6f1ad
malcolm/core/mapmeta.py
malcolm/core/mapmeta.py
from collections import OrderedDict from loggable import Loggable from malcolm.core.attributemeta import AttributeMeta class MapMeta(Loggable): """A meta object to store a set of attribute metas""" def __init__(self, name): super(MapMeta, self).__init__(logger_name=name) self.name = name ...
from collections import OrderedDict from loggable import Loggable from malcolm.core.attributemeta import AttributeMeta class MapMeta(Loggable): """An object containing a set of AttributeMeta objects""" def __init__(self, name): super(MapMeta, self).__init__(logger_name=name) self.name = nam...
Remove uneccesary dict definition, clarify doc string
Remove uneccesary dict definition, clarify doc string
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
6ac0598982f90b23d772d6b3cba802ad5fad5459
watchman/management/commands/watchman.py
watchman/management/commands/watchman.py
from __future__ import absolute_import import json from optparse import make_option from django.core.management.base import BaseCommand, CommandError from watchman.utils import get_checks class Command(BaseCommand): help = 'Runs the default django-watchman checks' option_list = BaseCommand.option_list + (...
from __future__ import absolute_import import json from optparse import make_option from django.core.management.base import BaseCommand, CommandError from watchman.utils import get_checks class Command(BaseCommand): help = 'Runs the default django-watchman checks' option_list = BaseCommand.option_list + (...
Use `self.stdout.write` instead of `print`
Use `self.stdout.write` instead of `print`
Python
bsd-3-clause
JBKahn/django-watchman,blag/django-watchman,mwarkentin/django-watchman,blag/django-watchman,JBKahn/django-watchman,ulope/django-watchman,mwarkentin/django-watchman,gerlachry/django-watchman,gerlachry/django-watchman,ulope/django-watchman
5d5bbcd380300c5fd786fac59bf360a287b99c3b
oauthenticator/__init__.py
oauthenticator/__init__.py
# include github, bitbucket, google here for backward-compatibility # don't add new oauthenticators here. from .oauth2 import * from .github import * from .bitbucket import * from .google import * from ._version import __version__, version_info
# include github, bitbucket, google here for backward-compatibility # don't add new oauthenticators here. from .oauth2 import * from .github import * from .bitbucket import * from .google import * from .generic import * from ._version import __version__, version_info
Add the GenericHandler to the init file
Add the GenericHandler to the init file
Python
bsd-3-clause
santi81/oauthenticator,santi81/oauthenticator
05cf5f3729ffbceeb2436322b2aac5285d7228de
wsgi.py
wsgi.py
# Copyright 2017 Jonathan Anderson # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # ...
# Copyright 2017 Jonathan Anderson # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # ...
Print registration code in WSGI app.
Print registration code in WSGI app. Otherwise, how will we know what it is?
Python
bsd-2-clause
trombonehero/nerf-herder,trombonehero/nerf-herder,trombonehero/nerf-herder
beb06f3377a5e3e52f5756a1ecbf4197c7a3e99e
base/components/correlations/managers.py
base/components/correlations/managers.py
# -*- coding: utf-8 -*- from datetime import date from django.contrib.contenttypes.models import ContentType from django.db import models class CorrelationManager(models.Manager): def update_or_create(self, instance, timestamp, attribute): # Membership is a special case. Since most groups are static ...
# -*- coding: utf-8 -*- from datetime import date from django.contrib.contenttypes.models import ContentType from django.db import models class CorrelationManager(models.Manager): def update_or_create(self, instance, timestamp, attribute): ctype = ContentType.objects.get_for_model(instance.sender) ...
Remove the Membership special case. We want everything correlated.
Remove the Membership special case. We want everything correlated.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
1025121c19af4d1ea224abc8f37120cb9f24210d
Scripts/RoboFabUFO/ImportFontFromUFO.py
Scripts/RoboFabUFO/ImportFontFromUFO.py
#FLM: Import .ufo File into FontLab from robofab.world import NewFont from robofab.interface.all.dialogs import GetFolder path = GetFolder("Please select a .ufo") if path is not None: font = NewFont() font.readUFO(path, doProgress=True) font.update() print 'DONE!'
#FLM: Import .ufo File into FontLab from robofab.world import NewFont from robofab.interface.all.dialogs import GetFileOrFolder path = GetFileOrFolder("Please select a .ufo") if path is not None: font = NewFont() font.readUFO(path, doProgress=True) font.update() print 'DONE!'
Use GetFileOrFolder for the dialog.
Use GetFileOrFolder for the dialog. git-svn-id: 68c5a305180a392494b23cb56ff711ec9d5bf0e2@493 b5fa9d6c-a76f-4ffd-b3cb-f825fc41095c
Python
bsd-3-clause
jamesgk/robofab,daltonmaag/robofab,bitforks/robofab,schriftgestalt/robofab,moyogo/robofab,schriftgestalt/robofab,miguelsousa/robofab,anthrotype/robofab,daltonmaag/robofab,anthrotype/robofab,jamesgk/robofab,miguelsousa/robofab,moyogo/robofab
4a5e6373692798eb4d48c294d3262c93902b27de
zou/app/blueprints/crud/schedule_item.py
zou/app/blueprints/crud/schedule_item.py
from zou.app.models.schedule_item import ScheduleItem from .base import BaseModelResource, BaseModelsResource class ScheduleItemsResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, ScheduleItem) class ScheduleItemResource(BaseModelResource): def __init__(self): ...
from zou.app.models.schedule_item import ScheduleItem from .base import BaseModelResource, BaseModelsResource from zou.app.services import user_service class ScheduleItemsResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, ScheduleItem) class ScheduleItemResource(BaseMo...
Allow schedule edition by supervisors
[schedule] Allow schedule edition by supervisors
Python
agpl-3.0
cgwire/zou
fb5bc5d789986df53844d8f0620db95f349e4096
sch/__init__.py
sch/__init__.py
import os if hasattr(os, 'add_dll_directory'): os.add_dll_directory("$<TARGET_FILE_DIR:sch-core::sch-core>") from . sch import *
import os if hasattr(os, 'add_dll_directory'): os.add_dll_directory("$<TARGET_FILE_DIR:sch-core::sch-core>") os.add_dll_directory("$<TARGET_FILE_DIR:Boost::serialization>") from . sch import *
Add the Boost DLL directory to the search path as well
Add the Boost DLL directory to the search path as well
Python
bsd-2-clause
jrl-umi3218/sch-core-python,jrl-umi3218/sch-core-python
a2d6c32305577640bcd111fa1011bea61d7ca9e7
packages/mono-llvm-2-10.py
packages/mono-llvm-2-10.py
GitHubTarballPackage ('mono', 'llvm', '2.10', '943edbc1a93df204d687d82d34d2b2bdf9978f4e', configure = 'CFLAGS="-m32" CPPFLAGS="-m32" CXXFLAGS="-m32" LDFLAGS="-m32" ./configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0', override_properties = { 'make': 'make...
GitHubTarballPackage ('mono', 'llvm', '2.10', '943edbc1a93df204d687d82d34d2b2bdf9978f4e', configure = './configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0', override_properties = { 'make': 'make' } )
Fix llvm so it doesn't corrupt the env when configuring itself
Fix llvm so it doesn't corrupt the env when configuring itself
Python
mit
BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild
6910fe840a2b54d7848adcaa032d4303aee0ceec
dedupe/convenience.py
dedupe/convenience.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPair...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPair...
Index of the list should be an int
Index of the list should be an int
Python
mit
nmiranda/dedupe,davidkunio/dedupe,tfmorris/dedupe,datamade/dedupe,nmiranda/dedupe,01-/dedupe,pombredanne/dedupe,davidkunio/dedupe,dedupeio/dedupe,neozhangthe1/dedupe,neozhangthe1/dedupe,01-/dedupe,datamade/dedupe,pombredanne/dedupe,dedupeio/dedupe,dedupeio/dedupe-examples,tfmorris/dedupe
1d3bd1fe50806180c8fb6889b1bed28f602608d6
couchdb/tests/__main__.py
couchdb/tests/__main__.py
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import unittest from couchdb.tests import client, couch_tests, design, couchhttp, \ ...
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import unittest from couchdb.tests import client, couch_tests, design, couchhttp, \ ...
Include loader tests in test suite
Include loader tests in test suite
Python
bsd-3-clause
djc/couchdb-python,djc/couchdb-python
bf18c698596be9de094d94cdc52d95186fc37e6a
configReader.py
configReader.py
class ConfigReader(): def __init__(self): self.keys={} #Read Keys from file def readKeys(self): keysFile=open("config.txt","r") fileLines=keysFile.readlines() keysFile.close() self.keys.clear() for item in fileLines: #If last char is \n if (item[-1]=='\n'): item=item[:-1] #If a commented ...
class ConfigReader(): def __init__(self,name="config.txt"): self.keys={} self.name = name #Read Keys from file def readKeys(self): keysFile=open(self.name,"r") fileLines=keysFile.readlines() keysFile.close() self.keys.clear() for item in fileLines: #If last char is \n if (item[-1]=='\n'): ite...
Add mode for changing what file it is, and fix a bug where a line without an equals wouldn't work
Add mode for changing what file it is, and fix a bug where a line without an equals wouldn't work
Python
mit
ollien/PyConfigReader
4e30a58386afb5b34bd83c8115c55e5d09b8f631
common/views.py
common/views.py
from django.shortcuts import render from common.models.Furniture import Furniture from common.models.Plan import Plan def overlay(request, floor=1): edit_rooms = False if request.method == 'POST': if 'floor' in request.POST: floor = request.POST['floor'] if 'edit_rooms' in request....
from django.shortcuts import render from common.models.Furniture import Furniture from common.models.Plan import Plan def overlay(request, floor=1): edit_rooms = False if request.method == 'POST': if 'floor' in request.POST: floor = request.POST['floor'] if 'edit_rooms' in request....
Improve performance by prefetching where needed
Improve performance by prefetching where needed
Python
agpl-3.0
Pajn/RAXA-Django,Pajn/RAXA-Django
e7cbed6df650851b2d44bf48f2b94291822f0b91
recipes/sos-notebook/run_test.py
recipes/sos-notebook/run_test.py
# Test that sos kernel is installed import jupyter_client try: jupyter_client.kernelspec.get_kernel_spec('sos') except jupyter_client.kernelspec.NoSuchKernel: print('sos kernel was not installed') print('The following kernels are installed:') print('jupyter_client.kernelspec.find_kernel_specs()') ...
# Test that sos kernel is installed import jupyter_client try: jupyter_client.kernelspec.get_kernel_spec('sos') except jupyter_client.kernelspec.NoSuchKernel: print('sos kernel was not installed') print('The following kernels are installed:') print('jupyter_client.kernelspec.find_kernel_specs()') ...
Add test of kernel switch.
Add test of kernel switch.
Python
bsd-3-clause
kwilcox/staged-recipes,scopatz/staged-recipes,patricksnape/staged-recipes,asmeurer/staged-recipes,mcs07/staged-recipes,patricksnape/staged-recipes,birdsarah/staged-recipes,mcs07/staged-recipes,hadim/staged-recipes,basnijholt/staged-recipes,goanpeca/staged-recipes,synapticarbors/staged-recipes,kwilcox/staged-recipes,asm...
d101b7f023db1583ca7b65899bfdef296f838ad2
openspending/ui/validation/source.py
openspending/ui/validation/source.py
from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', 'h...
from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', '...
Fix PEP8 issues in openspending/ui/validation.
Fix PEP8 issues in openspending/ui/validation.
Python
agpl-3.0
CivicVision/datahub,openspending/spendb,CivicVision/datahub,spendb/spendb,spendb/spendb,johnjohndoe/spendb,USStateDept/FPA_Core,nathanhilbert/FPA_Core,openspending/spendb,spendb/spendb,USStateDept/FPA_Core,USStateDept/FPA_Core,johnjohndoe/spendb,openspending/spendb,nathanhilbert/FPA_Core,johnjohndoe/spendb,pudo/spendb,...
23fc2bbd22aa8d45301207b0608634df4414707f
panoptes_client/classification.py
panoptes_client/classification.py
from panoptes_client.panoptes import LinkResolver, PanoptesObject class Classification(PanoptesObject): _api_slug = 'classifications' _link_slug = 'classification' _edit_attributes = ( ) LinkResolver.register(Classification)
from panoptes_client.panoptes import LinkResolver, PanoptesObject class Classification(PanoptesObject): _api_slug = 'classifications' _link_slug = 'classification' _edit_attributes = ( ) @classmethod def where(cls, **kwargs): scope = kwargs.pop('scope', None) if not scope: ...
Add scope kwarg to Classification.where()
Add scope kwarg to Classification.where()
Python
apache-2.0
zooniverse/panoptes-python-client
24b52024b76206b59a650cee477773ad5836b175
labonneboite/importer/conf/lbbdev.py
labonneboite/importer/conf/lbbdev.py
import os # --- importer input directory of DPAE and ETABLISSEMENT exports INPUT_SOURCE_FOLDER = '/srv/lbb/data' # --- job 1/8 & 2/8 : check_etablissements & extract_etablissements JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins") MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPART...
import os # --- importer input directory of DPAE and ETABLISSEMENT exports INPUT_SOURCE_FOLDER = '/srv/lbb/data' # --- job 1/8 & 2/8 : check_etablissements & extract_etablissements JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins") MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPART...
Fix evolution threshold for dpt 77
Fix evolution threshold for dpt 77 The threshold HIGH_SCORE_COMPANIES_DIFF_MAX which is the max percentage of difference between number of companies in lbb from one importer cycle to another was set to 70, and it reached 73 for the department 77. This threshold has now been set to 75.
Python
agpl-3.0
StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite
b9882cc9d12aef06091727c76263039b30f0c4ce
numscons/tools/ifort.py
numscons/tools/ifort.py
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) def generate(env): if sys.platform.star...
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate from numscons.tools.intel_common import get_abi def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(...
Add initial support for win32 fortran compiler support.
Add initial support for win32 fortran compiler support.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
fffbf30ab4f64cbfad939529dde416280a68b125
addons/osfstorage/settings/defaults.py
addons/osfstorage/settings/defaults.py
# encoding: utf-8 import importlib import os import logging from website import settings logger = logging.getLogger(__name__) DEFAULT_REGION_NAME = 'N. Virginia' DEFAULT_REGION_ID = 'us-east-1' WATERBUTLER_CREDENTIALS = { 'storage': {} } WATERBUTLER_SETTINGS = { 'storage': { 'provider': 'filesystem...
# encoding: utf-8 import importlib import os import logging from website import settings logger = logging.getLogger(__name__) DEFAULT_REGION_NAME = 'United States' DEFAULT_REGION_ID = 'us' WATERBUTLER_CREDENTIALS = { 'storage': {} } WATERBUTLER_SETTINGS = { 'storage': { 'provider': 'filesystem', ...
Adjust OSF Storage default region names
Adjust OSF Storage default region names
Python
apache-2.0
pattisdr/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,adlius/osf.io,aaxelb/osf.io,saradbowman/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,felliott/osf.io,saradbowman/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,erinspace/osf.io,adlius/osf.io,baylee-d/...
721c4d0cd4e99b4c45eeee813375e7d0050ef970
doc/pyplots/plot_qualitative2.py
doc/pyplots/plot_qualitative2.py
# -*- coding: utf-8 -*- """Plot to demonstrate the qualitative2 colormap. """ import numpy as np import matplotlib.pyplot as plt from typhon.plots import (figsize, mpl_colors) fig, ax = plt.subplots(figsize=figsize(10)) ax.set_prop_cycle(color=mpl_colors('qualitative2', 7)) for c in np.arange(7): X = np.random...
# -*- coding: utf-8 -*- """Plot to demonstrate the qualitative2 colormap. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D from typhon.plots import (figsize, mpl_colors) # Create an iterator to conveniently change the marker in the following plot. markers = (m for m in Lin...
Change marker as an example.
Change marker as an example.
Python
mit
atmtools/typhon,atmtools/typhon
197aa546b2043602a622340bdec220bdc67e13dd
prince/plot/mpl/util.py
prince/plot/mpl/util.py
import matplotlib.cm as cm import matplotlib.colors as clr import matplotlib.pyplot as plt from ..palettes import SEABORN def create_discrete_cmap(n): """Create an n-bin discrete colormap.""" if n <= len(SEABORN): colors = list(SEABORN.values())[:n] else: base = plt.cm.get_cmap('Paired') ...
import matplotlib.cm as cm import matplotlib.colors as clr import matplotlib.pyplot as plt from ..palettes import SEABORN def create_discrete_cmap(n): """Create an n-bin discrete colormap.""" if n <= len(SEABORN): colors = list(SEABORN.values())[:n] else: base = plt.cm.get_cmap('Paired') ...
Fix AttributeError on ListedColormap from_list method
Fix AttributeError on ListedColormap from_list method
Python
mit
MaxHalford/Prince
c4b7532987958573dafe01621cdd254db63bf8ea
bfg9000/builtins/hooks.py
bfg9000/builtins/hooks.py
import functools from six import iteritems _all_builtins = {} class _Binder(object): def __init__(self, args, fn): self._args = args self._fn = fn class _FunctionBinder(_Binder): def bind(self, **kwargs): # XXX: partial doesn't forward the docstring of the function. return f...
import functools import inspect import sys from six import iteritems _all_builtins = {} class _Binder(object): def __init__(self, args, fn): self._args = args self._fn = fn class _FunctionBinder(_Binder): def bind(self, **kwargs): pre_args = tuple(kwargs[i] for i in self._args) ...
Change how the wrappers work for builtin functions so that docs get forwarded correctly
Change how the wrappers work for builtin functions so that docs get forwarded correctly
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
b3b281c9bf789c44a9a2b2d750e4dd8cf789dd1a
playserver/webserver.py
playserver/webserver.py
import flask from . import track app = flask.Flask(__name__) @app.route("/") def root(): return "{} by {} - {}"
import flask from . import track app = flask.Flask(__name__) @app.route("/") def root(): song = track.getCurrentSong() artist = track.getCurrentArtist() album = track.getCurrentAlbum() return "{} by {} - {}".format(song, artist, album)
Add song display to root page
Add song display to root page
Python
mit
ollien/playserver,ollien/playserver,ollien/playserver
6ccc85832aeff2ca9800cd9e2af8461515ff680d
cartography/midi_utils.py
cartography/midi_utils.py
import mido def open_output(): return open_steinberg_output() def get_steinberg_device_name(): output_names = [n for n in mido.get_output_names() if 'steinberg' in n.lower()] if len(output_names) != 1: raise Exception(f"Found the following steinberg MIDI devices: {output_names}. Expected only on...
import mido def open_output(): return open_steinberg_output() def get_steinberg_device_name(): output_names = [n for n in mido.get_output_names() if 'steinberg' in n.lower()] if len(output_names) != 1: raise Exception(f"Found the following steinberg MIDI devices: {output_names}. Expected only on...
Add dump presets and utils
Add dump presets and utils
Python
mit
tingled/synthetic-cartography,tingled/synthetic-cartography
883b8d3ebdf006bb6c9b28b234936231f0eac442
l10n_br_nfse/__manifest__.py
l10n_br_nfse/__manifest__.py
# Copyright 2019 KMEE INFORMATICA LTDA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "NFS-e", "summary": """ NFS-e""", "version": "14.0.1.7.0", "license": "AGPL-3", "author": "KMEE, Odoo Community Association (OCA)", "maintainers": ["gabrielcardoso21", "mileo...
# Copyright 2019 KMEE INFORMATICA LTDA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "NFS-e", "summary": """ NFS-e""", "version": "14.0.1.7.0", "license": "AGPL-3", "author": "KMEE, Odoo Community Association (OCA)", "maintainers": ["gabrielcardoso21", "mileo...
Update python lib erpbrasil.assinatura version 1.4.0
l10n_br_nfse: Update python lib erpbrasil.assinatura version 1.4.0
Python
agpl-3.0
akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil
0eabc95105fecfd4b960b1c135f589f0eea9de2a
flaskrst/modules/staticpages/__init__.py
flaskrst/modules/staticpages/__init__.py
# -*- coding: utf-8 -*- """ flask-rst.modules.staticfiles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ import os from flask import current_app, render_template from flaskrst.parsers import rstDocument from flaskrst.modules impo...
# -*- coding: utf-8 -*- """ flask-rst.modules.staticfiles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ import os from flask import current_app, render_template from flaskrst.parsers import rstDocument from flaskrst.modules impo...
Support of static pages inside of a directory
Support of static pages inside of a directory
Python
bsd-3-clause
jarus/flask-rst
46328b5baaf25b04703ca04fd376f3f79a26a00f
sockjs/cyclone/proto.py
sockjs/cyclone/proto.py
import simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """R...
try: import simplejson except ImportError: import json as simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Vari...
Use the json module from stdlib (Python 2.6+) as fallback
Use the json module from stdlib (Python 2.6+) as fallback
Python
mit
flaviogrossi/sockjs-cyclone
196b5aabe2bcee8677c34481f19099f65699a44e
billjobs/tests/tests_user_admin_api.py
billjobs/tests/tests_user_admin_api.py
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ ...
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST ...
Add test admin to retrieve a user detail
Add test admin to retrieve a user detail
Python
mit
ioO/billjobs
f34afd52aa1b89163d90a21feac7bd9e3425639d
gapipy/resources/booking/agency_chain.py
gapipy/resources/booking/agency_chain.py
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.base import Resource from gapipy.resources.booking_company import BookingCompany class AgencyChain(Resource): _resource_name = 'agency_chains' _as_is_fields = [ 'id', 'href', 'name', 'agencies', ...
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.base import Resource from gapipy.resources.booking_company import BookingCompany class AgencyChain(Resource): _resource_name = 'agency_chains' _is_parent_resource = True _as_is_fields = [ 'id', 'href', ...
Make `AgencyChain.agencies` a "resource collection" field
Make `AgencyChain.agencies` a "resource collection" field We can now get a `Query` when accessing the `agencies` attribute on an `AgencyChain` instead of a dict with an URI to the agencies list.
Python
mit
gadventures/gapipy
a42d238fcc33a18cd90267864f0d308e27319ec5
rbtools/utils/checks.py
rbtools/utils/checks.py
import os import subprocess import sys from rbtools.utils.process import die, execute GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm' def check_install(command): """ Try executing an external command and return a boolean indicating whether that command is installed or not....
import os import subprocess import sys from rbtools.utils.process import die, execute GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm' def check_install(command): """ Try executing an external command and return a boolean indicating whether that command is installed or not....
Fix the GNU diff error to not mention Subversion.
Fix the GNU diff error to not mention Subversion. The GNU diff error was specifically saying Subversion was required, which didn't make sense when other SCMClients triggered the check. Instead, make the error more generic.
Python
mit
davidt/rbtools,datjwu/rbtools,halvorlu/rbtools,datjwu/rbtools,davidt/rbtools,bcelary/rbtools,clach04/rbtools,halvorlu/rbtools,datjwu/rbtools,reviewboard/rbtools,reviewboard/rbtools,haosdent/rbtools,beol/rbtools,1tush/rbtools,beol/rbtools,Khan/rbtools,haosdent/rbtools,reviewboard/rbtools,beol/rbtools,haosdent/rbtools,ha...
408ccc648d48725271db36a83c71aed1f03ff8c7
gntp/test/__init__.py
gntp/test/__init__.py
import unittest from gntp.config import GrowlNotifier class GNTPTestCase(unittest.TestCase): def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register() self.notification = { 'noteType': 'Testing', 'title': 'Unittest Title', 'description': 'Unittest Description', ...
import unittest from gntp.config import GrowlNotifier class GNTPTestCase(unittest.TestCase): notification = { 'noteType': 'Testing', 'title': 'Unittest Title', 'description': 'Unittest Description', } def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register() def _...
Move variables to class variables so that we have to duplicate less for child classes
Move variables to class variables so that we have to duplicate less for child classes
Python
mit
kfdm/gntp
b5240580e1786185bc6a889b0106d404cddc78e0
AnnotationToXMLConverter/AnnotationToXMLConverter.py
AnnotationToXMLConverter/AnnotationToXMLConverter.py
import os from TextFileReader import * def main(): # get the base directory base_directory = os.getcwd() # counter for percentage print stage_counter = 0 total_stage = len(os.listdir(base_directory + "/Annotation")) for filename in os.listdir(base_directory + "/Annotation"): # print t...
import os import time from TextFileReader import * def main(): # get the base directory base_directory = os.getcwd() # counter for percentage print stage_counter = 0 total_stage = len(os.listdir(base_directory + "/Annotation")) start_time = time.time() for filename in os.listdir(base_dir...
Add display for running states
Add display for running states
Python
mit
Jamjomjara/snu-artoon,Jamjomjara/snu-artoon
493314bb1d8778c10033f7011cd865526c34b6ce
boardinghouse/contrib/template/apps.py
boardinghouse/contrib/template/apps.py
from django.apps import AppConfig from django.db import models from django.dispatch import receiver from boardinghouse.schema import activate_schema class BoardingHouseTemplateConfig(AppConfig): name = 'boardinghouse.contrib.template' def ready(self): from boardinghouse import signals from ....
from django.apps import AppConfig from django.db import models from django.dispatch import receiver from boardinghouse.schema import activate_schema class BoardingHouseTemplateConfig(AppConfig): name = 'boardinghouse.contrib.template' def ready(self): from boardinghouse import signals from ....
Debug version to check codeship.
Debug version to check codeship. --HG-- branch : schema-templates/fix-codeship-issue
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
43a7f6a2130f57bd1e94aa418c4b7d6e085c09ea
tests/test_api_info.py
tests/test_api_info.py
from tests import string def test_get(test): def handle_connect(handler): info = handler.api.get_info() assert isinstance(info['api_version'], string) assert isinstance(info['server_timestamp'], string) if info.get('rest_server_url'): assert info['websocket_server_url'...
from tests import string def test_get(test): def handle_connect(handler): info = handler.api.get_info() assert isinstance(info['api_version'], string) assert isinstance(info['server_timestamp'], string) if info.get('rest_server_url'): assert info['websocket_server_url'...
Remove skip of test_get_cluster function for websocket transport
Remove skip of test_get_cluster function for websocket transport
Python
apache-2.0
devicehive/devicehive-python
8e623faa44ad767baf4c92596a2501f98dfd2bbb
src/masterfile/validators/__init__.py
src/masterfile/validators/__init__.py
from __future__ import absolute_import from . import io_validator from . import index_column_validator
from __future__ import absolute_import from . import ( # noqa io_validator, index_column_validator )
Clean up validator package imports
Clean up validator package imports
Python
mit
njvack/masterfile
6cfebbf4548db9d52ba0c94997e81196705b4cc8
mimesis_project/apps/mimesis/managers.py
mimesis_project/apps/mimesis/managers.py
from django.db import models from django.contrib.contenttypes.models import ContentType class MediaAssociationManager(models.Manager): def for_model(self, model, content_type=None): content_type = content_type or ContentType.objects.get_for_model(model) objects = self.get_query_set().filter(...
from django.db import models from django.contrib.contenttypes.models import ContentType from django.utils.encoding import force_unicode class MediaAssociationManager(models.Manager): def for_model(self, model, content_type=None): """ QuerySet for all media for a particular model (either an instanc...
Allow both instance and model classes in Media.objects.for_model()
Allow both instance and model classes in Media.objects.for_model()
Python
bsd-3-clause
eldarion/mimesis,eldarion/mimesis
d760c42b1abb37087e9d5cf97d1bd1f2c0d76279
application/__init__.py
application/__init__.py
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_login import LoginManager from rauth import OAuth2Service app = Flask(__name__) BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) app.static_f...
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_login import LoginManager from rauth import OAuth2Service app = Flask(__name__) BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) app.static_f...
Allow cross-origin headers on dev builds
Allow cross-origin headers on dev builds
Python
bsd-3-clause
Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber
680271d4669a309977e5fcfe89f92ea35ebc8d6f
common/djangoapps/dark_lang/migrations/0002_data__enable_on_install.py
common/djangoapps/dark_lang/migrations/0002_data__enable_on_install.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Converted from the original South migration 0002_enable_on_install.py # from django.db import migrations, models def create_dark_lang_config(apps, schema_editor): """ Enable DarkLang by default when it is installed, to prevent accidental r...
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Converted from the original South migration 0002_enable_on_install.py # from django.db import migrations, models def create_dark_lang_config(apps, schema_editor): """ Enable DarkLang by default when it is installed, to prevent accidental r...
Correct the darklang migration, since many darklang configs can exist.
Correct the darklang migration, since many darklang configs can exist.
Python
agpl-3.0
waheedahmed/edx-platform,hamzehd/edx-platform,ovnicraft/edx-platform,hamzehd/edx-platform,miptliot/edx-platform,Lektorium-LLC/edx-platform,kursitet/edx-platform,Ayub-Khan/edx-platform,marcore/edx-platform,teltek/edx-platform,analyseuc3m/ANALYSE-v1,msegado/edx-platform,franosincic/edx-platform,marcore/edx-platform,kmooc...
8cac0c660eee774c32b87d2511e4d2eeddf0ffe8
scripts/slave/chromium/dart_buildbot_run.py
scripts/slave/chromium/dart_buildbot_run.py
#!/usr/bin/env python # Copyright (c) 2012 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. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation sc...
#!/usr/bin/env python # Copyright (c) 2012 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. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation sc...
Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process.
Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process. Additionally, start calling a new script for release builds (there are none yet, but this is what will be used to build the sdk and editor) TBR=foo Review URL: https://chromiumcodereview...
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
0daae44acaefcc40b749166a1ee4ab8fe6ace368
fix_virtualenv.py
fix_virtualenv.py
from __future__ import unicode_literals, print_function import os import argparse import sys import shutil def main(): ap = argparse.ArgumentParser() ap.add_argument("virtualenv", help="The path to the virtual environment.") args = ap.parse_args() target = "{}/include/python{}.{}".format(args.virtual...
from __future__ import unicode_literals, print_function import os import argparse import sys import shutil import sysconfig def main(): target = os.path.dirname(sysconfig.get_config_h_filename()) try: source = os.readlink(target) except: print(target, "is not a symlink. Perhaps this scrip...
Use sysconfig to find the include directory.
Use sysconfig to find the include directory.
Python
lgpl-2.1
renpy/pygame_sdl2,renpy/pygame_sdl2,renpy/pygame_sdl2,renpy/pygame_sdl2
703c0f20215e63cb92436875a1798c1becf4b89f
tests/test_examples.py
tests/test_examples.py
import requests import time import multiprocessing from examples import minimal def test_minimal(): port = minimal.app.get_port() p = multiprocessing.Process( target=minimal.app.start_server) p.start() try: time.sleep(3) r = requests.get('http://127.0.0.1:{port}/hello'.format(...
import requests import time import multiprocessing from examples import minimal class TestExamples(object): servers = {} @classmethod def setup_class(self): """ setup any state specific to the execution of the given module.""" self.servers['minimal'] = {'port': minimal.app.get_port()} ...
Reorganize tests in a class
Reorganize tests in a class
Python
mit
factornado/factornado
4078743923befac99672b67ea53fd1fe11af2e8c
tests/test_mjviewer.py
tests/test_mjviewer.py
""" Test mujoco viewer. """ import unittest from mujoco_py import mjviewer, mjcore class MjLibTest(unittest.TestCase): xml_path = 'tests/models/cartpole.xml' def setUp(self): self.width = 100 self.height = 100 self.viewer = mjviewer.MjViewer(visible=False, ...
""" Test mujoco viewer. """ import unittest from mujoco_py import mjviewer, mjcore class MjLibTest(unittest.TestCase): xml_path = 'tests/models/cartpole.xml' def setUp(self): self.width = 100 self.height = 100 self.viewer = mjviewer.MjViewer(visible=False, ...
Stop using ord with ints
Stop using ord with ints
Python
mit
pulkitag/mujoco140-py,pulkitag/mujoco140-py,pulkitag/mujoco140-py
94e13e5d00dc5e2782cf4a1346f098e3c2ad2fc0
iotendpoints/endpoints/urls.py
iotendpoints/endpoints/urls.py
import os from django.conf.urls import url from . import views OBSCURE_URL = r'^{}$'.format(os.environ.get('OBSCURE_URL', 'this_should_be_in_env_var')) urlpatterns = [ url(r'^$', views.index, name='index'), url(OBSCURE_URL, views.obscure_dump_request_endpoint, name='dump_request'), ]
import os from django.conf.urls import url from . import views DUMMY_OBSCURE_URL = 'this_should_be_in_env_var' OBSCURE_URL = os.environ.get('OBSCURE_URL', DUMMY_OBSCURE_URL) if DUMMY_OBSCURE_URL == OBSCURE_URL: print("Warning: you should set OBSCURE_URL environment variable in this env\n\n") OBSCURE_URL_PATTERN ...
Add warning if OBSCURE_URL env var is not set
Add warning if OBSCURE_URL env var is not set
Python
mit
aapris/IoT-Web-Experiments
8895cd5090bd1014d3fe16976c56d6c24bad0ded
parlai/agents/local_human/local_human.py
parlai/agents/local_human/local_human.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """Agent does gets the loca...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """Agent does gets the loca...
Send episode_done=True from local human agent
Send episode_done=True from local human agent
Python
mit
facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI,facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI
a5b7dabcb4450cadd931421738c0ee6f6b63ea4a
helpers/config.py
helpers/config.py
import os from os.path import join, dirname, abspath from dotenv import load_dotenv class Config: loaded = False @staticmethod def load(file_name='../config/.env'): load_dotenv(join(dirname(__file__), file_name)) env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get(...
import os from os.path import join, dirname, abspath from dotenv import load_dotenv class Config: max_seq_size = 1000 loaded = False @staticmethod def load(file_name='../config/.env'): load_dotenv(join(dirname(__file__), file_name)) env_file_path = abspath(join(dirname(__file__), '../...
Move seq size to const
Move seq size to const
Python
mit
Holovin/D_GrabDemo
1ae097291a42022013969287ecb91bafa60ae625
examples/send_transfer.py
examples/send_transfer.py
# coding=utf-8 """ Example script that shows how to use PyOTA to send a transfer to an address. """ from iota import * # Create the API instance. api =\ Iota( # URI of a locally running node. 'http://localhost:14265/', # Seed used for cryptographic functions. seed = b'SEED9GOES9HERE' ) # For mor...
# coding=utf-8 """ Example script that shows how to use PyOTA to send a transfer to an address. """ from iota import * SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999" ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL29999...
Clarify Address usage in send example
Clarify Address usage in send example Improved the script to explain the recipient address a little better. Changed the address concat to a reference to a specific kind of Iota address. This is loosely inspired by the JAVA sen transaction test case.
Python
mit
iotaledger/iota.lib.py
a029c6f4fce36693a9dee53ff8bc797890cfe71e
plugins/basic_info_plugin.py
plugins/basic_info_plugin.py
import string import textwrap from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Len...
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some ba...
Use table instead of separate lines
Use table instead of separate lines
Python
mit
Sakartu/stringinfo
1ff53eade7c02a92f5f09c371b766e7b176a90a1
speyer/ingest/gerrit.py
speyer/ingest/gerrit.py
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not...
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not...
Allow connecting to unknown hosts but warn
Allow connecting to unknown hosts but warn
Python
apache-2.0
locke105/streaming-python-testdrive
5954196d3c81083f7f94eca147fe1a76a6dfb301
vc_vidyo/indico_vc_vidyo/blueprint.py
vc_vidyo/indico_vc_vidyo/blueprint.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...
Fix "make me room owner"
VC/Vidyo: Fix "make me room owner"
Python
mit
ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,indico/indico-plugins,indico/indico-plugins
e1a1a19408c052c93ccc1684b2e1408ba229addc
tests/test_cookiecutter_invocation.py
tests/test_cookiecutter_invocation.py
# -*- coding: utf-8 -*- """ test_cookiecutter_invocation ---------------------------- Tests to make sure that cookiecutter can be called from the cli without using the entry point set up for the package. """ import pytest import subprocess def test_should_raise_error_without_template_arg(capfd): with pytest.ra...
# -*- coding: utf-8 -*- """ test_cookiecutter_invocation ---------------------------- Tests to make sure that cookiecutter can be called from the cli without using the entry point set up for the package. """ import os import pytest import subprocess from cookiecutter import utils def test_should_raise_error_witho...
Implement test to make sure cookiecutter main is called
Implement test to make sure cookiecutter main is called
Python
bsd-3-clause
michaeljoseph/cookiecutter,luzfcb/cookiecutter,benthomasson/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,takeflight/cookiecutter,cguardia/cookiecutter,moi65/cookiecutter,christabor/cookiecutter,pjbull/cookiecutter,michaeljoseph/cookiec...
5eaca14a3ddf7515f5b855aee4b58d21048ca9a9
avena/utils.py
avena/utils.py
#!/usr/bin/env python from os.path import exists, splitext from random import randint _depth = lambda x, y, z=1: z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) _PREFERRED_RGB = { 'R': 0, 'G': 1, 'B': 2, } def depth(array): '''Return the depth (the third dimension) of an array...
#!/usr/bin/env python from os.path import exists, splitext from random import randint def _depth(x, y, z=1): return z _invert_dict = lambda d: dict((v, k) for k, v in list(d.items())) _PREFERRED_RGB = { 'R': 0, 'G': 1, 'B': 2, } def depth(array): '''Return the depth (the third dimension) of a...
Use a function instead of a lambda expression.
Use a function instead of a lambda expression.
Python
isc
eliteraspberries/avena
e36caab07168d3884b55970e5fa6ee5146df1b1c
src/waldur_mastermind/booking/processors.py
src/waldur_mastermind/booking/processors.py
import mock BookingCreateProcessor = mock.MagicMock() BookingDeleteProcessor = mock.MagicMock()
from waldur_mastermind.marketplace import processors class BookingCreateProcessor(processors.CreateResourceProcessor): def get_serializer_class(self): pass def get_viewset(self): pass def get_post_data(self): pass def get_scope_from_response(self, response): pass c...
Fix using mock in production
Fix using mock in production [WAL-2530]
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur
48f15196bdbdf6c86491ff4ab966f4ae82932b80
libact/labelers/interactive_labeler.py
libact/labelers/interactive_labeler.py
"""Interactive Labeler This module includes an InteractiveLabeler. """ import matplotlib.pyplot as plt from libact.base.interfaces import Labeler from libact.utils import inherit_docstring_from class InteractiveLabeler(Labeler): """Interactive Labeler InteractiveLabeler is a Labeler object that shows the ...
"""Interactive Labeler This module includes an InteractiveLabeler. """ import matplotlib.pyplot as plt from libact.base.interfaces import Labeler from libact.utils import inherit_docstring_from class InteractiveLabeler(Labeler): """Interactive Labeler InteractiveLabeler is a Labeler object that shows the ...
Fix compatibility issues with "input()" in python2
Fix compatibility issues with "input()" in python2 override input with raw_input if in python2
Python
bsd-2-clause
ntucllab/libact,ntucllab/libact,ntucllab/libact
c26ebf61079fc783d23000ee4e023e1111d8a75e
blog/manage.py
blog/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": if socket.gethostname() == 'blog': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.production") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.local" from django.core.management import execute_...
#!/usr/bin/env python import os import sys if __name__ == "__main__": if socket.gethostname() == 'blog': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base") from django.core.management import execute_from_c...
Switch settings used to just settings/base.py
Switch settings used to just settings/base.py
Python
bsd-3-clause
giovannicode/giovanniblog,giovannicode/giovanniblog
432bbebbfa6376779bc605a45857ccdf5fef4b59
soundgen.py
soundgen.py
from wavebender import * import sys start = 10 final = 200 end_time= 10 def val(i): time = float(i) / 44100 k = (final - start) / end_time return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2))) def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = comp...
from wavebender import * import sys from common import * def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
Make sound generator use common
Make sound generator use common Signed-off-by: Ian Macalinao <57a33a5496950fec8433e4dd83347673459dcdfc@giza.us>
Python
isc
simplyianm/resonance-finder
1237e75486ac0ae5c9665ec10d6701c530d601e8
src/petclaw/__init__.py
src/petclaw/__init__.py
# ===================================================================== # Package: petclaw # File: __init__.py # Authors: Amal Alghamdi # David Ketcheson # Aron Ahmadia # ====================================================================== """Main petclaw package""" im...
# ===================================================================== # Package: petclaw # File: __init__.py # Authors: Amal Alghamdi # David Ketcheson # Aron Ahmadia # ====================================================================== """Main petclaw package""" im...
Add ImplicitClawSolver1D to base namespace
Add ImplicitClawSolver1D to base namespace
Python
bsd-3-clause
unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw
40f9f82289d0b15c1bc42415460325ce2a447eaf
cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py
cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py
from django.core.management.base import BaseCommand from dateutil.relativedelta import relativedelta from legalaid.models import Case from cla_butler.tasks import DeleteOldData class FindAndDeleteCasesUsingCreationTime(DeleteOldData): def get_eligible_cases(self): two_years = self.now - relativedelta(yea...
from django.core.management.base import BaseCommand from dateutil.relativedelta import relativedelta from legalaid.models import Case from cla_butler.tasks import DeleteOldData class FindAndDeleteCasesUsingCreationTime(DeleteOldData): def get_eligible_cases(self): super(FindAndDeleteCasesUsingCreationTim...
Refactor class so the now time is always defined
Refactor class so the now time is always defined Added code to class to run the setup method which assigns a variable to self.now (ie. defines a time for now)
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend