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
1e5d549b6fdf62c1016451f9dfe566c9546b2f38
bcbio/bed/__init__.py
bcbio/bed/__init__.py
import pybedtools as bt import six def concat(bed_files, catted=None): """ recursively concat a set of BED files, returning a sorted bedtools object of the result """ if len(bed_files) == 0: if catted: return catted.sort() else: return catted if not catt...
import pybedtools as bt import six def concat(bed_files, catted=None): """ recursively concat a set of BED files, returning a sorted bedtools object of the result """ bed_files = [x for x in bed_files if x] if len(bed_files) == 0: if catted: # move to a .bed extension for do...
Move the file to have an extension of .bed.
Move the file to have an extension of .bed. A lot of tools detect what type of file it is by the extension, so this lets us pass on the BedTool.fn as the filename and not break things.
Python
mit
guillermo-carrasco/bcbio-nextgen,lbeltrame/bcbio-nextgen,gifford-lab/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,vladsaveliev/bcbio-nextgen,brainstorm/bcbio-nextgen,mjafin/bcbio-nextgen,lbeltrame/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,brainstorm/bcbio-nextgen,fw1121/bcbio-nextgen,verdurin/bcbio-nextgen,lpantano/bcbio-ne...
8abf65d6b364bd71e8aa32e25d319c77d716a85f
bin/verify_cached_graphs.py
bin/verify_cached_graphs.py
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) diff = compare(cached, graph) if diff: ...
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): cached = flow.get_cached_graph(ignore_balances) if not cached: continue graph = flow.build_graph(ignore_balances) diff = com...
Fix cached graph verifier tool to handle case where no graph is cached ATM.
Fix cached graph verifier tool to handle case where no graph is cached ATM.
Python
agpl-3.0
rfugger/villagescc,rfugger/villagescc,rfugger/villagescc,rfugger/villagescc
5d63656e9b03aaed2ef9042ff61a86bc4b8ee715
django_rq/decorators.py
django_rq/decorators.py
from django.utils import six from rq.decorators import job as _rq_job from .queues import get_queue def job(func_or_queue, connection=None, *args, **kwargs): """ The same as RQ's job decorator, but it works automatically works out the ``connection`` argument from RQ_QUEUES. And also, it allows simpl...
from rq.decorators import job as _rq_job from .queues import get_queue def job(func_or_queue, connection=None, *args, **kwargs): """ The same as RQ's job decorator, but it works automatically works out the ``connection`` argument from RQ_QUEUES. And also, it allows simplified ``@job`` syntax to put ...
Add a fallback for older Django versions that doesn't come with "six"
Add a fallback for older Django versions that doesn't come with "six"
Python
mit
meteozond/django-rq,sbussetti/django-rq,sbussetti/django-rq,ui/django-rq,viaregio/django-rq,1024inc/django-rq,meteozond/django-rq,lechup/django-rq,ui/django-rq,mjec/django-rq,1024inc/django-rq,ryanisnan/django-rq,ryanisnan/django-rq,viaregio/django-rq,mjec/django-rq,lechup/django-rq
bd1719885b1328c5aca34bc8d78b761e846f4037
tests/query_test/test_decimal_queries.py
tests/query_test/test_decimal_queries.py
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted tests for decimal type. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestDecimalQueries(ImpalaTestSuite): BATCH_SIZES = [0, 1] ...
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted tests for decimal type. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestDecimalQueries(ImpalaTestSuite): BATCH_SIZES = [0, 1] ...
Fix the ASAN build by xfailing test_decimal when ASAN_OPTIONS is set.
Fix the ASAN build by xfailing test_decimal when ASAN_OPTIONS is set. Adding decimal columns crashes an ASAN built impalad. This change skips the test. Change-Id: Ic94055a3f0d00f89354177de18bc27d2f4cecec2 Reviewed-on: http://gerrit.ent.cloudera.com:8080/2532 Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485...
Python
apache-2.0
cchanning/Impala,XiaominZhang/Impala,tempbottle/Impala,cgvarela/Impala,kapilrastogi/Impala,grundprinzip/Impala,scalingdata/Impala,bratatidas9/Impala-1,mapr/impala,ImpalaToGo/ImpalaToGo,cchanning/Impala,lnliuxing/Impala,gerashegalov/Impala,theyaa/Impala,lirui-intel/Impala,bowlofstew/Impala,ImpalaToGo/ImpalaToGo,gerasheg...
9611fcd38c8d75b1c101870ae59de3db326c6951
pyfive/tests/test_pyfive.py
pyfive/tests/test_pyfive.py
import numpy as np from numpy.testing import assert_array_equal import pyfive import h5py def test_read_basic_example(): # reading with HDF5 hfile = h5py.File('basic_example.hdf5', 'r') assert hfile['/example'].attrs['foo'] == 99.5 assert hfile['/example'].attrs['bar'] == 42 np.testing.assert_ar...
""" Unit tests for pyfive. """ import os import numpy as np from numpy.testing import assert_array_equal import pyfive import h5py DIRNAME = os.path.dirname(__file__) BASIC_HDF5_FILE = os.path.join(DIRNAME, 'basic_example.hdf5') BASIC_NETCDF4_FILE = os.path.join(DIRNAME, 'basic_example.nc') def test_read_basic_exa...
Make unit tests path aware
Make unit tests path aware
Python
bsd-3-clause
jjhelmus/pyfive
2cc8a541814cc353e7b60767afd2128dce38918a
tests/test_plugins/test_plugin/server.py
tests/test_plugins/test_plugin/server.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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 ...
Fix failing python style test
Fix failing python style test
Python
apache-2.0
jbeezley/girder,jcfr/girder,RafaelPalomar/girder,opadron/girder,Kitware/girder,essamjoubori/girder,RafaelPalomar/girder,adsorensen/girder,Xarthisius/girder,adsorensen/girder,data-exp-lab/girder,jcfr/girder,girder/girder,opadron/girder,Xarthisius/girder,data-exp-lab/girder,jcfr/girder,kotfic/girder,manthey/girder,msmole...
db99f77edfb7318ee3b4a443a98c837611054515
utils/fields.py
utils/fields.py
import json from django.contrib.postgres.forms.jsonb import InvalidJSONInput, JSONField class JSONPrettyField(JSONField): def __init__(self, *args, **kwargs): self.__indent = kwargs.pop('indent', 2) super().__init__(*args, **kwargs) def prepare_value(self, value): if isinstance(value...
import json from django.contrib.postgres.forms.jsonb import InvalidJSONInput, JSONField from django.forms import ValidationError class JSONPrettyField(JSONField): def __init__(self, *args, **kwargs): self.__indent = kwargs.pop('indent', 2) self.__dict_only = kwargs.pop('dict_only', False) ...
Add list_only and dict_only to JSONPrettyField
Add list_only and dict_only to JSONPrettyField
Python
mit
bulv1ne/django-utils,bulv1ne/django-utils
30b6a5364dc22261a4d47aec2e0a77e0c5b8ccd4
wsme/release.py
wsme/release.py
name = "WSME" version = "0.1.0a2" description = "Web Services Made Easy" long_description = """ Web Service Made Easy is a pure-wsgi and modular rewrite of TGWebServices. """ author = "Christophe de Vienne" email = "cdevienne@gmail.com" url = "http://bitbucket.org/cdevienne/wsme" license = "MIT"
name = "WSME" version = "0.1.0a3" description = "Web Services Made Easy" long_description = """ Web Service Made Easy is a pure-wsgi and modular rewrite of TGWebServices. """ author = "Christophe de Vienne" email = "python-wsme@googlegroups.com" url = "http://bitbucket.org/cdevienne/wsme" license = "MIT"
Update the contact mail and version
Update the contact mail and version
Python
mit
stackforge/wsme
49263d5e43be6ab9a5c3faf2ee6478840526cccb
flatten-array/flatten_array.py
flatten-array/flatten_array.py
def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" if isinstance(lst, (list, tuple)): for item in lst: if item is None: continue else: ...
def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" for item in lst: if isinstance(item, (list, tuple)): yield from _flatten(item) elif item is not None: ...
Tidy and simplify generator code
Tidy and simplify generator code
Python
agpl-3.0
CubicComet/exercism-python-solutions
614ab31af817fa9775fe2aa904687456656bf6fc
tags/fields.py
tags/fields.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db.models.fields import CharField from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from tags.models import Tag @python_2_unicode_compatible class TagField(CharField): def __init__(self, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db.models.fields import CharField from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from tags.models import Tag @python_2_unicode_compatible class TagField(CharField): def __init__(self, ...
Set except import error on add introspection rules south
Set except import error on add introspection rules south
Python
mit
avelino/django-tags
be03357a9d18a4a6174c075db1fdd786100925aa
lat_lng.py
lat_lng.py
from math import atan, tan, radians def lat_lng(lat, lng): """ Return corrected lat/lng. Lat: -90 to 90 Lng: -180 to 180 """ # lat # if lat > 180: # reduce to value less than 180 # lat = lat - (lat//180)*180 # if lat < -180: # increase to value greater than -180 # ...
from math import atan, tan, radians, degrees def lat_lng(lat, lng): """ Return corrected lat/lng. Lat: -90 to 90 Lng: -180 to 180 """ # lat # if lat > 180: # reduce to value less than 180 # lat = lat - (lat//180)*180 # if lat < -180: # increase to value greater than -180 ...
Change output back to degrees.
Change output back to degrees.
Python
mit
bm5w/lat_lng
4657ecdf6889684cf83c77f34233d8bd3ba852a2
tests/events/test_models.py
tests/events/test_models.py
# -*- coding: utf-8 -*- import pytest from components.events.models import Event, Performance, Venue from components.events.factories import (EventFactory, PerformanceFactory, VenueFactory) pytestmark = pytest.mark.django_db class TestEvents: def test_factory(self): factory = EventFactory() ...
# -*- coding: utf-8 -*- import datetime import pytest from components.events.models import Event, Performance, Venue from components.events.factories import (EventFactory, PerformanceFactory, VenueFactory) pytestmark = pytest.mark.django_db class TestEvents: def test_factory(self): factory = EventFa...
Test string representations and get_absolute_url() calls.
Test string representations and get_absolute_url() calls.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
dfefb21bd170bf253f0d07dba2931de82ed0b1e8
tests/conftest.py
tests/conftest.py
import os.path import pytest def pytest_collection_modifyitems(items): for item in items: module_path = os.path.relpath( item.module.__file__, os.path.commonprefix([__file__, item.module.__file__]), ) module_root_dir = module_path.split(os.sep)[0] if modul...
import os.path import pytest @pytest.yield_fixture def tmpdir(request, tmpdir): try: yield tmpdir finally: tmpdir.remove(ignore_errors=True) def pytest_collection_modifyitems(items): for item in items: module_path = os.path.relpath( item.module.__file__, ...
Fix tmpdir fixture to remove all the sutff (normally it keeps the last 3, which is a lot).
Fix tmpdir fixture to remove all the sutff (normally it keeps the last 3, which is a lot).
Python
mit
ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv
34754e91a398e35f0e7d16bbd591c5b4a496536a
src/commons.py
src/commons.py
from contextlib import contextmanager from sympy import Eq, Lambda, Function, Indexed def define(let, be, **kwds): return Eq(let, be, **kwds) @contextmanager def lift_to_Lambda(eq, return_eq=False, lhs_handler=lambda args: []): lhs = eq.lhs args = (lhs.args[1:] if isinstance(lhs, Indexed) else ...
from contextlib import contextmanager, redirect_stdout from sympy import Eq, Lambda, Function, Indexed, latex def define(let, be, **kwds): return Eq(let, be, **kwds) @contextmanager def lift_to_Lambda(eq, return_eq=False, lhs_handler=lambda args: []): lhs = eq.lhs args = (lhs.args[1:] if isinstance(lhs, ...
Add a definition about saving latex representation of a term in a file capturing `print` stdout.
Add a definition about saving latex representation of a term in a file capturing `print` stdout.
Python
mit
massimo-nocentini/simulation-methods,massimo-nocentini/simulation-methods
c33e9cbf0f08c4ec93c9aeea899d93ac257b9bea
sysrev/tests.py
sysrev/tests.py
from django.test import TestCase from api import PubMed from sysrev.models import Review class PubmedQueryTestCase(TestCase): def test_query(self): result = PubMed.query("smoking") self.assertGreater(result[u'Count'], 25000, "Expected >25000 results for smoking") def test_paper(self): ...
from django.test import TestCase from api import PubMed from sysrev.models import Review class PubmedQueryTestCase(TestCase): def test_query(self): result = PubMed.query("smoking") self.assertGreater(result[u'Count'], 25000, "Expected >25000 results for smoking") def test_paper(self): ...
Add (failing) test for ADHD query. Returns results on site, not through API. Needs investigation
Add (failing) test for ADHD query. Returns results on site, not through API. Needs investigation
Python
mit
iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview
f2396815912b1698c4969d86d1f4176122489222
taemin/plugin.py
taemin/plugin.py
""" Base class for all taemin plugin """ class TaeminPlugin(object): helper = {} def __init__(self, taemin): self.taemin = taemin def start(self): pass def stop(self): pass def on_join(self, connection): pass def on_pubmsg(self, msg): pass def o...
""" Base class for all taemin plugin """ import itertools MAX_MSG_LENGTH = 400 class TaeminPlugin(object): helper = {} def __init__(self, taemin): self.taemin = taemin def start(self): pass def stop(self): pass def on_join(self, connection): pass def on_pu...
Split privmsg if their are too long
Split privmsg if their are too long
Python
mit
ningirsu/taemin,ningirsu/taemin
c52a39b8a89e1fc8bfe607d2bfa92970d7ae17ad
evelink/parsing/assets.py
evelink/parsing/assets.py
from evelink import api from evelink import constants def parse_assets(api_result): def handle_rowset(rowset, parent_location): results = [] for row in rowset.findall('row'): item = {'id': int(row.attrib['itemID']), 'item_type_id': int(row.attrib['typeID']), ...
from evelink import api from evelink import constants def parse_assets(api_result): def handle_rowset(rowset, parent_location): results = [] for row in rowset.findall('row'): item = {'id': int(row.attrib['itemID']), 'item_type_id': int(row.attrib['typeID']), ...
Fix test involving Element object
Fix test involving Element object
Python
mit
zigdon/evelink,FashtimeDotCom/evelink,Morloth1274/EVE-Online-POCO-manager,ayust/evelink,bastianh/evelink
07999d1f24acbbfde50fe94897054e7c8df7fea1
api/jsonstore.py
api/jsonstore.py
import json import os import tempfile def store(data, directory="/var/www/luke/wikipedia/graphs/"): try: json.loads(data) except ValueError: return "not-json" tf = tempfile.mkstemp(prefix="", dir=directory)[1] with open(tf, "w") as f: f.write(data) return tf if __name__ ...
import json import os import tempfile def store(data, directory="/var/www/luke/wikipedia/graphs/"): try: json.loads(data) except ValueError: return "not-json" tf = tempfile.mkstemp(prefix="", dir=directory)[1] with open(tf, "w") as f: f.write(data) return os.path.split(tf...
Tweak JSON api return value to be friendlier
Tweak JSON api return value to be friendlier
Python
mit
controversial/wikipedia-map,controversial/wikipedia-map,controversial/wikipedia-map
56e3225329d2f7fae37139ec1d6727784718d339
test_portend.py
test_portend.py
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = None port = portend.find_available_local_port() family = socket.AF_UNSPEC socktype = socket.SOCK_STREAM return socket.getaddrinfo(host, port, family, socktype) def id_for_info(inf...
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = None # all available interfaces port = portend.find_available_local_port() family = socket.AF_UNSPEC socktype = socket.SOCK_STREAM return socket.getaddrinfo(host, port, family, soc...
Add indication of what None means
Add indication of what None means
Python
mit
jaraco/portend
6bb3321c0a2e4221d08f39e46e1d21220361cdc6
shuup_tests/api/conftest.py
shuup_tests/api/conftest.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2018, Shuup Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from django.conf import settings def pytest_runtest_setup(item): sett...
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2018, Shuup Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from django.conf import settings ORIGINAL_SETTINGS = [] def pytest_runt...
Fix unit test by adding back front apps after API tests
Fix unit test by adding back front apps after API tests
Python
agpl-3.0
shoopio/shoop,shoopio/shoop,shoopio/shoop
46ea832db6db8a98c5b9f5a58a37bfed16a27a10
app/actions/peptable/base.py
app/actions/peptable/base.py
from app.dataformats import peptable as peptabledata from app.dataformats import mzidtsv as psmtsvdata def add_peptide(allpeps, psm, scorecol=False, fncol=None, new=False, track_psms=True): peptide = {'score': psm[scorecol], 'line': psm, 'psms': [] } ...
from app.dataformats import mzidtsv as psmtsvdata def add_peptide(allpeps, psm, key, scorecol=False, fncol=None, new=False, track_psms=True): peptide = {'score': psm[scorecol], 'line': psm, 'psms': [] } if track_psms: if not new: ...
Use input param key instead of using HEADER field
Use input param key instead of using HEADER field
Python
mit
glormph/msstitch
02f7edc042b46f091663fc12451aa043106f4f38
correctiv_justizgelder/urls.py
correctiv_justizgelder/urls.py
from functools import wraps from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_ano...
from functools import wraps from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(req...
Update urlpatterns and remove old patterns pattern
Update urlpatterns and remove old patterns pattern
Python
mit
correctiv/correctiv-justizgelder,correctiv/correctiv-justizgelder
db9703ef5cb277e4556d94503c581cbdf46a8419
api/addons/serializers.py
api/addons/serializers.py
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer, LinksField from api.base.utils import absolute_reverse class NodeAddonFolderSerializer(JSONAPISerializer): """ Overrides AddonSettingsSerializer to return node-specific fields """ class Meta: type_...
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer, LinksField from api.base.utils import absolute_reverse class NodeAddonFolderSerializer(JSONAPISerializer): class Meta: type_ = 'node_addon_folders' id = ser.CharField(source='provider', read_only=True) ...
Remove other docstring of lies
Remove other docstring of lies
Python
apache-2.0
chennan47/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,saradbowman/osf.io,chrisseto/osf.io,cwisecarver/osf.io,acshi/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,mluo613/osf.io,adlius/osf.io,sloria/osf.io,icereval/osf.io,adlius/osf.i...
77caf4f14363c6f53631050d008bc852df465f5e
tests/repl_tests.py
tests/repl_tests.py
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_session(f): strin = Pipe() strout = Pipe() strerr = Pipe() replthread = Thread(target=repl, args=(s...
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_line(exp_line, strin, strout): expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt =...
Stop the repl test on an error, making sure all Pipes are closed
Stop the repl test on an error, making sure all Pipes are closed
Python
mit
andybalaam/cell
93a4191b9cb79ee4ddb2efbb4962bef99bc2ec28
totp_bookmarklet.py
totp_bookmarklet.py
import binascii import base64 import os.path def __content(f): return open(os.path.join(os.path.dirname(__file__), f)).read() crypto_js = __content('crypto.js') hotp_js = __content('hotp.js') myotp_js = __content('my-otp.js') def dataize(document, type='text/html'): return 'data:%s;base64,%s' % (type, base6...
import binascii import base64 import os.path def __content(f): return open(os.path.join(os.path.dirname(__file__), f)).read() crypto_js = __content('crypto.js') hotp_js = __content('hotp.js') myotp_js = __content('my-otp.js') def dataize(document, type='text/html'): return 'data:%s;base64,%s' % (type, base6...
Change exemple code to generate OTP link
Change exemple code to generate OTP link
Python
mit
bdauvergne/totp-js,bdauvergne/totp-js
9f0c73eab846d9b2b35c3223fca2014c338e0617
active_link/templatetags/active_link_tags.py
active_link/templatetags/active_link_tags.py
from django import template from django.conf import settings from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the pat...
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=T...
Fix import of 'reverse' for Django>1.9
Fix import of 'reverse' for Django>1.9
Python
bsd-3-clause
valerymelou/django-active-link
5062700980fe432653a11173ab3c3835caf206c9
scripts/generate_db.py
scripts/generate_db.py
#!/usr/bin/python # This script has to generate the sqlite database # # Requirements (import from): # - sqlite3 # # Syntax: # ./generate_db.py import sqlite3 DEFAULT_DB = "run-tracking.db" def generate_tables(filename_db): conn = sqlite3.connect(filename_db) c = conn.cursor() # Create tables ...
#!/usr/bin/python # This script has to generate the sqlite database # # Requirements (import from): # - sqlite3 # # Syntax: # ./generate_db.py import sqlite3 DEFAULT_DB = "run-tracking.db" def generate_tables(db=DEFAULT_DB): conn = sqlite3.connect(db) c = conn.cursor() # Create tables c.exe...
Add field 'creator' to table 'runs'
Add field 'creator' to table 'runs' Example of values stored into *.tcx files: runtastic - makes sports funtastic, http://www.runtastic.com
Python
mit
dubzzz/py-run-tracking,dubzzz/py-run-tracking,dubzzz/py-run-tracking
5d8453f18689a67185472b20e7daf287ebbdb3ac
wafer/pages/urls.py
wafer/pages/urls.py
from django.conf.urls import patterns, url from django.views.generic import RedirectView urlpatterns = patterns( 'wafer.pages.views', url('^index(?:\.html)?$', RedirectView.as_view(url='/')), url(r'^(.*)$', 'slug', name='wafer_page'), )
from django.conf.urls import patterns, url from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView urlpatterns = patterns( 'wafer.pages.views', url('^index(?:\.html)?$', RedirectView.as_view(url=get_script_prefix())), url(r'^(.*)$', 'slug', name='wafer_page'), )...
Fix default redirect to use get_script_prefix
Fix default redirect to use get_script_prefix
Python
isc
CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer
12866921945d01481f78602dd33eb568c71b5173
localore/people/wagtail_hooks.py
localore/people/wagtail_hooks.py
from django.utils.html import format_html from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('profile_photo', 'full_name', '...
from django.utils.html import format_html from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('profile_photo', 'full_name', '...
Add more search fields to admin team listing page.
Add more search fields to admin team listing page.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
6f09f32684571306b15175e23ee1672fa74ae9a6
teamworkApp/lib/delete_data.py
teamworkApp/lib/delete_data.py
# muddersOnRails() # Sara McAllister November 17, 2017 # Last updated: 11-17-2017 # delete all data from database (this is super sketch) import dbCalls def main(): print('Deleting everything from students, styles, and answers.') dbCalls.remove_all() if __name__ == "__main__": main()
# muddersOnRails() # Sara McAllister November 17, 2017 # Last updated: 11-17-2017 # delete all data from database (this is super sketch) import os import dbCalls summary_file = 'app/assets/images/summary.png' overall_file = 'app/assets/images/overall.png' def main(): print('Deleting everything from students, s...
Remove picture files along with data
Remove picture files along with data
Python
mit
nathanljustin/teamwork-analysis,nathanljustin/teamwork-analysis,nathanljustin/teamwork-analysis,nathanljustin/teamwork-analysis
c4a0b6a5b40f7ed964ef43533c4a761124b2ea06
organizer/views.py
organizer/views.py
from django.http.response import HttpResponse def homepage(request): return HttpResponse('Hello (again) World!')
from django.http.response import HttpResponse from .models import Tag def homepage(request): tag_list = Tag.objects.all() output = ", ".join([tag.name for tag in tag_list]) return HttpResponse(output)
Modify homepage view to list Tags.
Ch04: Modify homepage view to list Tags.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
4ab53bc73406396206ead375dd7b5e656fdc41b7
mycli/packages/special/utils.py
mycli/packages/special/utils.py
import os import subprocess def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' command = arg.strip() directory = '' error = False tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] try: os.chdir(directory) ou...
import os import subprocess def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' directory = '' error = False tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] try: os.chdir(directory) output = subprocess.check_ou...
Remove unused variable from `handle_cd_command`
Remove unused variable from `handle_cd_command`
Python
bsd-3-clause
mdsrosa/mycli,mdsrosa/mycli
e26b3ed4c96d0912f543d079f1ef016974483be5
falmer/matte/queries.py
falmer/matte/queries.py
import graphene from falmer.schema.schema import DjangoConnectionField from . import types from . import models class Query(graphene.ObjectType): all_images = DjangoConnectionField(types.Image) image = graphene.Field(types.Image, media_id=graphene.Int()) def resolve_all_images(self, info, **kwargs): ...
import graphene from falmer.schema.schema import DjangoConnectionField from . import types from . import models class Query(graphene.ObjectType): all_images = DjangoConnectionField(types.Image) image = graphene.Field(types.Image, media_id=graphene.Int()) def resolve_all_images(self, info, **kwargs): ...
Order images by created at
Order images by created at
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
5e4843b99f043bc5ad1ba9842e4bee452a5681e8
yarnitor/ui.py
yarnitor/ui.py
"""YARN monitoring built-in UI.""" from flask import Blueprint, render_template ui_bp = Blueprint('ui', __name__, static_folder='static') @ui_bp.route('/') def index(): return render_template('index.html')
"""YARN monitoring built-in UI.""" import time from flask import Blueprint, render_template, url_for ui_bp = Blueprint('ui', __name__, static_folder='static') version = str(time.time()) def versioned_url_for(endpoint, **args): """Inserts a query string `q` into the args dictionary with the version string ge...
Add static web asset cache busting
Add static web asset cache busting
Python
bsd-3-clause
maxpoint/yarnitor,maxpoint/yarnitor,maxpoint/yarnitor
baf82d48125d51ae5f5f37cf761ade574a2f8fc1
services/flickr.py
services/flickr.py
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/o...
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/o...
Simplify Flickr's scope handling a bit
Simplify Flickr's scope handling a bit
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
852f067c7aab6bdcaabf2550fc5a0995a7e9b0ae
maediprojects/__init__.py
maediprojects/__init__.py
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.babel import Babel import os app = Flask(__name__.split('.')[0]) app.config.from_pyfile(os.path.join('..', 'config.py')) db = SQLAlchemy(app) babel = Babel(app) import routes @babel.localeselector def get_locale(): return app.conf...
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.babel import Babel from flask.ext.mail import Mail import os app = Flask(__name__.split('.')[0]) app.config.from_pyfile(os.path.join('..', 'config.py')) db = SQLAlchemy(app) babel = Babel(app) mail = Mail(app) import routes @babel.loc...
Add flask-mail to use for emailing updates
Add flask-mail to use for emailing updates
Python
agpl-3.0
markbrough/maedi-projects,markbrough/maedi-projects,markbrough/maedi-projects
854bb642dd6a4800f57555187b9dfb1a27a7801c
nibble_aes/find_dist/find_ids.py
nibble_aes/find_dist/find_ids.py
""" Derive a list of impossible differentials. """ from ast import literal_eval import sys def parse(line): return literal_eval(line) def in_set(s, xs): return any(i in s for i in xs) def main(): if len(sys.argv) != 3: print("usage: ./find_ids.py [forward differentials file] [backward differenti...
""" Derive a list of impossible differentials. """ from ast import literal_eval import sys def parse(line): return literal_eval(line) def in_set(s, xs): return any(i in s for i in xs) def main(): if len(sys.argv) != 3: print("usage: ./find_ids.py [forward differentials file] [backward differenti...
Remove conversion to set, as the new file format uses sets in tuples.
Remove conversion to set, as the new file format uses sets in tuples.
Python
mit
wei2912/aes-idc,wei2912/idc,wei2912/idc,wei2912/idc,wei2912/aes-idc,wei2912/idc
7c1dd8a6a547cb6183f66d73b27868a75451eb54
dsh.py
dsh.py
# ----- Info ------------------------------------------------------------------ __author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] ...
# ----- Info ------------------------------------------------------------------ __author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] ...
Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened.""
Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."" This reverts commit 9c428fbfb69c93ef3da935d0d2ab098fbeb1c317.
Python
mit
mcmontero/tinyAPI,mcmontero/tinyAPI
2a41cae0e1992b23647ebdc7d49c435e4a187cf2
jujubigdata/__init__.py
jujubigdata/__init__.py
# Copyright 2014-2015 Canonical Limited. # # This file is part of jujubigdata. # # jujubigdata is free software: you can redistribute it and/or modify # it under the terms of the Apache License version 2.0. # # jujubigdata is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the i...
# Copyright 2014-2015 Canonical Limited. # # This file is part of jujubigdata. # # jujubigdata is free software: you can redistribute it and/or modify # it under the terms of the Apache License version 2.0. # # jujubigdata is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the i...
Make relations import conditional for layers migration
Make relations import conditional for layers migration
Python
apache-2.0
tsakas/jujubigdata,johnsca/jujubigdata,ktsakalozos/jujubigdata-dev,juju-solutions/jujubigdata,juju-solutions/jujubigdata,ktsakalozos/jujubigdata-dev,andrewdmcleod/jujubigdata,andrewdmcleod/jujubigdata,johnsca/jujubigdata,ktsakalozos/jujubigdata,ktsakalozos/jujubigdata,tsakas/jujubigdata
a9581a26704f663f5d496ad07c4a6f4fd0ee641f
lampost/util/encrypt.py
lampost/util/encrypt.py
import hashlib from os import urandom from base64 import b64encode, b64decode from itertools import izip from lampost.util.pdkdf2 import pbkdf2_bin SALT_LENGTH = 8 KEY_LENGTH = 20 COST_FACTOR = 800 def make_hash(password): if isinstance(password, unicode): password = password.encode('utf-8') salt = ...
import hashlib from os import urandom from base64 import b64encode, b64decode from itertools import izip from lampost.util.pdkdf2 import pbkdf2_bin SALT_LENGTH = 8 KEY_LENGTH = 20 COST_FACTOR = 800 def make_hash(password): if isinstance(password, unicode): password = password.encode('utf-8') salt = ...
Remove password back door since database updates complete.
Remove password back door since database updates complete.
Python
mit
genzgd/Lampost-Mud,genzgd/Lampost-Mud,genzgd/Lampost-Mud
1e62124cfb3b3c30cc10a9f8fb1ff25ee2e4aa56
examples/python/helloworld/greeter_server.py
examples/python/helloworld/greeter_server.py
# Copyright 2015 gRPC authors. # # 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...
# Copyright 2015 gRPC authors. # # 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...
Revert changes to helloworld example
Revert changes to helloworld example
Python
apache-2.0
muxi/grpc,ctiller/grpc,firebase/grpc,firebase/grpc,pszemus/grpc,grpc/grpc,donnadionne/grpc,ctiller/grpc,grpc/grpc,pszemus/grpc,pszemus/grpc,vjpai/grpc,grpc/grpc,stanley-cheung/grpc,pszemus/grpc,pszemus/grpc,muxi/grpc,muxi/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,stanley-cheung/grpc,ejona86/grpc,jboeuf/grpc...
ab627a078eee3000806bfd0abcd01dc89e85d93c
src/test_read+write.py
src/test_read+write.py
#!/usr/bin/env python from bioc import BioCReader from bioc import BioCWriter test_file = '../test_input/PMID-8557975-simplified-sentences.xml' dtd_file = '../test_input/BioC.dtd' def main(): bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file) bioc_reader.read() ''' sentences = bioc_reader.c...
#!/usr/bin/env python from bioc import BioCReader from bioc import BioCWriter test_file = '../test_input/bcIVLearningCorpus.xml' dtd_file = '../test_input/BioC.dtd' def main(): bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file) bioc_reader.read() ''' sentences = bioc_reader.collection.docum...
Add BioC.dtd one level up
Add BioC.dtd one level up
Python
bsd-2-clause
SuLab/PyBioC
ac900d1a42e5379e192b57cef67845db202e82c3
tests/test_signed_div.py
tests/test_signed_div.py
import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_strtol(threads): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = ang...
import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_signed_div(): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.P...
Rename the signed_div test case, and ... disable the multithreaded test case.
Rename the signed_div test case, and ... disable the multithreaded test case.
Python
bsd-2-clause
tyb0807/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,schieb/angr,f-prettyland/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,axt/angr,chubbymaggie/angr,schieb/angr,angr/angr,schieb/angr,tyb0807/angr,chubbymaggie/angr,iamahuman/angr,iamahuman/angr,angr/angr,axt/angr,axt/angr
58cc02faf08ec499f0d9239959b6d50a1b2b90ad
tests/unit/test_place.py
tests/unit/test_place.py
"""Tests for the isort import placement module""" from functools import partial from isort import place, sections from isort.settings import Config def test_module(src_path): place_tester = partial(place.module, config=Config(src_paths=[src_path])) assert place_tester("isort") == sections.FIRSTPARTY asse...
"""Tests for the isort import placement module""" from functools import partial from isort import place, sections from isort.settings import Config def test_module(src_path): place_tester = partial(place.module, config=Config(src_paths=[src_path])) assert place_tester("isort") == sections.FIRSTPARTY asse...
Add unit test case for desired placement behavior
Add unit test case for desired placement behavior
Python
mit
PyCQA/isort,PyCQA/isort
8521d53b20e8f4874a82188b792dd1d4d0ecf419
djangae/db/backends/appengine/parsers/version_18.py
djangae/db/backends/appengine/parsers/version_18.py
from django.db.models.expressions import Star from django.db.models.sql.datastructures import EmptyResultSet from .version_19 import Parser as BaseParser class Parser(BaseParser): def _prepare_for_transformation(self): from django.db.models.sql.where import EmptyWhere if isinstance(self.django_qu...
from django.db.models.expressions import Star from django.db.models.sql.datastructures import EmptyResultSet from django.db.models.sql.where import SubqueryConstraint from .version_19 import Parser as BaseParser class Parser(BaseParser): def _prepare_for_transformation(self): from django.db.models.sql.wh...
Fix empty Q() filters on Django 1.8
Fix empty Q() filters on Django 1.8
Python
bsd-3-clause
grzes/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae
a382c448da054db4631bb9940d27d4b527d7d5ce
execute_all_tests.py
execute_all_tests.py
#! /bin/python3 """ This program 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 (at your option) any later version. This program is distributed in the hope that it will be us...
#! /bin/python3 """ This program 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 (at your option) any later version. This program is distributed in the hope that it will be us...
Test execution: Add bear tests
Test execution: Add bear tests
Python
agpl-3.0
Asalle/coala,incorrectusername/coala,AdeshAtole/coala,stevemontana1980/coala,Balaji2198/coala,NalinG/coala,abhiroyg/coala,SambitAcharya/coala,tushar-rishav/coala,RJ722/coala,arjunsinghy96/coala,netman92/coala,scriptnull/coala,damngamerz/coala,d6e/coala,FeodorFitsner/coala,stevemontana1980/coala,abhiroyg/coala,saurabhii...
b4e06f4e35355ed7502359d2ecffbee00d615f36
numba/tests/test_numpyadapt.py
numba/tests/test_numpyadapt.py
from __future__ import print_function from numba.ctypes_support import * import numpy import numba.unittest_support as unittest from numba._numpyadapt import get_ndarray_adaptor class ArrayStruct3D(Structure): _fields_ = [ ("data", c_void_p), ("shape", (c_ssize_t * 3)), ("strides", (c_ssiz...
from __future__ import print_function from numba.ctypes_support import * import numpy import numba.unittest_support as unittest from numba._numpyadapt import get_ndarray_adaptor class ArrayStruct3D(Structure): _fields_ = [ ("data", c_void_p), ("shape", (c_ssize_t * 3)), ("strides", (c_ssiz...
Fix test after changing array structure
Fix test after changing array structure
Python
bsd-2-clause
seibert/numba,GaZ3ll3/numba,pombredanne/numba,sklam/numba,stonebig/numba,gmarkall/numba,sklam/numba,seibert/numba,numba/numba,stuartarchibald/numba,sklam/numba,stonebig/numba,pombredanne/numba,IntelLabs/numba,ssarangi/numba,stuartarchibald/numba,cpcloud/numba,stefanseefeld/numba,gdementen/numba,ssarangi/numba,pitrou/nu...
0106108b2bb4f9ad5eaa4e02981293d5f5613aaf
cvmfs/webapi/cvmfs_api.py
cvmfs/webapi/cvmfs_api.py
import os import cvmfs_geo negative_expire_secs = 60*5; # 5 minutes def bad_request(start_response, reason): response_body = 'Bad Request: ' + reason + "\n" start_response('400 Bad Request', [('Cache-control', 'max-age=' + str(negative_expire_secs))]) return [response_body] def d...
import os import cvmfs_geo negative_expire_secs = 60*5; # 5 minutes def bad_request(start_response, reason): response_body = 'Bad Request: ' + reason + "\n" start_response('400 Bad Request', [('Cache-control', 'max-age=' + str(negative_expire_secs)), ('Content-Lengt...
Add Content-Length to message in the body of a bad request
Add Content-Length to message in the body of a bad request
Python
bsd-3-clause
reneme/cvmfs,cvmfs/cvmfs,djw8605/cvmfs,djw8605/cvmfs,alhowaidi/cvmfsNDN,cvmfs/cvmfs,djw8605/cvmfs,Gangbiao/cvmfs,trshaffer/cvmfs,cvmfs/cvmfs,reneme/cvmfs,reneme/cvmfs,cvmfs-testing/cvmfs,Moliholy/cvmfs,Gangbiao/cvmfs,reneme/cvmfs,MicBrain/cvmfs,DrDaveD/cvmfs,Moliholy/cvmfs,trshaffer/cvmfs,DrDaveD/cvmfs,MicBrain/cvmfs,G...
5488e6361359eb299e47814fd83e8e09187f45fd
draw_initials.py
draw_initials.py
import turtle def draw_initials(): #Set up screen, etc. window = turtle.Screen() window.bgcolor('gray') ###THE LETTER B### letter = turtle.Turtle() letter.shape('turtle') letter.color('white', 'gray') letter.speed(8) #Move pen into place letter.penup() letter.left(180)...
#!/usr/bin/env python import turtle def draw_initials(): """Draw the initials BC""" # Set up screen, etc. window = turtle.Screen() window.bgcolor('gray') letter = turtle.Turtle() letter.shape('turtle') letter.color('white', 'gray') letter.speed(8) # Move pen into place lette...
Make minor improvements to comments and formatting
Make minor improvements to comments and formatting
Python
mit
bencam/turtle
dd6090464fa3eb1f95f6fd5efd7591b1c06c0ce6
fuel_plugin_builder/fuel_plugin_builder/messages.py
fuel_plugin_builder/fuel_plugin_builder/messages.py
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, 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 requi...
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, 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 requi...
Add rpm-build into environment setup message for CentOS
Add rpm-build into environment setup message for CentOS Change-Id: I44bd14f2f3c3e76c24f5efd26a5ff6a545dcaf72 Implements: blueprint plugin-major-version-for-releases
Python
apache-2.0
nebril/fuel-plugins,stackforge/fuel-plugins,stackforge/fuel-plugins,nebril/fuel-plugins
ee2a6bb99d2a8fadecddd58366c20202c863c97c
geocoder/__init__.py
geocoder/__init__.py
#!/usr/bin/python # coding: utf8 # TODO: Move imports to specific modules that need them # CORE from .api import get, yahoo, bing, geonames, google, mapquest # noqa from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa ...
#!/usr/bin/python # coding: utf8 """ Geocoder ~~~~~~~~ Geocoder is a geocoding library, written in python, simple and consistent. Many online providers such as Google & Bing have geocoding services, these providers do not include Python libraries and have different JSON responses between each other. Consistant JSON...
Add imports to init with noqa comments
Add imports to init with noqa comments
Python
mit
epyatopal/geocoder-1,akittas/geocoder,minimedj/geocoder,DenisCarriere/geocoder,ahlusar1989/geocoder,miraculixx/geocoder
21e5ee2ad250c313ea0eb2c67c3d3cc32661d24d
examples/benchmarking/server.py
examples/benchmarking/server.py
import asyncore,time,signal,sys from secure_smtpd import SMTPServer, FakeCredentialValidator class SecureSMTPServer(SMTPServer): def __init__(self): pass def process_message(self, peer, mailfrom, rcpttos, message_data): pass def start(self): SMTPServer.__init_...
from secure_smtpd import SMTPServer class SecureSMTPServer(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, message_data): pass server = SecureSMTPServer(('0.0.0.0', 1025), None) server.run()
Switch to non-privledged port to make testing easier.
Switch to non-privledged port to make testing easier. User the new server.run() method.
Python
isc
bcoe/secure-smtpd
ff61fb41273b8bf94bd0c64ddb1a4c1e1c91bb5f
api/__init__.py
api/__init__.py
from flask_sqlalchemy import SQLAlchemy import connexion from config import config db = SQLAlchemy() def create_app(config_name): app = connexion.FlaskApp(__name__, specification_dir='swagger/') app.add_api('swagger.yaml') application = app.app application.config.from_object(config[config_name]) ...
from flask_sqlalchemy import SQLAlchemy import connexion from config import config db = SQLAlchemy() def create_app(config_name): app = connexion.FlaskApp(__name__, specification_dir='swagger/') app.add_api('swagger.yaml') application = app.app application.config.from_object(config[config_name]) ...
Add url rules for public unauthorised routes
Add url rules for public unauthorised routes
Python
mit
EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list
51781b95b629a31107d16a52b0ea184306fe6163
pyfakefs/pytest_plugin.py
pyfakefs/pytest_plugin.py
"""A pytest plugin for using pyfakefs as a fixture When pyfakefs is installed, the "fs" fixture becomes available. :Usage: def my_fakefs_test(fs): fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import linecache import py import pytest from pyfakefs.fake_filesystem_unitt...
"""A pytest plugin for using pyfakefs as a fixture When pyfakefs is installed, the "fs" fixture becomes available. :Usage: def my_fakefs_test(fs): fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import linecache import sys import py import pytest from pyfakefs.fake_files...
Fix pytest when pyfakefs + future is installed
Fix pytest when pyfakefs + future is installed `python-future` is notorious for breaking modules which use `try:` / `except:` to import modules based on version. In this case, `pyfakefs` imported the backported `builtins` module which changes the semantics of the `open()` function. `pyfakefs` then monkeypatches `lin...
Python
apache-2.0
mrbean-bremen/pyfakefs,mrbean-bremen/pyfakefs,pytest-dev/pyfakefs,jmcgeheeiv/pyfakefs
4b7e20c5640242a6e06392aaf9cbfe8e4ee8a498
mangopaysdk/types/payinpaymentdetailscard.py
mangopaysdk/types/payinpaymentdetailscard.py
from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None
from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None self.StatementDescriptor = None
Add StatementDescriptor for card web payins
Add StatementDescriptor for card web payins
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
7bd82f6feb1a34dd7b855cfe2f421232229e19db
pages/search_indexes.py
pages/search_indexes.py
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) publication_date = ...
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(m...
Add a title attribute to the SearchIndex for pages.
Add a title attribute to the SearchIndex for pages. This is useful when displaying a list of search results because we can display the title of the result without hitting the database to actually pull the page.
Python
bsd-3-clause
remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,batis...
9ce1f694a7581333d000a6a7b77e8d846bb4b507
imageutils/scaling/normalize.py
imageutils/scaling/normalize.py
""" Normalization class for Matplotlib that can be used to produce colorbars. """ import numpy as np from numpy import ma from matplotlib.colors import Normalize __all__ = ['ImageNormalize'] class ImageNormalize(Normalize): def __init__(self, vmin=None, vmax=None, stretch=None, clip=True): super(Ima...
""" Normalization class for Matplotlib that can be used to produce colorbars. """ import numpy as np from numpy import ma from matplotlib.colors import Normalize __all__ = ['ImageNormalize'] class ImageNormalize(Normalize): def __init__(self, vmin=None, vmax=None, stretch=None, clip=True): super(Ima...
Use in-place operations in ImageNormalize
Use in-place operations in ImageNormalize
Python
bsd-3-clause
dhomeier/astropy,bsipocz/astropy,MSeifert04/astropy,mhvk/astropy,MSeifert04/astropy,mhvk/astropy,joergdietrich/astropy,stargaser/astropy,StuartLittlefair/astropy,lpsinger/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,astropy/astropy,lpsinger/astropy,joergdietrich/astropy,lpsinger/astropy,AustereCuriosity/as...
a33f288bb2937bbf750b9d195861e311f293d94b
grortir/test/externals/pyswarm/test_pyswarm.py
grortir/test/externals/pyswarm/test_pyswarm.py
"""Tests for pyswarm.""" from unittest import TestCase from grortir.externals.pyswarm.pso import pso class TestPso(TestCase): """Class for tests PSO.""" def test_run_simple_pso(self): """Test running library.""" lower_bound = [-3, -1] upper_bound = [2, 6] x_opt, f_opt = pso(m...
"""Tests for pyswarm.""" from unittest import TestCase from grortir.externals.pyswarm.pso import pso class TestPso(TestCase): """Class for tests pyswarm.""" def test_run_simple_pso(self): """Test running library.""" lower_bound = [-3, -1] upper_bound = [2, 6] x_opt, f_opt = p...
Add pySwarm code - tests fixed.
Add pySwarm code - tests fixed.
Python
mit
qbahn/grortir
f19b66d42f67a6a45bec6fdaffe6c73366788b48
rules/RoleRelativePath.py
rules/RoleRelativePath.py
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' n...
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' n...
Add check for src field
Add check for src field Src field can be absent in copy task, and content field can be used instead, so we should check if src is present to avoid Keyerror exception.
Python
mit
tsukinowasha/ansible-lint-rules
aaaaad77054658ad6c5d63a84bffe8d43b4e3180
falcom/tree/mutable_tree.py
falcom/tree/mutable_tree.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class MutableTree: def __init__ (self): self.length = 0 self.value = None @property def value (self): r...
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class MutableTree: def __init__ (self): self.child = None self.value = None @property def value (self): ...
Rework tree to store inserted nodes
Rework tree to store inserted nodes
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
7ddb1b3d0139ef8b6a7badcb2c6bef6a0e35e88a
hooks/post_gen_project.py
hooks/post_gen_project.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Rename the generated kv file to be compatible with the original kivy kv file detection of `App.load_kv`. """ import os package_dir = '{{cookiecutter.repo_name}}' old_kv_file = os.path.join(package_dir, '{{cookiecutter.app_class_name}}.kv') lower_app_class_name = '{{...
#!/usr/bin/env python # -*- coding: utf-8 -*- def rename_kv_file(): """Rename the generated kv file to be compatible with the original kivy kv file detection of `App.load_kv`. """ import os package_dir = '{{cookiecutter.repo_name}}' old_kv_file = os.path.join( package_dir, '{{cookiecut...
Use a function to rename the kv file in hooks
Use a function to rename the kv file in hooks
Python
mit
hackebrot/cookiedozer,hackebrot/cookiedozer
bc32d6456dc2c2b6cef5d2d7b1ccf602b43b1e69
crabpy/client.py
crabpy/client.py
from suds.client import Client def crab_factory(**kwargs): if 'wsdl' in kwargs: wsdl = kwargs['wsdl'] del kwargs['wsdl'] else: wsdl = "http://crab.agiv.be/wscrab/wscrab.svc?wsdl" if 'proxy' in kwargs: proxy = kwargs['proxy'] del kwargs['proxy'] c = Client( ...
from suds.client import Client def crab_factory(**kwargs): if 'wsdl' in kwargs: wsdl = kwargs['wsdl'] del kwargs['wsdl'] else: wsdl = "http://crab.agiv.be/wscrab/wscrab.svc?wsdl" if 'proxy' in kwargs: proxy = kwargs['proxy'] del kwargs['proxy'] c = Client( ...
Add factory for capakey and utility method for doing a request.
Add factory for capakey and utility method for doing a request.
Python
mit
kmillet/crabpytest,OnroerendErfgoed/crabpy,kmillet/crabpytest
caf8c08511042db195b359ed7fffac6d567f1e18
virtool/handlers/updates.py
virtool/handlers/updates.py
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases...
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases(repo, server_version) ...
Return server version from update API
Return server version from update API
Python
mit
igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool
1e5ec4a2923757ca79c8a55b056fd13872cac963
foyer/tests/test_xml_writer.py
foyer/tests/test_xml_writer.py
import glob import itertools as it import os import parmed as pmd from pkg_resources import resource_filename import pytest from foyer import Forcefield from foyer.tests.utils import atomtype from foyer.xml_writer import write_foyer def test_write_xml(filename, ff_file): structure = pmd.loadfile(filename) forc...
import parmed as pmd import pytest import os from pkg_resources import resource_filename from foyer import Forcefield from foyer.xml_writer import write_foyer OPLS_TESTFILES_DIR = resource_filename('foyer', 'opls_validation') def test_write_xml(): top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top') ...
Update xml writer test to work
Update xml writer test to work
Python
mit
iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer
142b9fa072e5958273e67ff38f8c7c7f6ea51373
laboratory/exceptions.py
laboratory/exceptions.py
class LaboratoryException(Exception): pass class MismatchException(LaboratoryException): pass
class LaboratoryException(Exception): def __init__(self, message, *a, **kw): self.message = message super(LaboratoryException, self).__init__(*a, **kw) class MismatchException(LaboratoryException): pass
Add message attr to LaboratoryException
Add message attr to LaboratoryException
Python
mit
joealcorn/laboratory
d9349d617a504381d65f412930126de8e7548300
setup/create_divisions.py
setup/create_divisions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_d...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_d...
Truncate target table before creating division items
Truncate target table before creating division items
Python
mit
leaffan/pynhldb
8b5bab10bf49f35c0c0e9147e7bcbffb88f8b536
django_mailer/managers.py
django_mailer/managers.py
from django.db import models from django_mailer import constants class QueueManager(models.Manager): use_for_related_fields = True def high_priority(self): """ Return a QuerySet of high priority queued messages. """ return self.filter(priority=constants.PRIORITY_HIGH)...
from django.db import models from django_mailer import constants class QueueManager(models.Manager): use_for_related_fields = True def high_priority(self): """ Return a QuerySet of high priority queued messages. """ return self.filter(priority=constants.PRIORITY_HIGH)...
Fix the manager methods for deferred/non_deferred
Fix the manager methods for deferred/non_deferred
Python
mit
APSL/django-mailer-2,pegler/django-mailer-2,tclancy/django-mailer-2,davidmarble/django-mailer-2,maykinmedia/django-mailer-2,Giftovus/django-mailer-2,torchbox/django-mailer-2,APSL/django-mailer-2,SmileyChris/django-mailer-2,victorfontes/django-mailer-2,mfwarren/django-mailer-2,morenopc/django-mailer-2,k1000/django-maile...
af9c686750d55ff786807f9175faadb8bb9087e7
test_quick_sort.py
test_quick_sort.py
from random import shuffle import pytest from quick_sort import quick_srt def test_quick_srt(): expected = range(20) actual = expected[:] shuffle(actual) quick_srt(actual) assert expected == actual def test_quick_srt_with_duplicates(): expected = [1, 3, 3, 6, 7, 8, 8, 8] actual = expect...
from random import shuffle import pytest from quick_sort import quick_srt def test_quick_srt(): expected = range(20) actual = expected[:] shuffle(actual) quick_srt(actual) assert expected == actual def test_quick_srt_with_duplicates(): expected = [1, 3, 3, 6, 7, 8, 8, 8] actual = expect...
Add a few more tests for edge cases
Add a few more tests for edge cases
Python
mit
jonathanstallings/data-structures
09668c1818ef028e10669b9652e2f0ae255cc47e
src/pyscaffold/extensions/no_skeleton.py
src/pyscaffold/extensions/no_skeleton.py
# -*- coding: utf-8 -*- """ Extension that omits the creation of file `skeleton.py` """ from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list...
# -*- coding: utf-8 -*- """ Extension that omits the creation of file `skeleton.py` """ from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension ...
Change extensions to use pathlib in helpers instead of lists
Change extensions to use pathlib in helpers instead of lists
Python
mit
blue-yonder/pyscaffold,blue-yonder/pyscaffold
221caf718c5aa53c2ef5b9b05c72764ae65eac44
SaudiStudentOrganization/models.py
SaudiStudentOrganization/models.py
from __future__ import unicode_literals from django.db import models # Create your models here.
from __future__ import unicode_literals from django.db import models class Student(models.Model): Frist_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=200) Email = models.CharField(max_length=200) Phone_Number = models.CharField(max_length=200) class Responds(models.M...
Change to model from class on 10/10/2016
Change to model from class on 10/10/2016
Python
mit
UniversityOfDubuque/CIS405_DjangoProject,UniversityOfDubuque/CIS405_DjangoProject
4b6afd36114fbe1871f17998f9e3f4ec0e116f0f
spacy/lang/en/__init__.py
spacy/lang/en/__init__.py
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ......
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ......
Remove English [initialize] default block for now to get tests to pass
Remove English [initialize] default block for now to get tests to pass
Python
mit
spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
fffe7392cb486f7218fc8afd2d42769660a1f558
tests/test_main.py
tests/test_main.py
# -*- coding:utf-8 -*- from subprocess import check_call from pytest import raises from csft import __main__ as main def test_call(): check_call(['python', '-m', 'csft', '.']) def test_main(): main.main(argv=['.']) with raises(SystemExit): main.main(argv=[])
# -*- coding:utf-8 -*- from subprocess import check_call from pytest import raises from csft import __main__ as main def test_call(): check_call(['python', '-m', 'csft', '.']) def test_main(): main.main(argv=['.']) with raises(SystemExit): main.main(argv=[]) with raises(TypeError): ...
Test when path not is a directory.
Test when path not is a directory.
Python
mit
yanqd0/csft
bc485e3deb47897fb5d87c80c299f2da240419db
app/__init__.py
app/__init__.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oa = OAuth() lm = LoginManager() lm.login_view = "main.login" from app.models import User @lm.user_loader def load_user(id): r...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oa = OAuth() lm = LoginManager() lm.login_view = "main.login" from app.models import User @lm.user_loader def load_user(id): r...
Add converter before blueprint registration
Add converter before blueprint registration
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
c85fbf33d22a9775f9d22b863027eb50b41923c2
src/excel_sheet_column_title.py
src/excel_sheet_column_title.py
""" Source : https://oj.leetcode.com/problems/excel-sheet-column-number/ Author : Changxi Wu Date : 2015-01-21 Given a column title as appear in an Excel sheet, return its corresponding column number. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB """ # @return a string...
""" Source : https://oj.leetcode.com/problems/excel-sheet-column-number/ Author : Changxi Wu Date : 2015-01-21 Given a column title as appear in an Excel sheet, return its corresponding column number. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB 732 -> ABC """ # @...
Add solution for excel sheet column title
Add solution for excel sheet column title
Python
mit
chancyWu/leetcode
0baf08c61348f4fa6a657e1c0e2ff9bdf65eaa15
leetcode/RemoveElement.py
leetcode/RemoveElement.py
# Remove Element https://oj.leetcode.com/problems/remove-element/ # Given an array and a value, remove all instances of that value in place and return the new length. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. #Arrays # Xilin SUN # Jan 8 2015 # Don't forget to ret...
# Remove Element https://oj.leetcode.com/problems/remove-element/ # Given an array and a value, remove all instances of that value in place and return the new length. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. #Arrays # Xilin SUN # Jan 8 2015 # Don't forget to ret...
Add one more if to speed up
Add one more if to speed up
Python
mit
aenon/OnlineJudge,aenon/OnlineJudge
7a68599ca8794d1d1b7d358e6f79791547f7740f
setuptools/tests/test_build.py
setuptools/tests/test_build.py
from setuptools.dist import Distribution from setuptools.command.build import build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', ...
from setuptools.dist import Distribution from setuptools.command.build import build from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ d...
Test that extending setuptools' build sub_commands does not extend distutils
Test that extending setuptools' build sub_commands does not extend distutils
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
dd3b135ab5e229c5f717fc4d296389e187a49f9a
one_time_eval.py
one_time_eval.py
# usage: python one_time_eval.py as8sqdtc from deuces.deuces import Card from convenience import find_pcts, pr, str2cards import sys cards_str = sys.argv[1] board_str = '' if len(sys.argv) > 2: board_str = sys.argv[2] cards = str2cards(cards_str) board = str2cards(board_str) assert len(cards) == 4 p1 = cards[0:...
# usage: python one_time_eval.py as8sqdtc # usage: python one_time_eval.py as8sqdtc 2skskd from convenience import find_pcts, pr, str2cards import sys ## argv to strings hole_cards_str = sys.argv[1] board_str = '' if len(sys.argv) > 2: board_str = sys.argv[2] ## strings to lists of Card objects hole_cards = str2...
Prepare the main script to accept multi-way pots.
Prepare the main script to accept multi-way pots.
Python
mit
zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments
b9156a522410bf39de8653bce22bb2cb56e435a0
parktain/main.py
parktain/main.py
#!/usr/bin/env python from os.path import abspath, dirname, join from gendo import Gendo HERE = dirname(abspath(__file__)) config_path = join(HERE, 'config.yaml') bot = Gendo.config_from_yaml(config_path) @bot.listen_for('morning') def morning(user, message): # make sure message is "morning" and doesn't just co...
#!/usr/bin/env python # Standard library from os.path import abspath, dirname, join import re # 3rd party library from gendo import Gendo class Parktain(Gendo): """Overridden to add simple additional functionality.""" @property def id(self): """Get id of the bot.""" if not hasattr(self...
Add 'where do you live' answer.
Add 'where do you live' answer.
Python
bsd-3-clause
punchagan/parktain,punchagan/parktain,punchagan/parktain
5ee77b7294af840a47e11a8a9a3da109e33f4a63
lib/stats_backend.py
lib/stats_backend.py
import platform from stats_file_backend import StatsFileBackend class StatsBackend: """ This is a class to manage the Stats backend. """ def __init__(self, options={}): if options == {}: if platform.system() == "Darwin": # For my local dev I need this hack options = {"db_path":"/tmp/stats.jso...
import platform from stats_file_backend import StatsFileBackend class StatsBackend: """ This is a class to manage the Stats backend. """ def __init__(self, options={}): if options == {}: if platform.system() == "Darwin": # For my local dev I need this hack options = {"db_path":"/tmp/stats.jso...
Remove some test code that got left behind
Remove some test code that got left behind
Python
agpl-3.0
dexX7/omniwallet,habibmasuro/omniwallet,habibmasuro/omniwallet,achamely/omniwallet,habibmasuro/omniwallet,VukDukic/omniwallet,OmniLayer/omniwallet,dexX7/omniwallet,achamely/omniwallet,OmniLayer/omniwallet,arowser/omniwallet,OmniLayer/omniwallet,arowser/omniwallet,curtislacy/omniwallet,ripper234/omniwallet,FuzzyBearBTC/...
5d2a4ac0e48d404a16b81d2f290be5ec13bdf8f1
logintokens/forms.py
logintokens/forms.py
"""forms for accounts app """ from django import forms from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get...
"""forms for accounts app """ from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintoken...
Update form to pass new test
Update form to pass new test
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
0b7a1904ef5511916fc4978c325862241a46aef3
lib/pyfrc/mains/cli_profiler.py
lib/pyfrc/mains/cli_profiler.py
import argparse import inspect import subprocess import sys class PyFrcProfiler: """ Wraps other commands by running them via the built in cProfile module. Use this to profile your program and figure out where you're spending a lot of time (note that cProfile only profiles the main thread)...
import argparse import inspect from os.path import abspath import subprocess import sys class PyFrcProfiler: """ Wraps other commands by running them via the built in cProfile module. Use this to profile your program and figure out where you're spending a lot of time (note that cProfile on...
Add output option for profiler
Add output option for profiler
Python
mit
robotpy/pyfrc
3786ebdf37820bc7b59342302c5858d7805a323c
planner/forms.py
planner/forms.py
from django.contrib.auth.forms import AuthenticationForm from django import forms from .models import PoolingUser class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-cont...
from django.contrib.auth.forms import AuthenticationForm from django import forms from .models import PoolingUser class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-cont...
Add documentation for SearchTrip form
Add documentation for SearchTrip form
Python
mit
livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride
8f0b72dcad39fbd6072185bf2244eb75f0f45a96
better_od/core.py
better_od/core.py
from collections import MutableMapping class BetterOrderedDict(MutableMapping): def __init__(self, **kwargs): self._d = dict() self._keys = [] def __len__(self): return len(self._d) def __iter__(self): for key in self._keys: yield key def __setitem__(self...
from collections import MutableMapping class BetterOrderedDict(MutableMapping): '''BetterOrderedDict is a mapping object that allows for ordered access and insertion of keys. With the exception of the key_index, insert, and reorder_keys methods behavior is identical to stock dictionary objects.''' de...
Add docstrings for most public API methods.
Add docstrings for most public API methods.
Python
mit
JustusW/BetterOrderedDict,therealfakemoot/collections2
98335de4b87638eff9613279bdd106651d4aefe1
catt/__init__.py
catt/__init__.py
# -*- coding: utf-8 -*- __author__ = "Stavros Korokithakis" __email__ = "hi@stavros.io" __version__ = "0.9.3"
# -*- coding: utf-8 -*- import sys if sys.version_info.major < 3: print("This program requires Python 3 and above to run.") sys.exit(1) __author__ = "Stavros Korokithakis" __email__ = "hi@stavros.io" __version__ = "0.9.3"
Make catt refuse to install under 2 more
fix: Make catt refuse to install under 2 more
Python
bsd-2-clause
skorokithakis/catt,skorokithakis/catt
f6ce2439f1f1ba299d0579c2dd4e57a58398aca5
printer/PrinterApplication.py
printer/PrinterApplication.py
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(Print...
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) ...
Load all storage plugins in the printer application
Load all storage plugins in the printer application
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
7b72dbb331c120eb5657ce9a81e725c550779485
dataportal/broker/__init__.py
dataportal/broker/__init__.py
from .simple_broker import _DataBrokerClass, EventQueue, Header from .handler_registration import register_builtin_handlers DataBroker = _DataBrokerClass() # singleton register_builtin_handlers()
from .simple_broker import (_DataBrokerClass, EventQueue, Header, LocationError, IntegrityError) from .handler_registration import register_builtin_handlers DataBroker = _DataBrokerClass() # singleton register_builtin_handlers()
Add Errors to the public API.
DOC: Add Errors to the public API.
Python
bsd-3-clause
danielballan/dataportal,ericdill/datamuxer,tacaswell/dataportal,ericdill/datamuxer,tacaswell/dataportal,NSLS-II/dataportal,danielballan/datamuxer,danielballan/datamuxer,ericdill/databroker,NSLS-II/datamuxer,danielballan/dataportal,NSLS-II/dataportal,ericdill/databroker
b40cb43eb2a3afcc08a207b66e1dededd1ff1eaa
count-inversions/count_inversions.py
count-inversions/count_inversions.py
from random import randint import sys def count(arr): n = len(arr) if n == 1: return 0 else: first_half = count(arr[:n/2]) second_half = count(arr[n/2:]) split = count_split(arr) return first_half + second_half + split def count_split(arr): return 0 def main(arr_len): test_arr = [randint(0,arr_len)...
from random import randint import sys def sort_and_count(arr): n = len(arr) if n == 1: return 0 else: first_half = sort_and_count(arr[:n/2]) second_half = sort_and_count(arr[n/2:]) split = merge_and_count_split(arr) return first_half + second_half + split def merge_and_count_split(arr): return 0 def...
Rename functions to include sorting and merging
Rename functions to include sorting and merging The algorithm will require sorting in order to run in O(nlogn) time. The implementation will closely follow that of merge-sort, so the functions were renamed to reflect this.
Python
mit
timpel/stanford-algs,timpel/stanford-algs
7ad0aa082114811a1638916060c6b18f93d09824
books/services.py
books/services.py
from datetime import date from datetime import timedelta from django.utils import timezone from books.models import Transaction def get_months_transactions(): today = timezone.now() first_day_of_a_month = date(today.year, today.month, 1) qs = Transaction.objects.filter(created__gte=first_day_of_a_month)...
from datetime import datetime from datetime import timedelta from django.utils import timezone from books.models import Transaction def get_months_transactions(): today = timezone.now() first_day_of_a_month = datetime(today.year, today.month, 1, tzinfo=today.tzinfo) q...
Add service functions to get transactions by time
Add service functions to get transactions by time
Python
mit
trimailov/finance,trimailov/finance,trimailov/finance
d538e4fd59d714b7a7826937c50b66ec3f697b05
mygpo/api/backend.py
mygpo/api/backend.py
import uuid from django.db import transaction, IntegrityError from mygpo.users.settings import STORE_UA from mygpo.users.models import Client import logging logger = logging.getLogger(__name__) def get_device(user, uid, user_agent, undelete=True): """ Loads or creates the device indicated by user, uid. ...
import uuid from django.db import transaction, IntegrityError from mygpo.users.settings import STORE_UA from mygpo.users.models import Client import logging logger = logging.getLogger(__name__) def get_device(user, uid, user_agent, undelete=True): """ Loads or creates the device indicated by user, uid. ...
Fix validation of Client objects
Fix validation of Client objects
Python
agpl-3.0
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
08ea2c257780f23cec5dfb923e80966fdf9c5ac8
IPython/zmq/zmqshell.py
IPython/zmq/zmqshell.py
import sys from subprocess import Popen, PIPE from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC class ZMQInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for ZMQ.""" def system(self, cmd): cmd = self.var_expand(cmd, depth=2) p = Popen(cmd, sh...
import sys from subprocess import Popen, PIPE from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC class ZMQInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for ZMQ.""" def system(self, cmd): cmd = self.var_expand(cmd, depth=2) sys.stdout.flush(...
Add flushing to stdout/stderr in system calls.
Add flushing to stdout/stderr in system calls.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
5a9bf08b78176097d918d0ec7174e68094ee63a2
Lib/test/test_binhex.py
Lib/test/test_binhex.py
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Roger E. Masse """ import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open...
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Roger E. Masse """ import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open...
Stop creating an unbounded number of "Jack is my hero" files under Windows. Not that Jack doesn't deserve them, but saying it so often cheapens the sentiment.
Stop creating an unbounded number of "Jack is my hero" files under Windows. Not that Jack doesn't deserve them, but saying it so often cheapens the sentiment.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
3b6ddce7c0db0f0b1fbd9febd9bf68ceeda51f44
della/user_manager/forms.py
della/user_manager/forms.py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator alphanumericu = RegexValidator( regex=r'^[0-9a-zA-Z_]*$', message='Only alphanumeric characters and underscore are allowed.') class Sig...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator alphanumericu = RegexValidator( regex=r'^[0-9a-zA-Z_]*$', message='Only alphanumeric characters and underscore are allowed.') class Sig...
Raise ValidationError properly in SignupForm
Raise ValidationError properly in SignupForm
Python
mit
avinassh/della,avinassh/della,avinassh/della
6f24dc967a082251d0bc62ab66c9263235174f9f
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/test_views.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/test_views.py
from django.core.urlresolvers import reverse from django.test import Client, TestCase from users.models import User class UserRedirectViewTestCase(TestCase): def setUp(self): self.client = Client() User.objects.create_user( username="testuser", email="test@example.com", ...
from django.core.urlresolvers import reverse from django.test import TestCase from users.models import User class UserRedirectViewTestCase(TestCase): def setUp(self): User.objects.create_user( username="testuser", email="test@example.com", password="testpass" ...
Remove unnecessary assignment to self.client in test cases.
Remove unnecessary assignment to self.client in test cases.
Python
bsd-3-clause
wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials
a696e9740920018d726c0c54987f6dc6ba2128d6
eppread.py
eppread.py
#!/usr/bin/env python # # Copyright (c) 2017 Ralf Horstmann <ralf@ackstorm.de> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PRO...
#!/usr/bin/env python # # Copyright (c) 2017 Ralf Horstmann <ralf@ackstorm.de> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PRO...
Improve printing of signature and version
Improve printing of signature and version
Python
isc
ra1fh/eppconvert
fb665cf8d6c0eb6c794a41eaf312c35473d1bdf0
tests/settings_complex.py
tests/settings_complex.py
from settings import * INSTALLED_APPS.append('complex') INSTALLED_APPS.append('django.contrib.comments') ROOT_URLCONF = 'complex.urls'
from settings import * INSTALLED_APPS += [ 'complex', 'django.contrib.comments', 'django.contrib.sites', ] ROOT_URLCONF = 'complex.urls'
Add sites app, change how installed_apps are edited.
Add sites app, change how installed_apps are edited.
Python
bsd-3-clause
esatterwhite/django-tastypie,beni55/django-tastypie,Eksmo/django-tastypie,SeanHayes/django-tastypie,cbxcube/bezrealitky.py,ywarezk/nerdeez-tastypie,mohabusama/django-tastypie,ocadotechnology/django-tastypie,ocadotechnology/django-tastypie,waveaccounting/django-tastypie,SeanHayes/django-tastypie,Eksmo/django-tastypie,be...
855ed8bcef8fc17655ccc28f70ce34a6b3b58d65
official/utils/misc/tpu_lib.py
official/utils/misc/tpu_lib.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Remove explicit initialize_tpu_system call from model garden.
Remove explicit initialize_tpu_system call from model garden. PiperOrigin-RevId: 290354680
Python
apache-2.0
tombstone/models,alexgorban/models,alexgorban/models,alexgorban/models,tombstone/models,tombstone/models,tombstone/models,tombstone/models,alexgorban/models,alexgorban/models,tombstone/models
345056a7a6a801013cdc340f0f9cd8b4f5d48173
convert-bookmarks.py
convert-bookmarks.py
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup from datetime import datetime, timezone from bson import json_util import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON...
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='...
Remove bson, datetime, and mongo
Remove bson, datetime, and mongo Current BSON fails to work datetime can't be serialized by json_util mongodb is not needed; just use JSON
Python
mit
jhh/netscape-bookmark-converter
05de6db4aab5f6705bb2867422fab5f7aca3a13a
thinglang/execution/builtins.py
thinglang/execution/builtins.py
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '....
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item.value) def __contains__(self, item): return hasattr(self, item.value) class ThingObjectOutput(ThingObjectBase): INTERNAL_NAME = "Output" def __init__(self, heap): self.data = [] sel...
Unify access in Pythonic built ins
Unify access in Pythonic built ins
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
7afedf19ff9dfcbf8872a7a9a6090c4ed235a206
phantasy/apps/__init__.py
phantasy/apps/__init__.py
# encoding: UTF-8 # # Copyright (c) 2015-2016 Facility for Rare Isotope Beams # """ Physics Applications """ from .latticemodel import lmapp from phantasy_apps import *
# encoding: UTF-8 # # Copyright (c) 2015-2016 Facility for Rare Isotope Beams # """ Physics Applications """ from .latticemodel import lmapp try: from phantasy_apps import * except ImportError: print("Package 'python-phantasy-apps' is required.")
Add warning if 'phantasy_apps' cannot be found.
Add warning if 'phantasy_apps' cannot be found.
Python
bsd-3-clause
archman/phantasy,archman/phantasy
73477dbb9176f7c71a1ce3bbab70313fb65578f8
uk_results/serializers.py
uk_results/serializers.py
from __future__ import unicode_literals from rest_framework import serializers from .models import PostResult, ResultSet, CandidateResult from candidates.serializers import ( MembershipSerializer, MinimalPostExtraSerializer ) class CandidateResultSerializer(serializers.HyperlinkedModelSerializer): class Met...
from __future__ import unicode_literals from rest_framework import serializers from .models import PostResult, ResultSet, CandidateResult from candidates.serializers import ( MembershipSerializer, MinimalPostExtraSerializer ) class CandidateResultSerializer(serializers.HyperlinkedModelSerializer): class Met...
Add review status to serializer
Add review status to serializer
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative