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 |
|---|---|---|---|---|---|---|---|---|---|
c04103b457040355da9dcf6a1059539bf6470092 | mutt-addressbook.py | mutt-addressbook.py | #!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
wi... | #!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
wi... | Rework string concatenation with join and format | Rework string concatenation with join and format
Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de>
| Python | isc | qsuscs/mutt-addressbook |
89a8cc53f2ad373eb8ff0508dbb5f111e6ee2b6e | nashvegas/models.py | nashvegas/models.py | from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=Tr... | from django.db import models
try:
from django.utils.timezone import now
except ImportError:
from datetime.datetime import now
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=now)
content = models.TextField()
sc... | Fix import error for Django 1.3.1 | Fix import error for Django 1.3.1
| Python | mit | paltman-archive/nashvegas,jonathanchu/nashvegas,iivvoo/nashvegas,dcramer/nashvegas,paltman/nashvegas |
292b4843fdb0efbf3cc8d7c97aaa8abd2cd22a28 | optimization/simple.py | optimization/simple.py | #!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)... | #!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE... | Use sum function to construct objective function. | Use sum function to construct objective function.
| Python | apache-2.0 | MiddelkoopT/CompOpt-2014-Fall,MiddelkoopT/CompOpt-2014-Fall |
432a7f72c790ca7ba18f4d575706461e337da593 | src/hunter/const.py | src/hunter/const.py | import os
import site
import stat
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKA... | import os
import site
import stat
import sys
import sysconfig
SITE_PACKAGES_PATHS = set()
for scheme in sysconfig.get_scheme_names():
for name in ['platlib', 'purelib']:
try:
SITE_PACKAGES_PATHS.add(sysconfig.get_path(name, scheme))
except KeyError:
pass
if hasattr(site, 'ge... | Use new method to get package paths that works without deprecations on Python 3.10 | Use new method to get package paths that works without deprecations on Python 3.10
| Python | bsd-2-clause | ionelmc/python-hunter |
88734c5aaf3bdddd1e41beff3bdb70b27590490c | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'p... | Add url leading to the archive page | Add url leading to the archive page
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
7a735bebf195f766a0db97b3fba6793a69a5731a | microcosm_elasticsearch/main.py | microcosm_elasticsearch/main.py | """
CLI entry point hook.
"""
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop"... | """
CLI entry point hook.
"""
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", act... | Add a query entry point | Add a query entry point
| Python | apache-2.0 | globality-corp/microcosm-elasticsearch,globality-corp/microcosm-elasticsearch |
9cf6e843eeb865eeaf90e4023bdccd1325e74535 | test_rle.py | test_rle.py | import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array(... | import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array(... | Add test for RLE decompression | Add test for RLE decompression
| Python | bsd-3-clause | ziotom78/polycomp |
a5e5cef7793c0692e556fc8c09e03af8ad33566a | mne/datasets/sample/__init__.py | mne/datasets/sample/__init__.py | # Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The da... | # Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The da... | FIX : in handling of sample dataset | FIX : in handling of sample dataset
| Python | bsd-3-clause | aestrivex/mne-python,agramfort/mne-python,leggitta/mne-python,yousrabk/mne-python,larsoner/mne-python,teonlamont/mne-python,antiface/mne-python,cjayb/mne-python,mne-tools/mne-python,kambysese/mne-python,lorenzo-desantis/mne-python,jmontoyam/mne-python,kingjr/mne-python,dimkal/mne-python,agramfort/mne-python,nicproulx/m... |
bea9d879d648853c5bd4c54bfa0ec3af857c7887 | ModuleInterface.py | ModuleInterface.py |
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, me... |
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
de... | Revert "[Core] Okay maybe this?" | Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.
| Python | mit | HubbeKing/Hubbot_Twisted |
8f247a0c4564af085bf6b3c9829d2892e818e565 | tools/update_manifest.py | tools/update_manifest.py | #!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:... | #!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:... | Add a symlink to downloaded manifest. | Add a symlink to downloaded manifest.
| Python | mit | zhirsch/destinykioskstatus,zhirsch/destinykioskstatus |
d6bb78235b8cec2ec65a4fb67641746565f77c20 | normandy/selfrepair/tests/test_views.py | normandy/selfrepair/tests/test_views.py | from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.djan... | from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.djan... | Test that self-repair endpoint does not set cookies | Test that self-repair endpoint does not set cookies
| Python | mpl-2.0 | mozilla/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy |
78915664179c4c2b3fc974fcf54cfe253689c154 | zinnia/tests/__init__.py | zinnia/tests/__init__.py | """Unit tests for Zinnia"""
from zinnia.signals import disconnect_entry_signals
from zinnia.signals import disconnect_discussion_signals
disconnect_entry_signals()
disconnect_discussion_signals()
| """Unit tests for Zinnia"""
| Remove disconnection of the signals when loading the zinnia.tests modules for compatibility | Remove disconnection of the signals when loading the zinnia.tests modules for compatibility
| Python | bsd-3-clause | petecummings/django-blog-zinnia,bywbilly/django-blog-zinnia,ghachey/django-blog-zinnia,extertioner/django-blog-zinnia,1844144/django-blog-zinnia,Fantomas42/django-blog-zinnia,1844144/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,marctc/django-blog-zinnia,Zopieux/django-blog-zinnia,Maplecrof... |
e4a7e8dea024a51036d66e2a357e83e7c085430e | opps/channels/tests/__init__.py | opps/channels/tests/__init__.py | # -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
| # -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
from opps.channels.tests.test_forms import *
| Add channel forms test in test case | Add channel forms test in test case
| Python | mit | jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,williamroot/opps |
d8b9dec51e3d01fb662ed1bc779d06fe9f723cb5 | openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py | openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py | """
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps... | """
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps... | Update this command for Django 1.8 | Update this command for Django 1.8
| Python | agpl-3.0 | louyihua/edx-platform,itsjeyd/edx-platform,solashirai/edx-platform,alu042/edx-platform,procangroup/edx-platform,Edraak/edraak-platform,jjmiranda/edx-platform,raccoongang/edx-platform,TeachAtTUM/edx-platform,jolyonb/edx-platform,raccoongang/edx-platform,shabab12/edx-platform,hastexo/edx-platform,eduNEXT/edunext-platform... |
bea572a086a9d8390a8e5fce5a275b889fa52338 | pymetabiosis/test/test_numpy_convert.py | pymetabiosis/test/test_numpy_convert.py | from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
numpy = import_module("numpy")
assert numpy.bool_(True) is True
assert numpy.bool_(Fals... | import pytest
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest... | Make sure numpy exists on the cpython side | Make sure numpy exists on the cpython side
| Python | mit | prabhuramachandran/pymetabiosis,rguillebert/pymetabiosis |
68f50e83f4b06d3e45bfe1610d50d88e73bde8af | examples/load_table_from_url.py | examples/load_table_from_url.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import io
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_framewo... | Fix for python 2 compatibility | Fix for python 2 compatibility
| Python | mit | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader |
78c70c0bdcf3b264cf522136ae35bc1ec5b12b62 | tests/test_basic.py | tests/test_basic.py | import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/CountWords/']
pubrunner.command_line.main()
def test_textminingcounter():
#pubrunner.pubrun('examples/CountWords/',T... | import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
def test_textminin... | Use absolute path for running tests | Use absolute path for running tests
| Python | mit | jakelever/pubrunner,jakelever/pubrunner |
80676409b706f3927b463afef6aa844d00aeb107 | pymatgen/core/__init__.py | pymatgen/core/__init__.py | """
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .l... | """
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .l... | Add units to Core import. | Add units to Core import.
| Python | mit | migueldiascosta/pymatgen,Bismarrck/pymatgen,sonium0/pymatgen,ctoher/pymatgen,Bismarrck/pymatgen,migueldiascosta/pymatgen,sonium0/pymatgen,migueldiascosta/pymatgen,yanikou19/pymatgen,Bismarrck/pymatgen,rousseab/pymatgen,Bismarrck/pymatgen,rousseab/pymatgen,rousseab/pymatgen,sonium0/pymatgen,yanikou19/pymatgen,Dioptas/py... |
900fa2acbdb4cde05ab26cb134d95870d68ce004 | salt/states/host.py | salt/states/host.py | '''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = Tr... | '''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = Tr... | Clean up strings to use format and add better comments | Clean up strings to use format and add better comments
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
f1d48525f1e8cde2af9a49636f38360b87b0ecb6 | function/univariate_function.py | function/univariate_function.py | """
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abst... | """
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abst... | Add comments to abstract methods. | Add comments to abstract methods.
| Python | mit | dpazel/music_rep |
bea0006566cb5512f1ae515689111339be27e42b | tk/material/apps.py | tk/material/apps.py | from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated title... | from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated title... | Change current language only within context when building search indexes | Change current language only within context when building search indexes
| Python | agpl-3.0 | GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa |
a6754051ced2763065007b765d5d523fe8c65835 | src/epiweb/urls.py | src/epiweb/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?... | from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?... | Add URLs to profile app. | Add URLs to profile app.
| Python | agpl-3.0 | ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website |
d23a2647f9313a49c9c552d90a2d57a26173b232 | tools/dump_redis.py | tools/dump_redis.py | #!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
... | #!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
... | Add : Load for redis | Add : Load for redis
| Python | agpl-3.0 | savoirfairelinux/mod-booster-snmp,savoirfairelinux/mod-booster-snmp,savoirfairelinux/mod-booster-snmp |
7c3cf9e430bee4451e817ccc3d32884ed0c5f8e9 | bakeit/uploader.py | bakeit/uploader.py | try:
from urllib.request import urlopen, Request, HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = a... | try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
... | Fix Python3 error when decoding the response. | fix: Fix Python3 error when decoding the response.
| Python | mit | skorokithakis/bakeit |
6e3bd2f5460049c9702bf44b37095c635ad8460b | smartfile/errors.py | smartfile/errors.py | import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args,... | import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args,... | Fix error handling to catch if JSON is not returned | Fix error handling to catch if JSON is not returned
| Python | mit | smartfile/client-python |
e2c53b348a69093cc770ba827a6bdd5191f2a830 | aldryn_faq/cms_toolbar.py | aldryn_faq/cms_toolbar.py | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolb... | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(... | Add ability to create question from toolbar | Add ability to create question from toolbar
| Python | bsd-3-clause | czpython/aldryn-faq,mkoistinen/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq |
b33fcfe3752caeb61a83eb04c3b8399b7c44c9a4 | sylvia/__init__.py | sylvia/__init__.py | from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
| import sys
if sys.version_info[0] > 2:
raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." )
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole impo... | Add meaningful error for runnign with Python3 | Add meaningful error for runnign with Python3
If we detect a Python3 interpreter at module init, tell the user to
use Python 2. And be sure to apologize because it's 2019...
| Python | mit | bgutter/sylvia |
71de95f9a2ea9e48d30d04897e79b025b8520775 | bfg9000/shell/__init__.py | bfg9000/shell/__init__.py | import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(... | import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(... | Clean up the shell execute() function | Clean up the shell execute() function
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 |
c8e57ffc08f89111bb628bdfa6114a76672e73b1 | chmvh_website/gallery/signals.py | chmvh_website/gallery/signals.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import create_thumbnail, process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def send_notifications(sender, instance, *args, **kwargs):
""" Notify users that a reply has been posted """
p... | from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def process_picture(sender, instance, update_fields, *args, **kwargs):
"""
Process a patients picture.
This involves checki... | Fix infinite loop when processing pictures. | Fix infinite loop when processing pictures.
| Python | mit | cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website |
699279fe19c20e200db91e032c97b3f0b644c2af | conllu/__init__.py | conllu/__init__.py | from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def _i... | from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def par... | Move helper to end of module and remove double spaces. | Move helper to end of module and remove double spaces.
| Python | mit | EmilStenstrom/conllu |
c305632eb916332802fa5229e6f739f4ad74f686 | ptpython/config.py | ptpython/config.py | __all__ = ('configure')
def configure(repl):
repl.vi_mode = True
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
| __all__ = ('configure')
def configure(repl):
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
| Disable vim mode in ptpython. Works meh | Disable vim mode in ptpython. Works meh
| Python | mit | mpardalos/dotfiles,mpardalos/dotfiles |
13f9a48166aed2f6d09e1a27c60568d2318ceee2 | src/ocspdash/custom_columns.py | src/ocspdash/custom_columns.py | # -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise us... | # -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise us... | Change the custom UUID column to work right | Change the custom UUID column to work right
| Python | mit | scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash |
053d4599dbb70664cb9f4e9c5b620b39733c254d | nova_powervm/conf/__init__.py | nova_powervm/conf/__init__.py | # Copyright 2016 IBM Corp.
#
# 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 a... | # Copyright 2016 IBM Corp.
#
# 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 a... | Support new conf refactor from Nova | Support new conf refactor from Nova
The core nova project is consolidating their conf options. This
impacted the PowerVM conf options as a few that we were explicitly
importing were moved.
This change set fixes the issue and allows PowerVM to work properly.
The change actually removes the imports, but they are stil... | Python | apache-2.0 | openstack/nova-powervm,openstack/nova-powervm,stackforge/nova-powervm,stackforge/nova-powervm |
8fafef4c2151d17133c5787847d68ab4b58f40c3 | stagecraft/libs/views/utils.py | stagecraft/libs/views/utils.py | import json
from django.utils.cache import patch_response_headers
from functools import wraps
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
... | import json
from django.utils.cache import patch_response_headers
from functools import wraps
from uuid import UUID
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return '{}'.format(obj)
if hasattr(obj, 'serialize'):
return obj.seri... | Extend JSON serialiser to use serialize() method | Extend JSON serialiser to use serialize() method
If an object is a UUID, return a string representation of it.
If the object still can't be serialised, call its serialize() method.
This is useful when nesting Link models inside dashboards, for
example.
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft |
be51fddd326975047b7e60227072f5df80eadbad | conf_site/accounts/tests/factories.py | conf_site/accounts/tests/factories.py | # -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class M... | # -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class M... | Fix race condition involving account usernames. | Fix race condition involving account usernames.
Fix race condition causing random test failures by using get_or_create
on generated usernames. See https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site |
115771e1917bd40989cc70762225fd3c6e0a565b | test/test_parser.py | test/test_parser.py | import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
... | import bz2
import gzip
import os
import re
import shutil
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position... | Add test for parsing different file types | Add test for parsing different file types
- Add tests for bzip, gzip and normal files to parser tests.
| Python | apache-2.0 | apel/apel,tofu-rocketry/apel,apel/apel,tofu-rocketry/apel,stfc/apel,stfc/apel |
401d5d3e676bdeeb067977b8506e420262d8be05 | tests/test_memes.py | tests/test_memes.py | from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(sel... | from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(sel... | Remove origin from meme model | Remove origin from meme model
| Python | mit | jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dalli... |
1b103d314e94e3c1dba9d9d08a2655c62f26d18c | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
291d26c5563307e33f7a4aaee406b75c4b8c591a | tulip/tasks_test.py | tulip/tasks_test.py | """Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_... | """Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_... | Test for sleep(dt) without extra arg. | Test for sleep(dt) without extra arg.
| Python | apache-2.0 | gvanrossum/asyncio,gsb-eng/asyncio,gsb-eng/asyncio,manipopopo/asyncio,gvanrossum/asyncio,haypo/trollius,gsb-eng/asyncio,vxgmichel/asyncio,ajdavis/asyncio,fallen/asyncio,jashandeep-sohi/asyncio,haypo/trollius,vxgmichel/asyncio,jashandeep-sohi/asyncio,gvanrossum/asyncio,Martiusweb/asyncio,ajdavis/asyncio,manipopopo/async... |
8832144b3fe0b1e227ebd02b2b3cf8ea5cbcb386 | introductions/__init__.py | introductions/__init__.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True... | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.con... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/introductions-alpha,LandRegistry/introductions-alpha,LandRegistry/introductions-alpha |
67be3c3e8ac89f3d8ce36aece39b0bd67fb8fd08 | src/testers/tls.py | src/testers/tls.py | # -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test... | # -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def... | Fix missing parentheses in exception | Fix missing parentheses in exception
| Python | mit | stampery/mongoaudit |
e018f35e51712e4d6a03f5b31e33f61c03365538 | profiles/views.py | profiles/views.py | from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from ... | from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from ... | Order content on profile by most recent. | Order content on profile by most recent.
| Python | mit | ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest |
9b8a223dc45f133851fac2df564c2c058aafdf91 | scripts/index.py | scripts/index.py | from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
... | from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, ... | Use pathlib for path segmentation | Use pathlib for path segmentation
| Python | mit | yeonghoey/notes,yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/yeonghoey |
f2e410492aaaad59fca83d313ec673c1fb411e44 | astral/api/tests/test_node.py | astral/api/tests/test_node.py | from nose.tools import eq_
from tornado.httpclient import HTTPRequest
import uuid
from astral.api.tests import BaseTest
from astral.models.node import Node
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = Node(uuid=uuid.getnode())
self.http_client.fetch(HTTPRequest(
... | from nose.tools import eq_
from tornado.httpclient import HTTPRequest
from astral.api.tests import BaseTest
from astral.models import Node
from astral.models.tests.factories import NodeFactory
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = NodeFactory()
self.http_client.fetch(... | Build proper Node in tests after refactoring constructor. | Build proper Node in tests after refactoring constructor.
| Python | mit | peplin/astral |
da98272c3b19828dabbbb339f025c9d3dd4a949e | relay_api/core/relay.py | relay_api/core/relay.py | import RPi.GPIO as GPIO
class relay():
def __init__(self, gpio_num):
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
... | import RPi.GPIO as GPIO
MAX_RELAY_GPIO = 27
class relay():
def __init__(self, gpio_num):
if gpio_num not in range(MAX_RELAY_GPIO + 1):
raise LookupError("Relay GPIO invalid! Use one between 0 - " +
str(MAX_RELAY_GPIO))
self.gpio = gpio_num
GPIO.s... | Change the way that GPIO is verified | Change the way that GPIO is verified
| Python | mit | pahumadad/raspi-relay-api |
66137ab7cc8a0736bbf52a6ded49fd5661ddb68b | test/test_files.py | test/test_files.py | import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb https://apt.dockerproject.org/repo"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-cl... | import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb \[arch=amd64\] https://download.docker.com/linux/ubuntu"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/us... | Update for new docker install | Update for new docker install
| Python | mit | wicksy/CV,wicksy/CV,wicksy/CV |
2c62c7f063af02f6872edd2801c6700bfffeebd4 | cloud_browser/cloud/config.py | cloud_browser/cloud/config.py | """Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection
class Config(object):
"""Cloud configuration helper."""
conn_cls = RackspaceConnection
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@clas... | """Cloud configuration."""
class Config(object):
"""Cloud configuration helper."""
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or envir... | Refactor to allow different connection class bindings. | Config: Refactor to allow different connection class bindings.
| Python | mit | ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,UrbanDaddy/django-cloud-browser,UrbanDaddy/django-cloud-browser |
3be2d3031f878232f38f692b186ea5699b1586ef | tm/tmux_wrapper.py | tm/tmux_wrapper.py | # -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist... | # -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist... | Add CommandResponse class to use instead of (out, err) tuple | Add CommandResponse class to use instead of (out, err) tuple
| Python | mit | ethanal/tm |
3277de26d239d5c0420df575b36cb065c033e4ed | massa/container.py | massa/container.py | # -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
... | # -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
... | Define the log level of the logger instead of the handler. | Define the log level of the logger instead of the handler. | Python | mit | jaapverloop/massa |
08ecc9aaf3398a0dd69bf27fc65c8ca744f98e4b | Orange/tests/test_naive_bayes.py | Orange/tests/test_naive_bayes.py | import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ... | import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
... | Improve naive bayes unit test. | Improve naive bayes unit test.
| Python | bsd-2-clause | cheral/orange3,qusp/orange3,qPCR4vir/orange3,cheral/orange3,qusp/orange3,qusp/orange3,cheral/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,kwikadi/orange3,marinkaz/orange3,qPCR... |
9704602f26b4a9aab15caf00795d283c5f6e4ae4 | src/fiona/tool.py | src/fiona/tool.py | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... | Change record output to strict GeoJSON. | Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.
| Python | bsd-3-clause | rbuffat/Fiona,Toblerity/Fiona,sgillies/Fiona,johanvdw/Fiona,perrygeo/Fiona,Toblerity/Fiona,perrygeo/Fiona,rbuffat/Fiona |
5875baf754d3bcc911f828fc3ecb302ac6da967f | tagcache/lock.py | tagcache/lock.py | # -*- encoding: utf-8 -*-
import os
import fcntl
from tagcache.utils import open_file
class FileLock(object):
def __init__(self, path):
self.path = path
self.fd = None
def acquire(self, ex=False, nb=False):
"""
Acquire a lock on a path.
:param ex (optional): defa... | # -*- encoding: utf-8 -*-
import os
import fcntl
from tagcache.utils import open_file
class FileLock(object):
def __init__(self, path):
self.path = path
self.fd = None
@property
def is_acquired(self):
return self.fd is not None
def acquire(self, ex=False, nb=False):
... | Add `is_acquired` property to FileLock | Add `is_acquired` property to FileLock
| Python | mit | huangjunwen/tagcache |
a56108990e2cda8694f7b5c4fe3c615966c4cd6c | python/powers_of_two.py | python/powers_of_two.py | def powers_of_two(limit):
value = 1
while value < limit:
yield value
value += value
# Use the generator
for i in powers_of_two(70):
print(i)
# Explore the mechanism
print(type(powers_of_two)) # <class 'function'>
g = powers_of_two(100)
print(type(g)) # <class 'generator'>
pri... | def powers_of_two(limit):
value = 1
while value < limit:
yield value
value += value
# Use the generator
for i in powers_of_two(70):
print(i)
# Explore the mechanism
g = powers_of_two(100)
assert(str(type(powers_of_two)) == "<class 'function'>")
assert(str(type(g)) == "<class 'generator'>")... | Use asserts instead of prints | Use asserts instead of prints
| Python | mit | rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,... |
55a1f6197800249b3ad13ec7c5358e907ea04c46 | comics/comics/treadingground.py | comics/comics/treadingground.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Treading Ground'
language = 'en'
url = 'http://www.treadingground.com/'
start_date = '2003-10-12'
rights = 'Nick Wright'
class Crawler(CrawlerBase):
history_capab... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Treading Ground'
language = 'en'
url = 'http://www.treadingground.com/'
start_date = '2003-10-12'
rights = 'Nick Wright'
class Crawler(CrawlerBase):
schedule = No... | Remove schedule for ended comic | Remove schedule for ended comic
| Python | agpl-3.0 | klette/comics,datagutten/comics,klette/comics,jodal/comics,datagutten/comics,klette/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics |
0795ffe195798461961fc41329fb7df30ec429c3 | lisa/server/tests/test_plugins.py | lisa/server/tests/test_plugins.py | from lisa.server.plugins.PluginManager import PluginManagerSingleton
from twisted.trial import unittest
import json
class LisaClientTestCase_Plugin(unittest.TestCase):
def setUp(self):
self.pluginManager = PluginManagerSingleton.get()
def test_a_install_plugin(self):
answer = self.pluginManag... | from lisa.server.plugins.PluginManager import PluginManagerSingleton
from twisted.trial import unittest
import json
class LisaClientTestCase_Plugin(unittest.TestCase):
def setUp(self):
self.pluginManager = PluginManagerSingleton.get()
def test_a_install_plugin(self):
answer = self.pluginManag... | Test with a dedicated plugin now | Test with a dedicated plugin now
| Python | mit | Seraf/LISA,Seraf/LISA,Seraf/LISA,Seraf/LISA |
d4fc34ea4635ee4ec294e1eb52fcd83174dd52c5 | steve/_version.py | steve/_version.py | #######################################################################
# This file is part of steve.
#
# Copyright (C) 2012 Will Kahn-Greene
#
# steve 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 ve... | #######################################################################
# This file is part of steve.
#
# Copyright (C) 2012 Will Kahn-Greene
#
# steve 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 ve... | Add version number notes; set to dev | Add version number notes; set to dev
| Python | bsd-2-clause | willkg/steve,pyvideo/steve,CarlFK/steve,willkg/steve,pyvideo/steve,CarlFK/steve,willkg/steve,CarlFK/steve,pyvideo/steve |
5487126bfc3c4fd16243b9c7e00b204f2f8d7374 | tests/test_znc.py | tests/test_znc.py | def test_service_running(Service):
service = Service('znc')
assert service.is_running
def test_socket_listening(Socket):
socket = Socket('tcp://127.0.0.1:6666')
assert socket.is_listening
| from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all')
def test_service_enabled(Service):
service = Service('znc')
assert service.is_enabled
def test_service_running(Service):
service = Service('znc')
assert service.i... | Tweak the infratest a bit | Tweak the infratest a bit
| Python | mit | triplepoint/ansible-znc |
0dd9fba16a73954a3bbb18c5b2de9995c07ef56f | pushbullet/filetype.py | pushbullet/filetype.py | def _magic_get_file_type(f, _):
file_type = magic.from_buffer(f.read(1024), mime=True)
f.seek(0)
return file_type
def _guess_file_type(_, filename):
return mimetypes.guess_type(filename)[0]
try:
import magic
except ImportError:
import mimetypes
get_file_type = _guess_file_type
else:
... | def _magic_get_file_type(f, _):
file_type = magic.from_buffer(f.read(1024), mime=True)
f.seek(0)
return file_type.decode("ASCII")
def _guess_file_type(_, filename):
return mimetypes.guess_type(filename)[0]
try:
import magic
except ImportError:
import mimetypes
get_file_type = _guess_file... | Fix libmagic issue with Python 3 | Fix libmagic issue with Python 3
| Python | mit | kovacsbalu/pushbullet.py,randomchars/pushbullet.py,Saturn/pushbullet.py |
bb897662f7f3fc17b32ffd06962fa5cb582fb6d7 | easytz/middleware.py | easytz/middleware.py | from django.conf import settings
from django.utils import timezone
from pytz import UnknownTimeZoneError
from .models import TimezoneStore
class TimezonesMiddleware(object):
def process_request(self, request):
"""
Attempts to activate a timezone from a cookie or session
"""
if get... | from django.conf import settings
from django.utils import timezone
from pytz import UnknownTimeZoneError
from .models import TimezoneStore
class TimezonesMiddleware(object):
def process_request(self, request):
"""
Attempts to activate a timezone from a cookie or session
"""
if get... | Set the timezone right after it gets activated. | Set the timezone right after it gets activated.
| Python | apache-2.0 | jamesmfriedman/django-easytz |
c035b951d85ffc60598968ca5a277afc416446a3 | pylinks/main/models.py | pylinks/main/models.py | from django.db import models
from django.contrib.sites.models import Site
class DatedModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True, null=True)
updated_time = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'updated_ti... | from django.db import models
from django.contrib.sites.models import Site
class DatedModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True, null=True)
updated_time = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'updated_ti... | Clear sites cache on SiteInfo save | Clear sites cache on SiteInfo save
| Python | mit | michaelmior/pylinks,michaelmior/pylinks,michaelmior/pylinks |
e3aa2ca9d9fb74de6512acd04c509a41c176040a | pdc/apps/repository/filters.py | pdc/apps/repository/filters.py | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters as filters
from pdc.apps.common.filters import MultiValueFilter
from . import models
class RepoFilter(filters.FilterSet):
arch = MultiValueFilter(name='variant_arch__arch__name')
... | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters as filters
from pdc.apps.common.filters import MultiValueFilter, MultiIntFilter
from . import models
class RepoFilter(filters.FilterSet):
arch = MultiValueFilter(name='variant_arch__... | Fix product_id filter on content delivery repos | Fix product_id filter on content delivery repos
The value should be an integer.
JIRA: PDC-1104
| Python | mit | release-engineering/product-definition-center,release-engineering/product-definition-center,lao605/product-definition-center,lao605/product-definition-center,product-definition-center/product-definition-center,pombredanne/product-definition-center,xychu/product-definition-center,xychu/product-definition-center,pombreda... |
ba8231787a6f464ee946feaea9d853ee24894478 | eJRF/snap-ci/snap-settings.py | eJRF/snap-ci/snap-settings.py | DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "app_test",
"USER": "go",
"PASSWORD": "go",
"HOST": "localhost",
}
}
LETTUCE_AVOID_APPS = (
'south',
'django_nose',
'lettuce.django',
'django_extensions... | import os
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "app_test",
"USER": "go",
"PASSWORD": "go",
"HOST": "localhost",
}
}
LETTUCE_AVOID_APPS = (
'south',
'django_nose',
'lettuce.django',
'django... | Revert "also removing the un-needed import" | Revert "also removing the un-needed import"
This reverts commit 483a88a2c707a3e5d44b9db83c2a7d2184f9acff.
| Python | bsd-3-clause | eJRF/ejrf,eJRF/ejrf,eJRF/ejrf,eJRF/ejrf |
5c41286666290c2a067c51b7ab9ea171e4657d69 | fb/models.py | fb/models.py | from django.db import models
# Create your models here.
| from django.db import models
class UserPost(models.Model):
text = models.TextField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
author = models.CharField(default='Eau De Web', max_length=20)
def __unicode__(self):
return '{} @ {}'.format(self.author, self.date_added)
| Write a model class for user posts. | Write a model class for user posts.
| Python | apache-2.0 | pure-python/brainmate |
3c0ebc1a8e5a3d626a53eb94fb80c9466b46ee59 | rplugin/python/vimp.py | rplugin/python/vimp.py | import neovim
@neovim.plugin
class VimpBuffers(object):
def __init__(self, vim):
self.vim = vim
@neovim.command("ToggleTerminalBuffer")
def toggle_terminal_buffer(self):
current_buffer = self.vim.current.buffer
# find the currently open terminal and close it
for idx, windo... | import neovim
import os
from datetime import datetime
@neovim.plugin
class VimpBuffers(object):
def __init__(self, vim):
self.vim = vim
@neovim.command("ToggleTerminalBuffer")
def toggle_terminal_buffer(self):
current_buffer = self.vim.current.buffer
# find the currently open term... | Add command to quickly open a notes file | Add command to quickly open a notes file
| Python | mit | vpetro/vimp |
68f25d536945e06fae814bdf19218bc148f6cc93 | backend/scripts/updatedf.py | backend/scripts/updatedf.py | #!/usr/bin/env python
#import hashlib
import os
def main():
for root, dirs, files in os.walk("/mcfs/data/materialscommons"):
for f in files:
print f
if __name__ == "__main__":
main()
| #!/usr/bin/env python
import hashlib
import os
import rethinkdb as r
def main():
conn = r.connect('localhost', 28015, db='materialscommons')
for root, dirs, files in os.walk("/mcfs/data/materialscommons"):
for f in files:
path = os.path.join(root, f)
with open(path) as fd:
... | Update script to write results to the database. | Update script to write results to the database.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
2844589a64ae8998b03cc1e3be7fee232618d9e9 | test/txn_tests.py | test/txn_tests.py | from __future__ import absolute_import
import captable
import unittest
import datetime
from ._helpers import StubTransaction
class TransactionTests(unittest.TestCase):
"""Test adding transactions and processing them"""
def setUp(self):
"""Initialize a blank captable and authorize multiple classes of... | from __future__ import absolute_import
import captable
import unittest
import datetime
from ._helpers import StubTransaction
class TransactionTests(unittest.TestCase):
"""Test adding transactions and processing them"""
def setUp(self):
"""Initialize a blank captable and authorize multiple classes of... | Test transaction list in table is ordered | Test transaction list in table is ordered
| Python | mit | fongandrew/captable.py |
04fa3a9fd61cc83c23ddd59ea474bd45cd2a1e8c | tests/__init__.py | tests/__init__.py | # coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
from os.path import join, realpath
import fs
# Add the local code directory to the `fs` module path
fs.__path__.insert(0, realpath(join(__file__, "..", "..", "fs")))
| # coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
from os.path import join, realpath
import fs
# Add the local code directory to the `fs` module path
# Can only rely on fs.__path__ being an iterable - on windows it's not a list
newPath = list(fs.__path__)
newPath.insert(... | Make namespace packages work for tests in windows | Make namespace packages work for tests in windows
| Python | mit | rkhwaja/fs.onedrivefs |
3bcc646e1120e69a9aab412e22a4f85cce4da7bf | hashtable.py | hashtable.py | # Write hashtable class that stores strings in a hash table where keys are calculated using the first two letters of the string
class HashTable(object):
def __init__(self):
self.table = [None]*10000
def store(self, string):
hash_value = self.calculate_hash_value(string)
if hash_value != -1:
if self.table[h... | # Write hashtable class that stores strings in a hash table where keys are calculated using the first two letters of the string
class HashTable(object):
def __init__(self):
self.table = [None]*10000
def store(self, string):
hash_value = self.calculate_hash_value(string)
if hash_value != -1:
if self.table[h... | Add calculate hash value method | Add calculate hash value method
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
fba8f3a2595ebb032e86c09710ef4757ae87c428 | heppy/modules/rgp.py | heppy/modules/rgp.py | from ..Module import Module
from ..TagData import TagData
class rgp(Module):
opmap = {
'infData': 'descend',
}
def parse_rgpStatus(self, response, tag):
status = tag.attrib['s']
response.set(status, tag.text)
def render_default(self, request, data):
ext = self.re... | from ..Module import Module
from ..TagData import TagData
class rgp(Module):
opmap = {
'infData': 'descend',
}
def parse_rgpStatus(self, response, tag):
status = tag.attrib['s']
response.set(status, tag.text)
def render_default(self, request, data):
ext = self.re... | Add RGP request and report | Add RGP request and report
| Python | bsd-3-clause | hiqdev/reppy |
33d8e9ce8be2901dab5998192559b0e1c3408807 | kikola/core/context_processors.py | kikola/core/context_processors.py | def path(request):
"""
kikola.core.context_processors.path
===================================
Adds current path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Djan... | def path(request):
"""
Adds current absolute URI, path and full path variables to templates.
To enable, adds ``kikola.core.context_processors.path`` to your project's
``settings`` ``TEMPLATE_CONTEXT_PROCESSORS`` var.
**Note:** Django has ``django.core.context_processors.request`` context
proce... | Make ``path`` context processor return request absolute URI too. | Make ``path`` context processor return request absolute URI too.
| Python | bsd-3-clause | playpauseandstop/kikola |
730c7e6982f737c166924e1cae73eb34024fc4ef | AWSLambdas/vote.py | AWSLambdas/vote.py | """
Watch Votes stream and update Sample ups and downs
"""
import json
import boto3
import time
import decimal
import base64
from boto3.dynamodb.conditions import Key, Attr
def consolidate_disposition(disposition_map, records):
for record in records:
type = record['eventName']
disposition = 0
... | """
Watch Votes stream and update Sample ups and downs
"""
import json
import boto3
import time
import decimal
import base64
from boto3.dynamodb.conditions import Key, Attr
from decimal import Decimal
def consolidate_disposition(disposition_map, records):
for record in records:
type = record['even... | Update the ups and downs members of the Samples items. | Update the ups and downs members of the Samples items.
| Python | mit | SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup |
6373e170c77079e304435d4c2e68201e29a7ecce | python/torque-and-development.py | python/torque-and-development.py |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the roadsAndLibraries function below.
def roadsAndLibraries(n, c_lib, c_road, cities):
print("n {}, c_lib {}, c_road {}, cities {}".format(n, c_lib, c_road, cities))
return 0
if __name__ == '__main__':
fptr = open(os.envi... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Note the name of the file is based on this URL:
# https://www.hackerrank.com/challenges/torque-and-development/problem
# The problem name is "Roads and Libraries"
def roadsAndLibraries(n, c_lib, c_road, cities):
print("n {}, c_lib {}, c_r... | Include dev comment explaing filename | Include dev comment explaing filename
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
cfffc18c5179a441c0412f313e20a1b3b7059f1c | dump_contributors.py | dump_contributors.py | import requests
url = "https://api.github.com/repos/urschrei/pyzotero/contributors"
result = requests.get(url)
result.raise_for_status()
as_dict = result.json()
# remove me from the list
as_dict.pop(0)
header = "# This is the list of people (as distinct from [AUTHORS](AUTHORS)) who have contributed code to Pyzotero.\n\... | # -*- coding: utf-8 -*-
import io
import requests
url = "https://api.github.com/repos/urschrei/pyzotero/contributors"
result = requests.get(url)
result.raise_for_status()
as_dict = result.json()
# remove me from the list
as_dict.pop(0)
header = u"# This is the list of people (as distinct from [AUTHORS](AUTHORS)) who ... | Make contributor dump a bit more robust | Make contributor dump a bit more robust
| Python | mit | urschrei/pyzotero |
88bf90d2949da603567e75f2492e5880b2ff8009 | build_scripts/rename_wheels.py | build_scripts/rename_wheels.py | # renames ABI string in wheels from cp34m or cp35m to none
import os
for file in os.listdir('../dist'):
if '-cp34m-' in file:
file_parts = file.split('-cp34m-')
os.rename('../dist/{}'.format(file),
'../dist/{}-none-{}'.format(file_parts[0], file_parts[1]))
elif '-cp35m-' in f... | # renames ABI string in wheels from cp34m, cp35m, cp36m to none
import os
for file in os.listdir('../dist'):
if '-cp34m-' in file:
file_parts = file.split('-cp34m-')
os.rename('../dist/{}'.format(file),
'../dist/{}-none-{}'.format(file_parts[0], file_parts[1]))
elif '-cp35m-'... | Add support for python 3.5 and 3.6 | Add support for python 3.5 and 3.6
| Python | mit | missionpinball/mpf-mc,missionpinball/mpf-mc,missionpinball/mpf-mc |
15a5e861e63fa5b2662968ce4296c75ecfadee50 | iscc_bench/readers/__init__.py | iscc_bench/readers/__init__.py | # -*- coding: utf-8 -*-
from iscc_bench.readers.bxbooks import bxbooks
ALL_READERS = (bxbooks,)
| # -*- coding: utf-8 -*-
from iscc_bench.readers.bxbooks import bxbooks
from iscc_bench.readers.harvard import harvard
ALL_READERS = (bxbooks, harvard)
| Add harvard reader to ALL_READERS | Add harvard reader to ALL_READERS
| Python | bsd-2-clause | coblo/isccbench |
ae260be14e575d9678bd20e94c44c70beb182848 | twitterexample.py | twitterexample.py | import json
from urllib2 import urlopen
import micromodels
class TwitterUser(micromodels.Model):
id = micromodels.IntegerField()
screen_name = micromodels.CharField()
name = micromodels.CharField()
description = micromodels.CharField()
def get_profile_url(self):
return 'http://twitter.com... | import json
from urllib2 import urlopen
import micromodels
class TwitterUser(micromodels.Model):
id = micromodels.IntegerField()
screen_name = micromodels.CharField()
name = micromodels.CharField()
description = micromodels.CharField()
def get_profile_url(self):
return 'http://twitter.com... | Add created_at DateTimeField to Twitter example | Add created_at DateTimeField to Twitter example
| Python | unlicense | j4mie/micromodels |
a69edf3e488125067371a96626b7f3cd45e9a11f | inventory.py | inventory.py | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = ... | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = ... | Add try for catching server error | Add try for catching server error
| Python | mit | lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory |
6021c4c54cb0a437878553a1e23f8d433476ff2d | main.py | main.py | import json
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
search_results = ObjectProperty()
def search_location(self):
... | import json
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
search_results = ObjectProperty()
def search_location(self):
... | Stop crashing when search doesn't have any matches | Stop crashing when search doesn't have any matches
| Python | mit | ciappi/Weather |
9605a14372aaf2ad4315bad11053839cfe75e50e | main.py | main.py | """
St. George Game
main.py
Sage Berg, Skyler Berg
Created: 5 Dec 2014
"""
import places
from character import Character
from display import Display
from actions import AskAboutAssassins, BuyADrink, LeaveInAHuff, SingASong
def main():
display = Display()
display.enable()
character = Character()
chara... | """
St. George Game
main.py
Sage Berg, Skyler Berg
Created: 5 Dec 2014
"""
import places
from character import Character
from display import Display
from actions import AskAboutAssassins, BuyADrink, LeaveInAHuff, SingASong
def main():
display = Display()
display.enable()
character = Character()
chara... | Set previous action after executing | Set previous action after executing
| Python | apache-2.0 | SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame |
80933f496ef57abe7335fd9490acf4a1f4a53648 | nose2/tests/functional/test_coverage.py | nose2/tests/functional/test_coverage.py | from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
stdout, stderr = proc.communicate()
... | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... | Make test also work on Windows that uses backslash as path delimiter | Make test also work on Windows that uses backslash as path delimiter
| Python | bsd-2-clause | little-dude/nose2,little-dude/nose2,ezigman/nose2,ezigman/nose2,ojengwa/nose2,ptthiem/nose2,ptthiem/nose2,ojengwa/nose2 |
8ba03f6be64ee12634183e0b5c5f3aa3b6014b94 | linguine/ops/StanfordCoreNLP.py | linguine/ops/StanfordCoreNLP.py | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
def __init__(self):
# I don't see anywhere to put properties like this path...
# For now it's hardcoded and would ... | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
def __init__(self):
# I don't see anywhere to put properties like this path...
# For now it's hardcoded and would ... | Add coreNLP models jar relative path as well | Add coreNLP models jar relative path as well
| Python | mit | rigatoni/linguine-python,Pastafarians/linguine-python |
0ba0d7d1e0b19ef0523c66726cff637018703b4a | tests/test_requesthandler.py | tests/test_requesthandler.py | from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence(self):
original = 'W... | from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence(self):
original = 'W... | Write tests in a better way | Write tests in a better way
| Python | mit | ProjetPP/PPP-Spell-Checker,ProjetPP/PPP-Spell-Checker |
b6ebb7936e19389ee132b6f0bfbeb1ba7441f95a | tmaps/extensions/__init__.py | tmaps/extensions/__init__.py | from .gc3pie import GC3PieEngine
gc3pie_engine = GC3PieEngine()
from flask.ext.redis import FlaskRedis
redis_store = FlaskRedis()
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from auth import jwt
from spark import Spark
spark = Spark()
from .gc3pie import GC3PieEngine
gc3pie_engine = GC3PieEngine(... | from flask.ext.redis import FlaskRedis
redis_store = FlaskRedis()
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from auth import jwt
from spark import Spark
spark = Spark()
from gc3pie import GC3Pie
gc3pie = GC3Pie()
from flask.ext.uwsgi_websocket import GeventWebSocket
websocket = GeventWebSocket(... | Fix import of tmaps extensions | Fix import of tmaps extensions
| Python | agpl-3.0 | TissueMAPS/TmServer |
ac462d27b4242a9e2ee04c052da6b832ae3d0df7 | plugins/Tools/TranslateTool/__init__.py | plugins/Tools/TranslateTool/__init__.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import TranslateTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"type": "tool",
"plugin": {
"name": i18n_catalog.i18nc("@lab... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import TranslateTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"type": "tool",
"plugin": {
"name": i18n_catalog.i18nc("@lab... | Fix order of tools in the toolbar (translate tool on top) | Fix order of tools in the toolbar (translate tool on top)
CURA-838
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
69b3911b6aa13a6420a1b9dc3117164f6bf8330f | PyFVCOM/__init__.py | PyFVCOM/__init__.py | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.3.4'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFV... | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.3.4'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFV... | Remove the backwards compatibility as it wasn't working for some reason. | Remove the backwards compatibility as it wasn't working for some reason.
| Python | mit | pwcazenave/PyFVCOM |
f967ba433284c573cbce47d84ae55c209801ad6e | ash/PRESUBMIT.py | ash/PRESUBMIT.py | # 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.
"""Chromium presubmit script for src/ash
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit A... | # 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.
"""Chromium presubmit script for src/ash
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit A... | Add linux_chromeos_clang to the list of automatic trybots. | Add linux_chromeos_clang to the list of automatic trybots.
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/10833037
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@148600 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | krieger-od/nwjs_chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chro... |
fac9a9a461049b164d478c58435725979b46d400 | usingnamespace/forms/csrf.py | usingnamespace/forms/csrf.py | # File: csrf.py
# Author: Bert JW Regeer <bertjw@regeer.org>
# Created: 2013-01-26
import colander
import deform
@colander.deferred
def deferred_csrf_default(node, kw):
request = kw.get('request')
csrf_token = request.session.get_csrf_token()
return csrf_token
@colander.deferred
def deferred_csrf_validat... | # File: csrf.py
# Author: Bert JW Regeer <bertjw@regeer.org>
# Created: 2013-01-26
import colander
import deform
@colander.deferred
def deferred_csrf_default(node, kw):
request = kw.get('request')
if request is None:
raise KeyError('Require bind: request')
csrf_token = request.session.get_csrf_t... | Add some checking that stuff is bound | Add some checking that stuff is bound
Specifically we require that request is bound to the form.
| Python | isc | usingnamespace/usingnamespace |
ee7d663f3c7e5c52581527167938d81ca2a07a3d | bisnode/models.py | bisnode/models.py | from datetime import datetime
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
cl... | from datetime import datetime
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
cl... | Make Organization Number a unique field | Make Organization Number a unique field
| Python | mit | FundedByMe/django-bisnode |
4078dcd4a35dd09c610bb5e9298a87828a0acf8e | apps/core/models.py | apps/core/models.py | from django.db import models
# Create your models here.
| from django.db import models
from django.utils.timezone import now
class DateTimeCreatedField(models.DateTimeField):
"""
DateTimeField that by default, sets editable=False,
blank=True, default=now.
"""
def __init__(self, *args, **kwargs):
kwargs.setdefault('editable', False)
kwarg... | Implement an abstract base class model | Implement an abstract base class model | Python | mit | SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas |
16b69b7a70d0f5f2dc198e09ad8b5d0e9997aba3 | src/bindings/python/__init__.py | src/bindings/python/__init__.py | import os
import platform
import sys
if platform.system() == "Windows":
os.add_dll_directory(os.path.join(sys.prefix, "Library", "bin"))
| import os
import platform
import sys
if platform.system() == "Windows":
version_info = sys.version_info
if sys.version_info.major == 3 && sys.version_info.minor < 8:
sys.path.append(os.path.join(sys.prefix, "Library", "bin"))
else:
os.add_dll_directory(os.path.join(sys.prefix, "Library", "... | Make aether package initialisation work for both Python 3.7 and 3.8. | Make aether package initialisation work for both Python 3.7 and 3.8.
| Python | apache-2.0 | LungNoodle/lungsim,LungNoodle/lungsim,LungNoodle/lungsim |
9c4aefb8ea88fd5505602c95f4762fdeb3aea183 | oslo_versionedobjects/_utils.py | oslo_versionedobjects/_utils.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | Handle TZ change in iso8601 >=0.1.12 | Handle TZ change in iso8601 >=0.1.12
The iso8601 lib introduced a change such that if running on python
3.2 or later it internally uses the python timezone information
instead of its own implementation. This does not change direct
date handling, but when converting this value there is a slight
difference where now pyt... | Python | apache-2.0 | openstack/oslo.versionedobjects |
e83df69d675eec01bf3253a2c7911cedb0c081af | tests/test_queryable.py | tests/test_queryable.py | from busbus.queryable import Queryable
def test_queryable():
q = Queryable(xrange(10)).where(lambda x: x % 5 == 0)
assert next(q) == 0
assert next(q) == 5
| from busbus.queryable import Queryable
from six.moves import range
def test_queryable():
q = Queryable(range(10)).where(lambda x: x % 5 == 0)
assert next(q) == 0
assert next(q) == 5
| Fix basic test case for Queryable class in Python 3 | Fix basic test case for Queryable class in Python 3
| Python | mit | spaceboats/busbus |
de21f7802cf9124fc2bb15936d35710946deeb18 | examples/asyncio/await.py | examples/asyncio/await.py | import asyncio
from rx import Observable
async def hello_world():
stream = Observable.just("Hello, world!")
n = await stream
print(n)
loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()
| import asyncio
from rx import Observable
stream = Observable.just("Hello, world!")
async def hello_world():
n = await stream
print(n)
loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()
| Move stream out of function | Move stream out of function
| Python | mit | ReactiveX/RxPY,ReactiveX/RxPY |
0232afac110e2cf9f841e861bd9622bcaf79616a | tensorbayes/distributions.py | tensorbayes/distributions.py | """ Assumes softplus activations for gaussian
"""
import tensorflow as tf
import numpy as np
def log_bernoulli(x, logits, eps=0.0, axis=-1):
return log_bernoulli_with_logits(x, logits, eps, axis)
def log_bernoulli_with_logits(x, logits, eps=0.0, axis=-1):
if eps > 0.0:
max_val = np.log(1.0 - eps) - np... | """ Assumes softplus activations for gaussian
"""
import tensorflow as tf
import numpy as np
def log_bernoulli(x, logits, eps=0.0, axis=-1):
return log_bernoulli_with_logits(x, logits, eps, axis)
def log_bernoulli_with_logits(x, logits, eps=0.0, axis=-1):
if eps > 0.0:
max_val = np.log(1.0 - eps) - np... | Add tf implementation of KL between normals | Add tf implementation of KL between normals
| Python | mit | RuiShu/tensorbayes |
4ba390219d58d1726773e14928428f2c9495f6de | api/src/SearchApi.py | api/src/SearchApi.py | from apiclient.discovery import build
import json
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
devKeyFile = open("search-api.key", "rb")
DEVELOPER_KEY = devKeyF... | from apiclient.discovery import build
import json
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
devKeyFile = open("search-api.key", "rb")
DEVELOPER_KEY = devKeyF... | Update search api to produce results more consistant with those found on youtube | Update search api to produce results more consistant with those found on youtube
| Python | mit | jghibiki/mopey,jghibiki/mopey,jghibiki/mopey,jghibiki/mopey,jghibiki/mopey |
e1888771261878d576b05bab806e1abfdc1d25bb | ExpandVariables.py | ExpandVariables.py | import sublime, string, platform
def expand_variables(the_dict, the_vars):
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items():
if isinstance(value, dict):
value = expand_variables(value, the_vars)
... | import sublime, string, platform
def expand_variables(the_dict, the_vars):
the_vars['machine'] = platform.machine()
the_vars['processor'] = platform.processor()
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items(... | Add extra vars "machine" and "processor" for the cmake dictionary. | Add extra vars "machine" and "processor" for the cmake dictionary.
| Python | mit | rwols/CMakeBuilder |
115ffb22128e12a0cc88b7c0cd1dd9bde04fb768 | wagtail/utils/compat.py | wagtail/utils/compat.py | def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
return getattr(rel, 'related_model', rel.model)
| import django
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
if django.VERSION >= (1, 8):
return rel.related_model
else:
return r... | Check Django version instead of hasattr | Check Django version instead of hasattr
| Python | bsd-3-clause | mixxorz/wagtail,taedori81/wagtail,FlipperPA/wagtail,mixxorz/wagtail,bjesus/wagtail,mjec/wagtail,stevenewey/wagtail,gasman/wagtail,hanpama/wagtail,thenewguy/wagtail,serzans/wagtail,kurtw/wagtail,Klaudit/wagtail,hamsterbacke23/wagtail,rv816/wagtail,Klaudit/wagtail,janusnic/wagtail,kurtrwall/wagtail,marctc/wagtail,rjsprox... |
eaf577b7a4aebc872cbf2b5674f9365faeec9cfb | template/module/__openerp__.py | template/module/__openerp__.py | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Module name",
"summary": "Module summary",
"version": "8.0.1.0.0",
"category": "Uncategorized",
"license": "AGPL-3",
"website": "https://odoo-community.org/",
"au... | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Module name",
"summary": "Module summary",
"version": "8.0.1.0.0",
"category": "Uncategorized",
"license": "AGPL-3",
"website": "https://odoo-community.org/",
"au... | Add real author to author key too. | Add real author to author key too.
| Python | agpl-3.0 | acsone/maintainers-tools,Endika/maintainer-tools,sambathkumarpi/maintainer-tools,dreispt/maintainer-tools,OCA/maintainer-tools,Yajo/maintainer-tools,Yajo/maintainer-tools,Vauxoo/maintainer-tools,vauxoo-dev/maintainer-tools,OCA/maintainer-tools,acsone/maintainer-tools,dreispt/maintainer-tools,tafaRU/maintainer-tools,Yaj... |
db64ca09e57da414d92888de1b52fade810d855e | handlers/downloadMapHandler.py | handlers/downloadMapHandler.py | from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
... | from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
... | Add some headers in osu! direct download | Add some headers in osu! direct download
| Python | agpl-3.0 | osuripple/lets,osuripple/lets |
03b55cad3839653cea62300eca80571541579d2b | dataviews/__init__.py | dataviews/__init__.py | import sys, os
# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))
import param
__version__ = param.Version(release=(0,7), fpath=__file__,
commit="$Format:%h$", reponame='dataviews')
from .views import *... | import sys, os
# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))
import param
__version__ = param.Version(release=(0,7), fpath=__file__,
commit="$Format:%h$", reponame='dataviews')
from .views import *... | Apply default style on import | Apply default style on import
| Python | bsd-3-clause | vascotenner/holoviews,basnijholt/holoviews,vascotenner/holoviews,basnijholt/holoviews,mjabri/holoviews,mjabri/holoviews,ioam/holoviews,basnijholt/holoviews,mjabri/holoviews,ioam/holoviews,vascotenner/holoviews,ioam/holoviews |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.