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 |
|---|---|---|---|---|---|---|---|---|---|
74e9c87f4a6ad9ad6458a1e297460220c587b197 | rbuild/client.py | rbuild/client.py | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | Fix getClient bugs found by smoketest | Fix getClient bugs found by smoketest
| Python | apache-2.0 | fedora-conary/rbuild,sassoftware/rbuild,fedora-conary/rbuild,sassoftware/rbuild |
6c4178f4b5518568d83523db418d34c36a791852 | skylines/__init__.py | skylines/__init__.py | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel... | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel... | Configure webassets environment from app.config | flask: Configure webassets environment from app.config
| Python | agpl-3.0 | RBE-Avionik/skylines,Turbo87/skylines,snip/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,RBE-Avionik/skylines,snip/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,snip/skylines,TobiasLohner/SkyLines,kerel-fs/skylines,kerel-fs/skylines,Harry-R/skylines,shadowoneau/sky... |
4727991d29bc888611b6eaa403456524785b6338 | highlightjs/testsettings.py | highlightjs/testsettings.py | import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
| import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES... | Add django backend for test settings | Add django backend for test settings | Python | mit | MounirMesselmeni/django-highlightjs |
97e3309a66c5d84489df4a384552e5b5d75643ea | spotpy/unittests/test_objectivefunctions.py | spotpy/unittests/test_objectivefunctions.py | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
... | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
... | Add tests for pbias and nashsutcliffe | Add tests for pbias and nashsutcliffe
| Python | mit | bees4ever/spotpy,thouska/spotpy,thouska/spotpy,bees4ever/spotpy,thouska/spotpy,bees4ever/spotpy |
63814839642e593e35f8afaf68fc6724b69075b5 | trade_server.py | trade_server.py | import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if d... | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
res... | Add stubs for handling requests to server. | Add stubs for handling requests to server.
| Python | mit | Tribler/decentral-market |
8b2cb51c8913737c524e1b922aeb02c07bfb2afc | src/keybar/models/entry.py | src/keybar/models/entry.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextF... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = mod... | Add decrypt helper to Entry | Add decrypt helper to Entry
| Python | bsd-3-clause | keybar/keybar |
cfc95643733244275e605a8ff0c00d4861067a13 | character_shift/character_shift.py | character_shift/character_shift.py | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1)... | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BC... | Use bitwise operators on ordinals to reduce code size | Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
| Python | mit | TotempaaltJ/tiniest-code,TotempaaltJ/tiniest-code |
1632b64372f2f38a6c43b000ace631d183278375 | observations/forms.py | observations/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploa... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models ... | Use transaction.atomic in batch uploader. | Use transaction.atomic in batch uploader.
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net |
8394011dc2cd0a6fe682c435b8e09f8accb1311f | web/impact/impact/v1/views/criterion_option_spec_list_view.py | web/impact/impact/v1/views/criterion_option_spec_list_view.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
hel... | Move some code around because code climate said so | [AC-5622] Move some code around because code climate said so
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api |
16dd533f32b3efdbbe9c2f7c6e5e3f42fe6c6b1d | qtpy/tests/test_qtprintsupport.py | qtpy/tests/test_qtprintsupport.py | import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrin... | """Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrint... | Add tests for aliased methods | QtPrintSupport: Add tests for aliased methods
| Python | mit | spyder-ide/qtpy |
3129d72151d81d8745a8e81ab4940dcd56a67b66 | scripts/get-translator-credits.py | scripts/get-translator-credits.py | import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string f... | import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
... | Sort languages by English name | Sort languages by English name
| Python | bsd-3-clause | zerolab/wagtail,thenewguy/wagtail,timorieber/wagtail,kaedroho/wagtail,kurtrwall/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,kurtw/wagtail,nimasmi/wagtail,torchbox/wagtail,zerolab/wagtail,timorieber/wagtail,FlipperPA/wagtail,rsalmaso/wagtail,zerolab/wagtail,kaedroho/wagtail,mixxorz/wagtail,mikedingjan/wagtail,rsalmas... |
a92121cfdbb94d36d021fb8d1386031829ee86a2 | patterns/solid.py | patterns/solid.py | import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixel... | class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
| Update Solid pattern for refactor | Update Solid pattern for refactor
| Python | mit | jonspeicher/blinkyfun |
c0ce65ccd7db7e7f34e9d6172f7179cf9ee16ef2 | chandra_aca/tests/test_dark_scale.py | chandra_aca/tests/test_dark_scale.py | import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
... | Add regression test of warm fractions calculation | Add regression test of warm fractions calculation
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca |
28d5e53da8a92985fa9b1b4a532467dd343cc4b5 | apilisk/junit_formatter.py | apilisk/junit_formatter.py | import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for ... | # -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
... | Fix junit utf-8 output to file | Fix junit utf-8 output to file
| Python | mit | apiwatcher/apilisk |
f74ce9c077054119c04ab65fc0afa4c137204770 | comics/comics/basicinstructions.py | comics/comics/basicinstructions.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(Cr... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(Cr... | Update "Basic Instructions" after feed change | Update "Basic Instructions" after feed change
| Python | agpl-3.0 | datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics |
7c847513155b1bdc29c04a10dbfd2efd669d1507 | async/spam_echo_clients.py | async/spam_echo_clients.py | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
s... | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
s... | Add reply checks to the spam client too | Add reply checks to the spam client too
| Python | unlicense | eliben/python3-samples |
8ffc8cabd5a2ba20997337c101018f3c25faef4e | onadata/apps/fsforms/management/commands/save_version_in_finstance.py | onadata/apps/fsforms/management/commands/save_version_in_finstance.py | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
... | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def... | Update command to save version in finstance | Update command to save version in finstance
| Python | bsd-2-clause | awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat |
ff6fbf0821112a0144fbe2d14768cd7a03907438 | rst2pdf/utils.py | rst2pdf/utils.py | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (ca... | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... | Add unit support for spacers | Add unit support for spacers
| Python | mit | thomaspurchas/rst2pdf,thomaspurchas/rst2pdf |
ead5a941efd8b8a41b81f679ad3e6c98e2248409 | dipy/io/tests/test_dicomreaders.py | dipy/io/tests/test_dicomreaders.py | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, ass... | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
... | TEST - added more explicit tests for directory read | TEST - added more explicit tests for directory read
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,sinkpoint/dipy,StongeEtienne/dipy,samuelstjean/dipy,rfdougherty/dipy,demianw/dipy,samuelstjean/dipy,JohnGriffiths/dipy,mdesco/dipy,rfdougherty/dipy,maurozucchelli/dipy,demianw/dipy,jyeatman/dipy,oesteban/dipy,beni55/dipy,StongeEtienne/dipy,mdesco/dipy,matthieudumont/dipy,FrancoisRheaultUS/dipy,jy... |
697bf0c23786794e35b0b9f72c878bb762d296b9 | benches/cprofile_pyproj.py | benches/cprofile_pyproj.py | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random... | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon... | Use NTv2 transform for Pyproj | Use NTv2 transform for Pyproj
| Python | mit | urschrei/lonlat_bng,urschrei/rust_bng,urschrei/lonlat_bng,urschrei/rust_bng,urschrei/lonlat_bng |
1fce663e37823d985d00d1700aba5e067157b789 | profiles/tests.py | profiles/tests.py | from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)... | from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequenc... | Add password handling to default factory. | Add password handling to default factory.
| Python | bsd-2-clause | incuna/django-extensible-profiles |
d369b2ba967643d16c58fbad0be5b3a24785f602 | neurodsp/tests/test_spectral_utils.py | neurodsp/tests/test_spectral_utils.py | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
##########################################################################... | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
##########################################################################... | Add smoke test for trim_spectrogram | Add smoke test for trim_spectrogram
| Python | apache-2.0 | voytekresearch/neurodsp |
5ac1dce80d0bfe4c52a2de5de4beefe235b8ad66 | post_process.py | post_process.py | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import tr... | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import tr... | Load SVM pickle and print metrics | Load SVM pickle and print metrics
| Python | bsd-3-clause | BeckResearchLab/USP-inhibition,pearlphilip/USP-inhibition |
19ce6528a722deec9f0080c229c329e15b843614 | src/pyqa.py | src/pyqa.py | def main():
pass
if __name__ == '__main__':
main()
| from __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
| Make it possible to load questions | Make it possible to load questions
| Python | mit | bebraw/pyqa |
28bc35bc8ed2646faf0d6662b54a5324c0fd1e31 | pspec/cli.py | pspec/cli.py | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
... | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]`... | Put CWD at start of sys.path | Put CWD at start of sys.path
| Python | bsd-3-clause | bfirsh/pspec |
6e9e6c0fbba6b1f6e97c40181ec58c55e4980995 | pyipmi/fw.py | pyipmi/fw.py | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to ho... | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(o... | Add equality operator to FWInfo | Add equality operator to FWInfo
| Python | bsd-3-clause | Cynerva/pyipmi,emaadmanzoor/pyipmi |
ff800f11b948808e4574ec3a893ed4e259707dcf | stubs/python2-urllib2/run.py | stubs/python2-urllib2/run.py | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.Cert... | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(... | Make python2-urllib2 compatible with more Python 2.7 versions | Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():".
| Python | mit | ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls |
4f1354f6e917a4a90a56f3c2545aa678809334c3 | scripts/release/rethreshold_family.py | scripts/release/rethreshold_family.py | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 a... | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 a... | Add function to run rfsearch on the cluster | Add function to run rfsearch on the cluster
| Python | apache-2.0 | Rfam/rfam-production,Rfam/rfam-production,Rfam/rfam-production |
76bda324fcd617677a3f107e6b7c162a81e88db9 | tests/test_vector2_negation.py | tests/test_vector2_negation.py | import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -te... | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
| Replace with an Hypothesis test | tests/negation: Replace with an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
8bb60a82f903126068434df3a464cdde5d894d0c | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load... | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `... | Add logger to env loader | Add logger to env loader
| Python | mit | serverless/serverless-helpers-py |
8dadb34bdfe6d85d3016a59a9441ed8a552d1149 | octane_fuelclient/octaneclient/commands.py | octane_fuelclient/octaneclient/commands.py | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | Fix endpoint for clone operation | Fix endpoint for clone operation
| Python | apache-2.0 | stackforge/fuel-octane,Mirantis/octane,Mirantis/octane,stackforge/fuel-octane |
e538f2862a875afc58071a9fc6419e4290f8b00d | rouver/types.py | rouver/types.py | from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional... | from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> re... | Remove obsolete aliases and imports | Remove obsolete aliases and imports
| Python | mit | srittau/rouver |
e69962de56cb5eaa12f908a74edca4c225dcee9c | run-tests.py | run-tests.py | #!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd... | #!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compar... | Add automated 'gm compare' invocation | Add automated 'gm compare' invocation
| Python | mit | iFixit/node-markup,iFixit/node-markup,iFixit/node-markup |
ccda4cd859b512d8694eba4261439bb52574f099 | cities/Sample_City.py | cities/Sample_City.py | from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
f... | from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes thi... | Add geodata parsing to sample city file | Add geodata parsing to sample city file
| Python | mit | Mic92/ParkAPI,Mic92/ParkAPI,offenesdresden/ParkAPI,offenesdresden/ParkAPI |
51029137cddaebeb3d84b7fa766c5e3914a02504 | multilingual_model/admin.py | multilingual_model/admin.py | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:... | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self... | Use a Mixin for Admin inlines; less code duplication. | Use a Mixin for Admin inlines; less code duplication.
| Python | agpl-3.0 | dokterbob/django-multilingual-model |
3e20365624f02b70d8332ba7ff7da23961337f86 | quickstart/python/understand/example-3/create_joke_samples.6.x.py | quickstart/python/understand/example-3/create_joke_samples.6.x.py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a j... | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a j... | Update samples creation for intent rename | Update samples creation for intent rename
Update intent --> task, code comment | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets |
9144e6011df4aebd74db152dad2bb07a8eebf6ee | setup_egg.py | setup_egg.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # need... | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in se... | Use `exec` instead of `execfile`. | Use `exec` instead of `execfile`.
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy |
f800d11aa5a198fcb2193773b30e4e066a226321 | code/handle-output.py | code/handle-output.py | import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
| import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
... | Set resu dir and data dir | Set resu dir and data dir
| Python | mit | chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan |
2fe315e1753aca8215228091e3a64af057020bc2 | celery/loaders/__init__.py | celery/loaders/__init__.py | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loa... | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loa... | Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. | Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
| Python | bsd-3-clause | frac/celery,WoLpH/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,cbrepo/celery,ask/celery |
7d130a447786c61c7bfbe6bfe2d87b2c28e32eb6 | shut-up-bird.py | shut-up-bird.py | #!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
| #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_se... | Add OAuth authentication and config settings load/save | Add OAuth authentication and config settings load/save
| Python | mit | petarov/shut-up-bird |
f2a31c4a203d06fd83086f3789e52be94320c691 | tests/test_utils/__init__.py | tests/test_utils/__init__.py | import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(Test... | import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
config... | Fix tests for new deployment | Fix tests for new deployment
| Python | mit | getslash/mailboxer,getslash/mailboxer,getslash/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer |
7f9c9b947948654d7557aa0fcfbb1c015521da9b | tests/modular_templates/routing.py | tests/modular_templates/routing.py | import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),... | import unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('v... | Fix RuleTestCase -> tests passing | Fix RuleTestCase -> tests passing
| Python | apache-2.0 | caneruguz/osf.io,brandonPurvis/osf.io,rdhyee/osf.io,KAsante95/osf.io,pattisdr/osf.io,KAsante95/osf.io,barbour-em/osf.io,HarryRybacki/osf.io,mluke93/osf.io,aaxelb/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,caseyrygt/osf.io,kwierman/osf.io,adlius/osf.io... |
507b8bb0910ef6fae9c7d9cb1405a33c4e4b6e8e | synapse/config/password.py | synapse/config/password.py | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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... | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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... | Add comment to prompt changing of pepper | Add comment to prompt changing of pepper
| Python | apache-2.0 | matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse |
389679c0fc575bb03bfa4e625de16eb7ed9c3a04 | testdoc/formatter.py | testdoc/formatter.py | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class ... | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class ... | Put a blank line before section headings, courtesy spiv. | Put a blank line before section headings, courtesy spiv.
| Python | mit | testing-cabal/testdoc |
30b6d886670b7ba65aee9b130ec50d577c778649 | run_server.py | run_server.py | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
... | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
... | Add a message with a socket on server start | Add a message with a socket on server start
| Python | mit | bondarevts/flucalc,bondarevts/flucalc,bondarevts/flucalc |
dc09143973640b2873dae7434ce654535fbfdd8c | qtpy/tests/test_qtwebenginewidgets.py | qtpy/tests/test_qtwebenginewidgets.py | from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.Q... | from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebE... | Fix failing tests in Python 2 | Tesitng: Fix failing tests in Python 2
| Python | mit | goanpeca/qtpy,goanpeca/qtpy,davvid/qtpy,spyder-ide/qtpy,davvid/qtpy |
722b588629fa0986e8d7c06ff135d81c08ad8fab | tensorflow_datasets/object_detection/waymo_open_dataset_test.py | tensorflow_datasets/object_detection/waymo_open_dataset_test.py | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... | Add doc string for waymo open dataset | Add doc string for waymo open dataset | Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets |
35a7e3e892135d805dfe73b8ce66f986651354f5 | tests/test_gutenbergweb.py | tests/test_gutenbergweb.py | from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
| import gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isins... | Add proper tests for gutenbergweb | Add proper tests for gutenbergweb
| Python | bsd-3-clause | pv/mgutenberg,pv/mgutenberg |
730aaf64635268df8d3c5cd3e1d5e2448644c907 | problem-static/Intro-Eval_50/admin/eval.py | problem-static/Intro-Eval_50/admin/eval.py | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | Make Intro Eval use input instead of raw_input | Make Intro Eval use input instead of raw_input
| Python | mit | james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF |
4b687d702face412330580ed88f71c897dfa5e6a | nipy/core/image/__init__.py | nipy/core/image/__init__.py | """
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
-----------------... | """
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester... | Remove old doc. Import Image into core.image | Remove old doc. Import Image into core.image | Python | bsd-3-clause | bthirion/nipy,arokem/nipy,alexis-roche/register,alexis-roche/nireg,alexis-roche/register,arokem/nipy,nipy/nipy-labs,arokem/nipy,alexis-roche/niseg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,nipy/nireg,alexis-roche/register,bthirion/nipy,arokem/nipy,alexis-roche/niseg,nipy/nireg,bthirion/nipy,alexis-roche/ni... |
b682ff69d5cbfa0529e4d231d5337be7f8fbfaf4 | non_logged_in_area/views.py | non_logged_in_area/views.py | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__n... | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__n... | Add filter do not display facilities without shifts | Add filter do not display facilities without shifts
| Python | agpl-3.0 | coders4help/volunteer_planner,christophmeissner/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,volunteer-planner/volunteer_planner,christophmeissner/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_p... |
13c6748313e1114853a45e25bcc8135a8b5f5240 | slowpoke/decorator.py | slowpoke/decorator.py | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
... | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
d... | Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | Python | bsd-3-clause | adamfast/django-slowpoke |
2995accb21d9b8c45792d12402470cfcf322d6a1 | models/phase3_eval/process_sparser.py | models/phase3_eval/process_sparser.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames ... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames ... | Update Sparser script for phase3 | Update Sparser script for phase3
| Python | bsd-2-clause | johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy |
f758513880cca46937833779ddf099b2ac88afc9 | utilities/ticker-update.py | utilities/ticker-update.py | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def u... | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities... | Fix config PATH for windows batch file | Fix config PATH for windows batch file | Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various |
3ffaf00e18208a1877c3d2286ba284071d5d3e09 | wafer/pages/serializers.py | wafer/pages/serializers.py | from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
... | from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user... | Add people and other fields to page update options | Add people and other fields to page update options
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
3570f3a1681cf2b5ad1ba31026ae9d13fcc3e9c2 | test_base.py | test_base.py | import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid =... | import pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = ... | Add some sleep in tests to not exceed allowed request limits | Add some sleep in tests to not exceed allowed request limits
| Python | mit | lincis/pynoaa |
ef2f5bf541ab2938f19b11c0845610ccce5e496e | test/__init__.py | test/__init__.py | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | Make unit tests run on RHEL boxes better via the python-unittest2 library | Make unit tests run on RHEL boxes better via the python-unittest2 library
| Python | agpl-3.0 | pombredanne/re-core,RHInception/re-core |
6d52364c44cf7244b920d04fe6f5917cd99b7377 | linkatos/utils.py | linkatos/utils.py | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no r... | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no r... | Add back is_fresh_url which was deleted by mistake | fix: Add back is_fresh_url which was deleted by mistake
| Python | mit | iwi/linkatos,iwi/linkatos |
f6d17ba769357ad0dfb8766728349d0fce60efe8 | Bookie/fabfile/development.py | Bookie/fabfile/development.py | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.p... | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
... | Add fab functions to build the chrome extension and upload to bmark.us | Add fab functions to build the chrome extension and upload to bmark.us
| Python | agpl-3.0 | bookieio/Bookie,wangjun/Bookie,charany1/Bookie,pombredanne/Bookie,wangjun/Bookie,GreenLunar/Bookie,charany1/Bookie,teodesson/Bookie,charany1/Bookie,teodesson/Bookie,wangjun/Bookie,adamlincoln/Bookie,pombredanne/Bookie,wangjun/Bookie,skmezanul/Bookie,teodesson/Bookie,bookieio/Bookie,GreenLunar/Bookie,bookieio/Bookie,ada... |
e811b1ca77f7b8ae090be369fd89d4fe8c7c3f6e | test/functional/rpc_deprecated.py | test/functional/rpc_deprecated.py | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from... | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
clas... | Add a test for the banscore deprecation | Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915
| Python | mit | Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc |
3a7f9520fce968d8292581caf6b94a6ce833b335 | migrations/versions/51775a13339d_patch_hash_column.py | migrations/versions/51775a13339d_patch_hash_column.py | """patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('... | """patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('... | Fix revision number in comment | Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes |
ce86f13553e97e3e86f8c07bf09228895aacd3c5 | scripts/master/factory/syzygy_commands.py | scripts/master/factory/syzygy_commands.py | # Copyright (c) 2011 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.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps impor... | # Copyright (c) 2011 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.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps impor... | Fix typos and paths broken in previous CL. | Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
49d7260f2454693c511a0f5124f412e987454dba | matches/models.py | matches/models.py | from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models... | from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
clas... | Add name and promotion to Card. | Add name and promotion to Card.
| Python | agpl-3.0 | OddBloke/moore |
dc1130766d356e1e9a613ba924e4af942631428c | distutils/tests/test_ccompiler.py | distutils/tests/test_ccompiler.py |
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler =... | import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build e... | Add compatibility for Python 3.7 | Add compatibility for Python 3.7
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
742ce33b0acc576aab72d625d2accc86a53b4023 | comrade/cronjobs/management/commands/cron.py | comrade/cronjobs/management/commands/cron.py | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):... | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts... | Fix import now that this is renamed. | Fix import now that this is renamed.
| Python | mit | bueda/django-comrade |
1fd73a2c07ce66a8dba0ef08210612a2535538ea | jesusmtnez/python/koans/koans/about_decorating_with_functions.py | jesusmtnez/python/koans/koans/about_decorating_with_functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_de... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_de... | Complete 'About Decorating with functions' koans | [Python] Complete 'About Decorating with functions' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge |
3310d8a83871fc0644045295db60cb3bbfe7f141 | tests/_support/empty_subcollection.py | tests/_support/empty_subcollection.py | from invoke import task, Collection
@task
def dummy(c):
pass
ns = Collection(dummy, subcollection=Collection())
| from invoke import task, Collection
@task
def dummy(c):
pass
ns = Collection(dummy, Collection('subcollection'))
| Fix a dumb test fixture mistake | Fix a dumb test fixture mistake
| Python | bsd-2-clause | pyinvoke/invoke,pyinvoke/invoke |
35296b1c87a86a87fbcf317e26a497fc91c287c7 | lexos/receivers/kmeans_receiver.py | lexos/receivers/kmeans_receiver.py | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k val... | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k val... | Update receiver to catch value error | Update receiver to catch value error
| Python | mit | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos |
8f280cece4d59e36ebfeb5486f25c7ac92718c13 | third_problem.py | third_problem.py | letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ'
phrase = input()
output = ''
vowels = ''
phrase = phrase.replace(' ', '')
for char in phrase:
if char in letters:
output += char
else:
vowels += char
print(output)
print(vowels) | not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ'
phrase = input()
output = ''
vowels = ''
# Remove sapces
phrase = phrase.replace(' ', '')
for char in phrase:
if char in not_vowel:
output += char # Add non vowel to output
else:
vowels += char # Add vowels to vowels
print(output)
pri... | Clean it up a bit | Clean it up a bit | Python | mit | DoublePlusGood23/lc-president-challenge |
b64e7714e581cfc0c0a0d0f055b22c5edca27e24 | susumutakuan.py | susumutakuan.py | import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
def sigterm_handler(signum, frame):
print("Logging out...")
client.logout()
print('Shutting down...')
sy... | import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
async def sigterm_handler(signum, frame):
print("Logging out...")
raise KeyboardInterrupt
print('Shutting do... | Raise KeyboardInterrupt to allow the run to handle logout | Raise KeyboardInterrupt to allow the run to handle logout
| Python | mit | gryffon/SusumuTakuan,gryffon/SusumuTakuan |
fb5ad293c34387b1ab7b7b7df3aed3942fdd9282 | src/webapp/activities/forms.py | src/webapp/activities/forms.py | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
clas... | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
clas... | Add default to max_places in proposal form | Add default to max_places in proposal form
| Python | agpl-3.0 | hirunatan/estelcon_web,hirunatan/estelcon_web,hirunatan/estelcon_web,hirunatan/estelcon_web |
551dddbb80d512ec49d8a422b52c24e98c97b38c | tsparser/main.py | tsparser/main.py | from tsparser import config
from tsparser.parser import BaseParser, ParseException
from tsparser.parser.gps import GPSParser
from tsparser.parser.imu import IMUParser
from tsparser.sender import Sender
def parse(input_file=None):
"""
Parse the file specified as input.
:param input_file: file to read inpu... | from time import sleep
from tsparser import config
from tsparser.parser import BaseParser, ParseException
from tsparser.parser.gps import GPSParser
from tsparser.parser.imu import IMUParser
from tsparser.sender import Sender
def parse(input_file=None):
"""
Parse the file specified as input.
:param input_... | Add waiting for new data to parse | Add waiting for new data to parse
| Python | mit | m4tx/techswarm-receiver |
6d7e597ce216093d52ecdcb7db5c087dc6040bb1 | fullcalendar/conf.py | fullcalendar/conf.py | from datetime import timedelta
from django.conf import settings as django_settings
default = {
'FULLCALENDAR_FIRST_WEEKDAY': 0,
'FULLCALENDAR_OCCURRENCE_DURATION': timedelta(hours=1),
'FULLCALENDAR_SITE_COLORS': {}
}
settings = object()
for key, value in default.items():
setattr(settings, key,
... | from datetime import timedelta
from django.conf import settings as django_settings
default = {
'FULLCALENDAR_FIRST_WEEKDAY': 0,
'FULLCALENDAR_OCCURRENCE_DURATION': timedelta(hours=1),
'FULLCALENDAR_SITE_COLORS': {}
}
settings = type('SettingsDummy', (), default)
for key, value in default.items():
se... | Fix initiation of settings object | Fix initiation of settings object
| Python | mit | jonge-democraten/mezzanine-fullcalendar |
7674437d752be0791688533dd1409fa083672bb2 | genes/java/config.py | genes/java/config.py | #!/usr/bin/env python
def config():
return {
'is-oracle': True,
'version': 'oracle-java8',
}
| #!/usr/bin/env python
from collections import namedtuple
JavaConfig = namedtuple('JavaConfig', ['is_oracle', 'version'])
def config():
return JavaConfig(
is_oracle=True,
version='oracle-java8',
)
| Switch from dictionary to namedtuple | Switch from dictionary to namedtuple | Python | mit | hatchery/Genepool2,hatchery/genepool |
1657e46cd5c2a81df4cbb73b292b0bf9072d5c51 | h2o-py/tests/testdir_tree/pyunit_tree_irf.py | h2o-py/tests/testdir_tree/pyunit_tree_irf.py | import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_clas... | import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_clas... | Fix test: make sure that Isolation Forest actually make a categorical split | Fix test: make sure that Isolation Forest actually make a categorical split
| Python | apache-2.0 | h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3 |
fc7f51877b6b991ad5a25afb755dd7a35e91dfea | cla_backend/apps/legalaid/migrations/0022_default_contact_for_research_methods.py | cla_backend/apps/legalaid/migrations/0022_default_contact_for_research_methods.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import uuid
from cla_common.constants import RESEARCH_CONTACT_VIA
def create_default_contact_for_research_methods(apps, schema_editor):
ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod")
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import uuid
from cla_common.constants import RESEARCH_CONTACT_VIA
def create_default_contact_for_research_methods(apps, schema_editor):
ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod")
... | Use get_or_create to avoid duplicate objects | Use get_or_create to avoid duplicate objects
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend |
4f2fa4e43b314c9d05e0b9b9e73641463c16a9cb | server/proposal/__init__.py | server/proposal/__init__.py | from django.apps import AppConfig
class ProposalConfig(AppConfig):
name = "proposal"
def ready(self):
# Register tasks with Celery:
from . import tasks
| from django.apps import AppConfig
class ProposalConfig(AppConfig):
name = "proposal"
def ready(self):
# Register tasks with Celery:
from . import tasks
tasks.set_up_hooks()
| Set up the proposal tasks on app startup | Set up the proposal tasks on app startup
| Python | mit | cityofsomerville/citydash,codeforboston/cornerwise,codeforboston/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/cornerwise,codeforboston/cornerwise,cityofsomerville/citydash,cityofsomerville/citydash,codeforboston/cornerwise,cityofsomerville/cornerwise,cityofsomerville/cornerwise |
833f8ce0673701eb64fb20ee067ccd8c58e473c6 | child_sync_typo3/wizard/child_depart_wizard.py | child_sync_typo3/wizard/child_depart_wizard.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | Correct wrong inheritance on sponsorship_typo3 child_depart wizard. | Correct wrong inheritance on sponsorship_typo3 child_depart wizard.
| Python | agpl-3.0 | MickSandoz/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ndtran/compassion-switzerland,ndtran/compassion-switzerland,CompassionCH/compassion-switzerland,MickSandoz/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,Secheron/compassion-swi... |
2192219d92713c6eb76593d0c6c29413d040db6a | scripts/cronRefreshEdxQualtrics.py | scripts/cronRefreshEdxQualtrics.py | from surveyextractor import QualtricsExtractor
import getopt
import sys
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
qe... | from surveyextractor import QualtricsExtractor
import getopt, sys
# Script for scheduling regular EdxQualtrics updates
# Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses... | Revert "Added script for cron job to load surveys to database." | Revert "Added script for cron job to load surveys to database."
This reverts commit 34e5560437348e5cfeab589b783c9cc524aa2abf.
| Python | bsd-3-clause | paepcke/json_to_relation,paepcke/json_to_relation,paepcke/json_to_relation,paepcke/json_to_relation |
899e3c9f81a43dcb94e290ce0a86f128bd94effd | opps/channel/context_processors.py | opps/channel/context_processors.py | # -*- coding: utf-8 -*-
from .models import Channel
def channel_context(request):
return {'opps_menu': Channel.objects.all()}
| # -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
published=True)
return {'opps_menu': opp... | Apply filter channel published on menu list (channel context processors) | Apply filter channel published on menu list (channel context processors)
| Python | mit | YACOWS/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps |
c55bf8d153c47500615b8ded3c95957be8ee70a3 | froide/helper/json_view.py | froide/helper/json_view.py | from django import http
from django.views.generic import DetailView
class JSONResponseDetailView(DetailView):
def render_to_json_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json_... | from django import http
from django.views.generic import DetailView, ListView
class JSONResponseMixin(object):
def render_to_json_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json... | Refactor JSONResponse views to include ListView | Refactor JSONResponse views to include ListView | Python | mit | okfse/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,catcosmo/froide,ryankanno/froide,stefanw/froide,okfse/froide,catcosmo/froide,ryankanno/froide,fin/froide,LilithWittmann/froide,okfse/froide,ryankanno/froide,ryankanno/froide,LilithWittmann/froide,fin/froide,CodeforHawaii/froide,LilithWittmann/froide... |
38eb6221ca41446c0c4fb1510354bdc4f00ba5f1 | serfnode/build/handler/launcher.py | serfnode/build/handler/launcher.py | #!/usr/bin/env python
import functools
import os
import signal
import sys
import docker_utils
def handler(name, signum, frame):
print('Should kill', name)
try:
docker_utils.client.remove_container(name, force=True)
except Exception:
pass
sys.exit(0)
def launch(name, args):
try:... | #!/usr/bin/env python
import functools
import os
import signal
import sys
import docker_utils
def handler(name, signum, frame):
print('Should kill', name)
try:
cid = open('/child_{}'.format(name)).read().strip()
docker_utils.client.remove_container(cid, force=True)
except Exception:
... | Remove children via uid rather than name | Remove children via uid rather than name | Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode |
bca6f6041e9f49d1d25d7a9c4cb88080d88c45b1 | dumper/invalidation.py | dumper/invalidation.py | import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
return [dumper.utils.cache_key(path, method) for ... | import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
'''
Each path can actually have multiple cach... | Comment concerning differences in keys per path | Comment concerning differences in keys per path | Python | mit | saulshanabrook/django-dumper |
b0806c0b8b950a3007107cc58fb21e504cf09427 | homedisplay/control_milight/management/commands/listen_433.py | homedisplay/control_milight/management/commands/listen_433.py | from django.core.management.base import BaseCommand, CommandError
from control_milight.utils import process_automatic_trigger
import serial
import time
class Command(BaseCommand):
args = ''
help = 'Listen for 433MHz radio messages'
ITEM_MAP = {
"5236713": "kitchen",
"7697747": "hall",
... | from control_milight.utils import process_automatic_trigger
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import serial
import time
class Command(BaseCommand):
args = ''
help = 'Listen for 433MHz radio messages'
ITEM_MAP = {
"5236713": "kitchen"... | Move serial device path to settings | Move serial device path to settings
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display |
6231afb51f5653e210f41d47c66797c4bd4d738d | accounts/views.py | accounts/views.py | # coding: utf-8
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import UpdateView
from django.core.urlresolvers import reverse_lazy
from volunteer_planner.utils import LoginRequiredMixin
@login_required()
def user_account_detail(request):
... | # coding: utf-8
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import UpdateView
from django.core.urlresolvers import reverse_lazy
from volunteer_planner.utils import LoginRequiredMixin
@login_required()
def user_account_detail(request):
... | Make it possible for the user to change username | Make it possible for the user to change username
| Python | agpl-3.0 | christophmeissner/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,coders4help/volunteer_planner,alper/volunteer_planner,alper/volunteer_planner,alper/volunteer_planner,coders4help/volunteer_planner,klinger/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,... |
7c75da48d6746fc148a79051338c3cd554d75615 | accounts/views.py | accounts/views.py | from django.shortcuts import redirect
from django.contrib.auth import logout as auth_logout
from django.conf import settings
def logout(request):
"""Logs out user redirects if in request"""
r = request.GET.get('r', '')
auth_logout(request)
if r:
return redirect('{}/?r={}'.format(settings.OPEN... | from django.shortcuts import redirect
from django.contrib.auth import logout as auth_logout
from django.conf import settings
def logout(request):
"""Logs out user redirects if in request"""
next = request.GET.get('next', '')
auth_logout(request)
if next:
return redirect('{}/?next={}'.format(s... | Change variable name to next for logout function | Change variable name to next for logout function
| Python | agpl-3.0 | openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms |
41ea0dd8c48ef8a336422482e9bbd1911bb7e168 | Commitment.py | Commitment.py | import sublime
import sublime_plugin
from commit import Commitment
whatthecommit = 'http://whatthecommit.com/'
randomMessages = Commitment()
class CommitmentToClipboardCommand(sublime_plugin.WindowCommand):
def run(self):
commit = randomMessages.get()
message = commit.get('message', '')
message_ha... | import sublime
import sublime_plugin
import HTMLParser
from commit import Commitment
whatthecommit = 'http://whatthecommit.com/'
randomMessages = Commitment()
class CommitmentToClipboardCommand(sublime_plugin.WindowCommand):
def run(self):
commit = randomMessages.get()
message = HTMLParser.HTMLParser()... | Make that it works in 90% of the cases. 3:30. | Make that it works in 90% of the cases. 3:30.
| Python | mit | janraasch/sublimetext-commitment,janraasch/sublimetext-commitment |
8fd65190a2a68a7afeab91b0a02c83309f72ccd6 | tests/test_testing.py | tests/test_testing.py |
import greenado
from greenado.testing import gen_test
from tornado.testing import AsyncTestCase
from tornado import gen
@gen.coroutine
def coroutine():
raise gen.Return(1234)
class GreenadoTests(AsyncTestCase):
@gen_test
def test_without_timeout(self):
assert greenado.gyield(coroutine()) ... |
import greenado
from greenado.testing import gen_test
from tornado.testing import AsyncTestCase
from tornado import gen
@gen.coroutine
def coroutine():
raise gen.Return(1234)
class GreenadoTests(AsyncTestCase):
@gen_test
def test_without_timeout1(self):
assert greenado.gyield(coroutine())... | Add tests to gen_test for generator, seems to work | Add tests to gen_test for generator, seems to work
| Python | apache-2.0 | virtuald/greenado,virtuald/greenado |
d2fb1f22be6c6434873f2bcafb6b8a9b714acde9 | website/archiver/decorators.py | website/archiver/decorators.py | import functools
from framework.exceptions import HTTPError
from website.project.decorators import _inject_nodes
from website.archiver import ARCHIVER_UNCAUGHT_ERROR
from website.archiver import utils
def fail_archive_on_error(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
... | import functools
from framework.exceptions import HTTPError
from website.project.decorators import _inject_nodes
from website.archiver import ARCHIVER_UNCAUGHT_ERROR
from website.archiver import signals
def fail_archive_on_error(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
... | Use fail signal in fail_archive_on_error decorator | Use fail signal in fail_archive_on_error decorator
| Python | apache-2.0 | amyshi188/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,mluke93/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,jeffreyliu3230/osf.io,chrisseto/osf.io,acshi/osf.io,mattclark/osf.io,billyhunt/osf.io,caneruguz/osf.io,cosenal/osf.io,SSJohns/osf.io,njantrania/osf.io,mattclark/osf.io,alexschiller/osf.io,samchrisinger/... |
22ae3a2e9a236de61c078d234d920a3e6bc62d7b | pylisp/application/lispd/address_tree/ddt_container_node.py | pylisp/application/lispd/address_tree/ddt_container_node.py | '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
pass
| '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
'''
A ContainerNode that indicates that we are responsible for this part of
the DDT tree.
'''
| Add a bit of docs | Add a bit of docs
| Python | bsd-3-clause | steffann/pylisp |
54c81494cbbe9a20db50596e68c57e1caa624043 | src-django/authentication/signals/user_post_save.py | src-django/authentication/signals/user_post_save.py | from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def on_user_post_save(sender, instance=None, created=False, **kwar... | from authentication.models import UserProfile
from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def on_user_post_sav... | Add a User post_save hook for creating user profiles | Add a User post_save hook for creating user profiles
| Python | bsd-3-clause | SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder |
d8cb4384f32f4d0e20f3212a36cc01915260f7a8 | tests/routers.py | tests/routers.py | """Search router."""
from rest_framework.routers import DefaultRouter, Route
class SearchRouter(DefaultRouter):
"""Custom router for search endpoints.
Search endpoints don't follow REST principles and thus don't need
routes that default router provides.
"""
routes = [
Route(
... | """Search router."""
from rest_framework.routers import DefaultRouter, DynamicRoute, Route
class SearchRouter(DefaultRouter):
"""Custom router for search endpoints.
Search endpoints don't follow REST principles and thus don't need
routes that default router provides.
"""
routes = [
Route... | Support custom actions in search router | Support custom actions in search router
| Python | apache-2.0 | genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio |
694df5ba69e4e7123009605e59c2b5417a3b52c5 | tools/fitsevt.py | tools/fitsevt.py | #! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fna... | #! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fna... | Remove print statement about number of bins | Remove print statement about number of bins
| Python | mit | fauzanzaid/IUCAA-GRB-detection-Feature-extraction |
d7bea2995fc54c15404b4b47cefae5fc7b0201de | partner_internal_code/res_partner.py | partner_internal_code/res_partner.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
class pa... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
class pa... | FIX partner internal code compatibility with sign up | FIX partner internal code compatibility with sign up
| Python | agpl-3.0 | ingadhoc/partner |
da05fe2d41a077276946c5d6c86995c60315e093 | src/auspex/instruments/__init__.py | src/auspex/instruments/__init__.py | import pkgutil
import importlib
import pyvisa
instrument_map = {}
for loader, name, is_pkg in pkgutil.iter_modules(__path__):
module = importlib.import_module('auspex.instruments.' + name)
if hasattr(module, "__all__"):
globals().update((name, getattr(module, name)) for name in module.__all__)
for name in module... | import pkgutil
import importlib
import pyvisa
instrument_map = {}
for loader, name, is_pkg in pkgutil.iter_modules(__path__):
module = importlib.import_module('auspex.instruments.' + name)
if hasattr(module, "__all__"):
globals().update((name, getattr(module, name)) for name in module.__all__)
for name in module... | Make sure we load pyvisa-py when enumerating instruments. | Make sure we load pyvisa-py when enumerating instruments.
| Python | apache-2.0 | BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex |
4eb4a2eaa42cd71bf4427bdaaa1e853975432691 | graphene/storage/intermediate/general_store_manager.py | graphene/storage/intermediate/general_store_manager.py | from graphene.storage.id_store import *
class GeneralStoreManager:
"""
Handles the creation/deletion of nodes to the NodeStore with ID recycling
"""
def __init__(self, store):
"""
Creates an instance of the GeneralStoreManager
:param store: Store to manage
:return: Ge... | from graphene.storage.id_store import *
class GeneralStoreManager:
"""
Handles the creation/deletion of nodes to the NodeStore with ID recycling
"""
def __init__(self, store):
"""
Creates an instance of the GeneralStoreManager
:param store: Store to manage
:return: Ge... | Allow keyword arguments in GeneralStoreManager.create_item method | Allow keyword arguments in GeneralStoreManager.create_item method
| Python | apache-2.0 | PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene |
6a8c8bc0e407327e5c0e4cae3d4d6ace179a6940 | webserver/codemanagement/serializers.py | webserver/codemanagement/serializers.py | from rest_framework import serializers
from greta.models import Repository
from competition.models import Team
from .models import TeamClient, TeamSubmission
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('id', 'name', 'slug')
class RepoSerializer(seriali... | from rest_framework import serializers
from greta.models import Repository
from competition.models import Team
from .models import TeamClient, TeamSubmission
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('id', 'name', 'slug', 'eligible_to_win')
class Rep... | Add team eligibility to API | Add team eligibility to API
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver |
56d3db6aae71c88ff8b55bb1d173abc025be7e8c | jacquard/tests/test_cli.py | jacquard/tests/test_cli.py | import io
import unittest.mock
import contextlib
import textwrap
from jacquard.cli import main
from jacquard.storage.dummy import DummyStore
def test_smoke_cli_help():
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['--help'])
except SystemExit:
p... | import io
import unittest.mock
import contextlib
import textwrap
from jacquard.cli import main
from jacquard.storage.dummy import DummyStore
def test_smoke_cli_help():
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['--help'])
except SystemExit:
p... | Add test of a write command | Add test of a write command
| Python | mit | prophile/jacquard,prophile/jacquard |
e9df15b0f084ed9e026a5de129b109a3c546f99c | src/libeeyore/parse_tree_to_cpp.py | src/libeeyore/parse_tree_to_cpp.py |
import builtins
from cpp.cpprenderer import EeyCppRenderer
from environment import EeyEnvironment
from values import *
def parse_tree_string_to_values( string ):
return eval( string )
def non_empty_line( ln ):
return ( ln.strip() != "" )
def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ):
env = EeyEnvironmen... | from itertools import imap
import builtins
from cpp.cpprenderer import EeyCppRenderer
from environment import EeyEnvironment
from functionvalues import *
from languagevalues import *
from values import *
def parse_tree_string_to_values( string ):
return eval( string )
def remove_comments( ln ):
i = ln.find( "#" )... | Handle comments in parse tree. | Handle comments in parse tree.
| Python | mit | andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper |
355372ff51a84c0a6d7d86c0ef1fb12def341436 | invada/engine.py | invada/engine.py | # -*- coding: utf-8 -*-
class Engine:
def __init__(self,
response_pairs,
knowledge={}):
self.response_pairs = response_pairs
self.knowledge = knowledge
def chat(self, user_utterance, context):
best_score = 0
best_response_pair = None
... | # -*- coding: utf-8 -*-
class Engine:
def __init__(self,
response_pairs,
knowledge={}):
self.response_pairs = response_pairs
self.knowledge = knowledge
def chat(self, user_utterance, context):
best_score = 0
best_response_pair = None
... | Add the score to Engine.chat return values | Add the score to Engine.chat return values
| Python | mit | carrotflakes/invada |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.