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 |
|---|---|---|---|---|---|---|---|---|---|
cf12d0560e8eaedae054c3276857be84c425a89c | ir/__init__.py | ir/__init__.py | from aqt import mw
from .main import ReadingManager
__version__ = '4.3.1'
mw.readingManager = ReadingManager()
| from aqt import mw
from .main import ReadingManager
mw.readingManager = ReadingManager()
| Remove version number from init | Remove version number from init
| Python | isc | luoliyan/incremental-reading-for-anki,luoliyan/incremental-reading-for-anki |
f57f3a5a7abec6c9c6077c213cf29ef3fd9b4483 | tools/test_sneeze.py | tools/test_sneeze.py |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni"]
def test_from_name... |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni",
... | Add more tests for sneeze. | Add more tests for sneeze. | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD |
3f728b83eb407527588dd5a13a06cc5d1cd11df5 | mfh.py | mfh.py | import mfhclient
import os
import Queue
import sys
import threading
import trigger
import update
def main():
q = Queue.Queue()
updateq = Queue.Queue()
mfhclient_thread = threading.Thread(
args=(q,),
name="mfhclient_thread",
target=mfhclient.main,
)
mfhclient_thread.star... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import update
from arguments import parse
def main():
q = Event()
mfhclient_process = Process(
args=(args, q,),
name="mfhclient_process",
target=mfhclient.main,
)
mfhclient_process... | Switch from multithreading to multiprocessing | Switch from multithreading to multiprocessing
It is easier to work with processes in terms of the current task.
The task was to make the client and updater work at the same time.
Threads have a lot of limitations and are harder to get right, so I
switched to processes.
The code went pretty much straightforward.
Not on... | Python | mit | Zloool/manyfaced-honeypot |
36a2051e8f0c36923d93e172d453ce0e6fe18512 | src/tarsnapper/test.py | src/tarsnapper/test.py | from datetime import datetime
from expire import expire as default_expire_func
__all__ = ('BackupSimulator',)
try:
from collections import OrderedDict # Python 2.7
except ImportError:
# Install from: http://pypi.python.org/pypi/ordereddict
from ordereddict import OrderedDict
class BackupSimulator(o... | from datetime import datetime
from expire import expire as default_expire_func
from config import parse_deltas
__all__ = ('BackupSimulator',)
try:
from collections import OrderedDict # Python 2.7
except ImportError:
# Install from: http://pypi.python.org/pypi/ordereddict
from ordereddict import Order... | Allow using strings for deltas and dates. | Allow using strings for deltas and dates.
| Python | bsd-2-clause | jyrkij/tarsnapper |
ea748053152c048f9ac763a4fb6b97a1815082df | wcsaxes/datasets/__init__.py | wcsaxes/datasets/__init__.py | """Downloads the FITS files that are used in image testing and for building documentation.
"""
from astropy.utils.data import download_file
from astropy.io import fits
def msx_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/msx.fits", cache=cache)
return fits.open(fil... | """Downloads the FITS files that are used in image testing and for building documentation.
"""
from astropy.utils.data import download_file
from astropy.io import fits
URL = 'http://astrofrog.github.io/wcsaxes-datasets/'
def get_hdu(filename, cache=True):
path = download_file(URL + filename, cache=cache)
re... | Simplify datasets functions a bit | Simplify datasets functions a bit
| Python | bsd-3-clause | saimn/astropy,saimn/astropy,StuartLittlefair/astropy,dhomeier/astropy,astropy/astropy,stargaser/astropy,astropy/astropy,larrybradley/astropy,bsipocz/astropy,bsipocz/astropy,kelle/astropy,pllim/astropy,funbaker/astropy,dhomeier/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,dhomeier/astropy,... |
bf307c6fa8c7259d49da2888f91d6bce9fc921cd | src/idea/utility/state_helper.py | src/idea/utility/state_helper.py | from idea.models import State
def get_first_state():
""" Get the first state for an idea. """
return State.objects.get(previous__isnull=True)
| from idea.models import State
def get_first_state():
""" Get the first state for an idea. """
#return State.objects.get(previous__isnull=True)
# previous__isnull breaks functionality if someone creates a new state
# without a previous state set. since we know the initial state
# is id=1 per fixtur... | Fix add_idea when multiple States have no previous | Fix add_idea when multiple States have no previous
| Python | cc0-1.0 | cfpb/idea-box,cfpb/idea-box,cfpb/idea-box |
0948e7a25e79b01dae3c5b6cf9b0c272e2d196b7 | moviepy/video/fx/scroll.py | moviepy/video/fx/scroll.py | import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1... | import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1... | Add int() wrapper to prevent floats | Add int() wrapper to prevent floats
| Python | mit | Zulko/moviepy,ssteo/moviepy,kerstin/moviepy |
9f13b732b68c62a90bbfd2f3fc9ad0c93d54f1e7 | likes/utils.py | likes/utils.py | from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters to set attribute names, so
we can... | from secretballot.models import Vote
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters... | Add common predicate for can_vote | Add common predicate for can_vote
| Python | bsd-3-clause | sandow-digital/django-likes,just-work/django-likes,Afnarel/django-likes,Afnarel/django-likes,just-work/django-likes,chuck211991/django-likes,Afnarel/django-likes,sandow-digital/django-likes,chuck211991/django-likes,chuck211991/django-likes,just-work/django-likes |
e2962b3888a2a82cff8f0f01a213c0a123873f60 | application.py | application.py | #!/usr/bin/env python
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5000, ['./json_schemas'])
@manager.command
def update_index(index_name):
from app.main.services.search_service ... | #!/usr/bin/env python
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5001, ['./mappings'])
@manager.command
def update_index(index_name):
from app.main.services.search_service impo... | Fix local search-api port to 5001 | Fix local search-api port to 5001
When upgrading dmutils I've copied the new `init_manager` code from
the API but forgot to update the port.
Also adds mappings to the list of watched locations for the development
server, so the app will restart if the files are modified.
| Python | mit | alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api |
d51b9786b1cc72dd01549a8547f06efc27aab4c3 | tests/test_settings.py | tests/test_settings.py |
from test_app.settings import *
INSTALLED_APPS += ("cmsplugin_rst",)
## DJANGO CMSPLUGIN RST CONF ##
CMSPLUGIN_RST_WRITER_NAME = "html4css1"
CMSPLUGIN_RST_CONTENT_PREFIX = """
.. |nbsp| unicode:: 0xA0
:trim:
*Global Prefix: Start of Content*
"""
CMSPLUGIN_RST_CONTENT_SUFFIX = \
"""*Global Suffix: End... |
from textwrap import dedent
from test_app.settings import *
INSTALLED_APPS += ("cmsplugin_rst",)
## DJANGO CMSPLUGIN RST CONF ##
if not os.environ.get("CMSPLUGIN_RST_SKIP_CONF"): # use this flag to test the zero-conf case
CMSPLUGIN_RST_WRITER_NAME = "html4css1"
CMSPLUGIN_RST_CONTENT_PREFIX = dedent("""... | Make test settings skippable via CMSPLUGIN_RST_SKIP_CONF environment variable. | Make test settings skippable via CMSPLUGIN_RST_SKIP_CONF environment variable.
| Python | bsd-3-clause | pakal/cmsplugin-rst,ojii/cmsplugin-rst |
ecab0066c8ecd63c1aae85ffd04b970539eae71b | genderator/utils.py | genderator/utils.py | from unidecode import unidecode
class Normalizer:
def normalize(text):
text = Normalizer.remove_extra_whitespaces(text)
text = Normalizer.replace_hyphens(text)
# text = Normalizer.remove_accent_marks(text)
return text.lower()
@staticmethod
def replace_hyphens(text):
... | from unidecode import unidecode
class Normalizer:
def normalize(text):
"""
Normalize a given text applying all normalizations.
Params:
text: The text to be processed.
Returns:
The text normalized.
"""
text = Normalizer.remove_extra_whitesp... | Add accent marks normalization and missing docstrings | Add accent marks normalization and missing docstrings
| Python | mit | davidmogar/genderator |
1a43628a42f249a69e0f8846ebbf88ef0af9bb9d | flow/__init__.py | flow/__init__.py | from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBui... | from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBui... | Make PersistenceSettings a top-level export | Make PersistenceSettings a top-level export
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow |
4ac6905ee4867c038f0574c9c14827164c10f6a6 | tools/unicode_tests.py | tools/unicode_tests.py | # coding: utf-8
"""These tests have to be run separately from the main test suite (iptest),
because that sets the default encoding to utf-8, and it cannot be changed after
the interpreter is up and running. The default encoding in a Python 2.x
environment is ASCII."""
import unittest, sys
from IPython.core import com... | #!/usr/bin/env python
# coding: utf-8
"""These tests have to be run separately from the main test suite (iptest),
because that sets the default encoding to utf-8, and it cannot be changed after
the interpreter is up and running. The default encoding in a Python 2.x
environment is ASCII."""
import unittest
import sys, ... | Add test for reloading history including unicode (currently fails). | Add test for reloading history including unicode (currently fails).
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
78aabbc9c66bc92fdedec740e32ad9fbd9ee8937 | pygraphc/clustering/ConnectedComponents.py | pygraphc/clustering/ConnectedComponents.py | import networkx as nx
class ConnectedComponents:
"""This is a class for connected component detection method to cluster event logs [1]_.
References
----------
.. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log
clustering, in Proceedings... | import networkx as nx
from ClusterUtility import ClusterUtility
class ConnectedComponents:
"""This is a class for connected component detection method to cluster event logs [1]_.
References
----------
.. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication... | Change cluster data structure from list to dict | Change cluster data structure from list to dict
| Python | mit | studiawan/pygraphc |
a39b1e480499c19eee1e7f341964f7c94d6cdbad | st2auth_ldap_backend/__init__.py | st2auth_ldap_backend/__init__.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Fix code so it works under Python 3. | Fix code so it works under Python 3.
| Python | apache-2.0 | StackStorm/st2-auth-backend-ldap |
53a1c2ccbd43a8fcb90d8d9b7814c8ed129c0635 | thumbor_botornado/s3_http_loader.py | thumbor_botornado/s3_http_loader.py | from botornado.s3.bucket import AsyncBucket
from botornado.s3.connection import AsyncS3Connection
from botornado.s3.key import AsyncKey
from thumbor_botornado.s3_loader import S3Loader
from thumbor.loaders.http_loader import HttpLoader
def load(context, url, callback):
p = re.compile('/^https?:/i')
m = p.match(url)... | import thumbor_botornado.s3_loader as S3Loader
import thumbor.loaders.http_loader as HttpLoader
import re
def load(context, url, callback):
if re.match('https?:', url, re.IGNORECASE):
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
| Add s3-http loader which delegates based on the uri | Add s3-http loader which delegates based on the uri
| Python | mit | 99designs/thumbor_botornado,Jimdo/thumbor_botornado,99designs/thumbor_botornado,Jimdo/thumbor_botornado |
be83b28d5a2dedd8caa39cfac57f398af69b2042 | piper/utils.py | piper/utils.py | class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma... | class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma... | Make dict comparisons possible for DotDicts | Make dict comparisons possible for DotDicts
| Python | mit | thiderman/piper |
cca106b4cb647e82838deb359cf6f9ef813992a9 | dbaas/integrations/credentials/admin/integration_credential.py | dbaas/integrations/credentials/admin/integration_credential.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("user","endpoint",)
save_on_top = True | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("endpoint","user",)
save_on_top = True | Change field order at integration credential admin index page | Change field order at integration credential admin index page
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
97cc8b9dd87d43e38d6ff2a20dc4cab2ffcc3d54 | tests/test_requests.py | tests/test_requests.py | import pytest
import ib_insync as ibi
pytestmark = pytest.mark.asyncio
async def test_request_error_raised(ib):
contract = ibi.Stock('MMM', 'SMART', 'USD')
order = ibi.MarketOrder('BUY', 100)
orderState = await ib.whatIfOrderAsync(contract, order)
assert orderState.commission > 0
ib.RaiseReques... | import pytest
import ib_insync as ibi
pytestmark = pytest.mark.asyncio
async def test_request_error_raised(ib):
contract = ibi.Forex('EURUSD')
order = ibi.MarketOrder('BUY', 100)
orderState = await ib.whatIfOrderAsync(contract, order)
assert orderState.commission > 0
ib.RaiseRequestErrors = Tru... | Use EURUSD for test order. | Use EURUSD for test order.
| Python | bsd-2-clause | erdewit/ib_insync,erdewit/ib_insync |
99609e3643c320484c7978440ffedd892f8bb088 | Toolkit/PlayPen/xscale_2_hkl.py | Toolkit/PlayPen/xscale_2_hkl.py | from iotbx.xds.read_ascii import reader
import sys
for n, argv in enumerate(sys.argv[1:]):
r = reader(open(argv))
mas = r.as_miller_arrays(merge_equivalents = False)
assert(len(mas) == 1)
ma = mas[0].apply_scaling(target_max = 9.99e5)
i = ma.data()
s = ma.sigmas()
hkl = ma.indices()
fo... | from iotbx.xds.read_ascii import reader
import sys
for n, argv in enumerate(sys.argv[1:]):
r = reader(open(argv))
mas = r.as_miller_arrays(merge_equivalents = False)
assert(len(mas) == 1)
ma = mas[0].apply_scaling(target_max = 9.99e5)
i = ma.data()
s = ma.sigmas()
hkl = ma.indices()
fo... | Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input) | Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input) | Python | bsd-3-clause | xia2/xia2,xia2/xia2 |
e09d60380f626502532e78494314f9ed97eca7c8 | build-cutline-map.py | build-cutline-map.py | #!/usr/bin/env python
from osgeo import ogr
from osgeo import osr
from glob import glob
import os.path
driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.CreateDataSource("summary-maps/cutline-map.shp")
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
layer = ds.CreateLayer("tiles", srs, ogr.wkbPolygon)... | #!/usr/bin/env python
from osgeo import ogr
from osgeo import osr
from glob import glob
import os.path
driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.CreateDataSource("summary-maps/cutline-map.shp")
srs = osr.SpatialReference()
srs.ImportFromEPSG(26915)
cutline_srs = osr.SpatialReference()
cutline_srs.Im... | Put cutline map in 26915 | Put cutline map in 26915
| Python | mit | simonsonc/mn-glo-mosaic,simonsonc/mn-glo-mosaic,simonsonc/mn-glo-mosaic |
6d7910deebeb68e12c7d7f721c54ada031560024 | src/WhiteLibrary/keywords/items/textbox.py | src/WhiteLibrary/keywords/items/textbox.py | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input):
"""
Writes text to a textbox... | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""
Writes text to a t... | Change to better argument name | Change to better argument name
| Python | apache-2.0 | Omenia/robotframework-whitelibrary,Omenia/robotframework-whitelibrary |
a179b2afff8af8dce5ae816d6f97a002a9151cf4 | booger_test.py | booger_test.py | #!/usr/bin/python
################################################################################
# "THE BEER-WARE LICENSE" (Revision 42):
# <thenoviceoof> wrote this file. As long as you retain this notice
# you can do whatever you want with this stuff. If we meet some day,
# and you think this stuff is worth it, you... | #!/usr/bin/python
################################################################################
# "THE BEER-WARE LICENSE" (Revision 42):
# <thenoviceoof> wrote this file. As long as you retain this notice
# you can do whatever you want with this stuff. If we meet some day,
# and you think this stuff is worth it, you... | Write some more tests for the short nosetests parser | Write some more tests for the short nosetests parser
| Python | mit | thenoviceoof/booger,thenoviceoof/booger |
65731a34e152d085f55893c65607b8fa25dcfd63 | pathvalidate/_interface.py | pathvalidate/_interface.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
from ._common import validate_null_string
from ._six import add_metaclass
@add_metaclass(abc.ABCMeta)
class NameSanitizer(object):
@abc.abstractproperty... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
from ._common import validate_null_string
from ._six import add_metaclass
from .error import ValidationError
@add_metaclass(abc.ABCMeta)
class NameSanitizer... | Add is_valid method for file sanitizer classes | Add is_valid method for file sanitizer classes
| Python | mit | thombashi/pathvalidate |
95d498009eca0a9e179a14eec05e7e3738a72bfb | twitter/stream_example.py | twitter/stream_example.py | """
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible.
USAGE
twitter-stream-example <username> <password>
"""
from __future__ import print_function
import sys
from .stream import TwitterStream
from .auth import UserPassAuth
from .util import prin... | """
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible.
USAGE
stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret>
"""
from __future__ import print_function
import argparse
from twitter.stream import TwitterStream
... | Update to use OAuth, take in command line arguments and modify the imports to function from within the module. | Update to use OAuth, take in command line arguments and modify the imports to function from within the module.
| Python | mit | Adai0808/twitter,tytek2012/twitter,adonoho/twitter,miragshin/twitter,hugovk/twitter,sixohsix/twitter,jessamynsmith/twitter |
70c98a42326471d3ed615def61954905673c5972 | typhon/nonlte/__init__.py | typhon/nonlte/__init__.py | # -*- coding: utf-8 -*-
from .version import __version__
try:
__ATRASU_SETUP__
except:
__ATRASU_SETUP__ = False
if not __ATRASU_SETUP__:
from . import spectra
from . import setup_atmosphere
from . import const
from . import nonltecalc
from . import mathmatics
from . import rtc
| # -*- coding: utf-8 -*-
try:
__ATRASU_SETUP__
except:
__ATRASU_SETUP__ = False
if not __ATRASU_SETUP__:
from . import spectra
from . import setup_atmosphere
from . import const
from . import nonltecalc
from . import mathmatics
from . import rtc
| Remove import of removed version module. | Remove import of removed version module.
| Python | mit | atmtools/typhon,atmtools/typhon |
9ccdbcc01d1bf6323256b8b8f19fa1446bb57d59 | tests/unit/test_authenticate.py | tests/unit/test_authenticate.py | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
def test_valid_data_calls_digital_ocean_record_creation(
mocker, api_key, hostname, domain, fqdn, auth_token):
create_environment = {
'DO_API_KEY': api_key,
... | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
def test_valid_data_calls_digital_ocean_record_creation(
mocker, api_key, hostname, domain, fqdn, auth_token):
create_environment = {
'DO_API_KEY': api_key,
... | Fix Bug in Test Assertion | Fix Bug in Test Assertion
Need to train myself better on red-green-refactor. The previous assert
always passed, because I wasn't triggering an actual Mock method. I had
to change to verifying that the call is in the list of calls. I've
verified that it fails when the call isn't made from the code under
test and that i... | Python | apache-2.0 | Jitsusama/lets-do-dns |
e1291e88e8d5cf1f50e9547fa78a4a53032cc89a | reproject/overlap.py | reproject/overlap.py | from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.):
"""
Compute the overlap between two 'pixels' in spherical coordinates
Parameters
----------
ilon : np.ndarray
The longitudes defining the four corners of the ... | from ._overlap_wrapper import _computeOverlap
def compute_overlap(ilon, ilat, olon, olat):
"""
Compute the overlap between two 'pixels' in spherical coordinates
Parameters
----------
ilon : np.ndarray
The longitudes defining the four corners of the input pixel
ilat : np.ndarray
... | Remove options until we actually need and understand them | Remove options until we actually need and understand them | Python | bsd-3-clause | barentsen/reproject,astrofrog/reproject,barentsen/reproject,mwcraig/reproject,astrofrog/reproject,astrofrog/reproject,mwcraig/reproject,barentsen/reproject,bsipocz/reproject,bsipocz/reproject |
2c1673930a40fc94c3d7c7d4f764ea423b638d26 | mccurse/cli.py | mccurse/cli.py | """Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of sea... | """Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of sea... | Raise error when there is no term to search for | Raise error when there is no term to search for
| Python | agpl-3.0 | khardix/mccurse |
6bdcda14c8bd5b66bc6fcb4bb6a520e326211f74 | poll/models.py | poll/models.py | from django.db import models
class QuestionGroup(models.Model):
heading = models.TextField()
text = models.TextField(blank=True)
date_added = models.DateTimeField(auto_now=True)
date_modified = models.DateTimeField(auto_now_add=True)
class Question(models.Model):
text = models.TextField()
qu... | from django.db import models
class QuestionGroup(models.Model):
heading = models.TextField()
text = models.TextField(blank=True)
date_added = models.DateTimeField(auto_now=True)
date_modified = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id) + ". " + self.he... | Implement __str__ for proper printing in admin | Implement __str__ for proper printing in admin
| Python | mit | gabriel-v/psi,gabriel-v/psi,gabriel-v/psi |
35d5dc83d8abc4e33988ebf26a6fafadf9b815d4 | fontGenerator/util.py | fontGenerator/util.py | import base64, os
def get_content(texts):
if isinstance(texts, str) or isinstance(texts, unicode):
file_path = texts
with open(file_path, 'r') as f:
return list(f.read().decode("utf-8"))
f.close()
else:
return texts
def write_file( path, data ):
with open( pa... | import base64, os
def get_content(texts):
if isinstance(texts, str) or isinstance(texts, unicode):
file_path = texts
with open(file_path, 'r') as f:
return list(f.read().decode("utf-8"))
f.close()
else:
return texts
def write_file( path, data ):
with open( pa... | Use `with` syntax to open file | Use `with` syntax to open file
| Python | mit | eHanlin/font-generator,eHanlin/font-generator |
c43e6a69fa1391b5fd00a43628111f8d52ec8792 | pct_vs_time.py | pct_vs_time.py | from deuces.deuces import Card, Deck
from convenience import who_wins
p1 = [Card.new('As'), Card.new('Ac')]
p2 = [Card.new('Ad'), Card.new('Kd')]
win_record = []
for i in range(100000):
deck = Deck()
b = []
while len(b) < 5:
c = deck.draw()
if c in p1 or c in p2:
continue
... | from deuces.deuces import Card, Deck
from convenience import who_wins, pr
from copy import deepcopy
p1 = [Card.new('As'), Card.new('Ac')]
p2 = [Card.new('Ad'), Card.new('Kd')]
def find_pcts(p1, p2, start_b = [], iter = 10000):
win_record = []
for i in range(iter):
deck = Deck()
b = deepcopy(st... | Make find_pcts() function that can repetitively run. | Make find_pcts() function that can repetitively run.
| Python | mit | zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments |
89a9d812f68fee1bda300be853cdf9536da6ba6b | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Glowstone Organization'
SITENAME = 'Glowstone'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'UTC'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEE... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Glowstone Organization'
SITENAME = 'Glowstone'
SITEURL = ''
PATH = 'content'
PAGE_PATHS = ['']
PAGE_URL = '{slug}/'
PAGE_SAVE_AS = '{slug}/index.html'
TIMEZONE = 'UTC'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_AT... | Move pages to root URL | Move pages to root URL
Fixes #1
| Python | artistic-2.0 | GlowstoneMC/glowstonemc.github.io,GlowstoneMC/glowstonemc.github.io,GlowstoneMC/glowstonemc.github.io |
0292bf82de87483ec0391ecd580e93f42bf6a95b | more/jinja2/main.py | more/jinja2/main.py | import os
import morepath
import jinja2
class Jinja2App(morepath.App):
pass
@Jinja2App.setting_section(section='jinja2')
def get_setting_section():
return {
'auto_reload': False,
'autoescape': True,
'extensions': ['jinja2.ext.autoescape']
}
@Jinja2App.template_engine(extension=... | import os
import morepath
import jinja2
class Jinja2App(morepath.App):
pass
@Jinja2App.setting_section(section='jinja2')
def get_setting_section():
return {
'auto_reload': False,
'autoescape': True,
'extensions': ['jinja2.ext.autoescape']
}
@Jinja2App.template_engine(extension=... | Add another note about caching. | Add another note about caching.
| Python | bsd-3-clause | morepath/more.jinja2 |
82b517426804e9e6984317f4b3aa5bbda5e3dc5e | tests/qctests/test_density_inversion.py | tests/qctests/test_density_inversion.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check density inversion QC test
"""
from numpy import ma
from cotede.qctests import density_inversion
def test():
dummy_data = {
'PRES': ma.masked_array([0.0, 100, 5000]),
'TEMP': ma.masked_array([25.18, 19.73, 2.13]),
'PSAL': ma.masked_... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check density inversion QC test
"""
from numpy import ma
from cotede.qctests import density_inversion
def test():
try:
import gsw
except:
print('GSW package not available. Can\'t run density_inversion test.')
return
dummy_data =... | Exit density inversion test if gsw is not available. | Exit density inversion test if gsw is not available.
| Python | bsd-3-clause | castelao/CoTeDe |
a6491e62201e070665020e8e123d1cd65fc2cca6 | Examples/THINGS/submit_all_THINGS.py | Examples/THINGS/submit_all_THINGS.py |
import os
'''
Submits a job for every sample defined in the info dict
'''
script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/"
submit_file = os.path.join(script_path, "submit_THINGS.pbs")
# Load in the info dict for the names
execfile(os.path.join(script_path, "info_THINGS.py"))
datapath = "/lust... |
import os
from datetime import datetime
'''
Submits a job for every sample defined in the info dict
'''
def timestring():
return datetime.now().strftime("%Y%m%d%H%M%S%f")
script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/"
submit_file = os.path.join(script_path, "submit_THINGS.pbs")
# Load ... | Write the error and output files with the galaxy name and in the right folder | Write the error and output files with the galaxy name and in the right folder
| Python | mit | e-koch/BaSiCs |
443cc0114d7669471e39661c97e2bad91c8eabb8 | tests/basics/set_difference.py | tests/basics/set_difference.py | l = [1, 2, 3, 4]
s = set(l)
outs = [s.difference(),
s.difference({1}),
s.difference({1}, [1, 2]),
s.difference({1}, {1, 2}, {2, 3})]
for out in outs:
print(sorted(out))
s = set(l)
print(s.difference_update())
print(sorted(s))
print(s.difference_update({1}))
print(sorted(s))
print(s.differen... | l = [1, 2, 3, 4]
s = set(l)
outs = [s.difference(),
s.difference({1}),
s.difference({1}, [1, 2]),
s.difference({1}, {1, 2}, {2, 3})]
for out in outs:
print(sorted(out))
s = set(l)
print(s.difference_update())
print(sorted(s))
print(s.difference_update({1}))
print(sorted(s))
print(s.differen... | Add test for set.difference_update with arg being itself. | tests/basics: Add test for set.difference_update with arg being itself.
| Python | mit | blazewicz/micropython,tobbad/micropython,tuc-osg/micropython,henriknelson/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,ryannathans/micropython,Timmenem/micropython,alex-robbins/micropython,PappaPeppar/micropython,dxxb/micropython,Peetz0r/micropython-esp32,jmarcelino/pycom-micropython,hiway/micropython... |
9a4afbab2aded6e6e0ad1088f8cc2d92cfd7684a | 26-lazy-rivers/tf-26.py | 26-lazy-rivers/tf-26.py | #!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
... | #!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
... | Make the last function also a generator, so that the explanation flows better | Make the last function also a generator, so that the explanation flows better
| Python | mit | alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style |
6c2354a1e56477eb983b0adbcc2d15223c158184 | foodsaving/subscriptions/consumers.py | foodsaving/subscriptions/consumers.py | from channels.auth import channel_session_user_from_http, channel_session_user
from django.utils import timezone
from foodsaving.subscriptions.models import ChannelSubscription
@channel_session_user_from_http
def ws_connect(message):
"""The user has connected! Register their channel subscription."""
user = m... | from channels.auth import channel_session_user_from_http, channel_session_user
from django.utils import timezone
from foodsaving.subscriptions.models import ChannelSubscription
@channel_session_user_from_http
def ws_connect(message):
"""The user has connected! Register their channel subscription."""
user = m... | Remove redundant ws accept replies | Remove redundant ws accept replies
It's only relevent on connection
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend |
9f76a0a673b83b2de6a5f8a37b0628796da4a88c | tests/hello/hello/__init__.py | tests/hello/hello/__init__.py | import pkg_resources
version = pkg_resources.require(__name__)[0].version
def greet(name='World'):
print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
| import pkg_resources
try: version = pkg_resources.require(__name__)[0].version
except: version = 'unknown'
def greet(name='World'):
print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
| Allow 'hello' test package to be used unpackaged | Allow 'hello' test package to be used unpackaged
| Python | apache-2.0 | comoyo/python-transmute |
8d5ac7efd98426394040fb01f0096f35a804b1b7 | tests/plugins/test_generic.py | tests/plugins/test_generic.py | import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from .utils import create_har_entry
class TestGenericPlugin(object):
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(Gene... | import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from tests import create_pm
from .utils import create_har_entry
class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class ... | Fix test for generic plugins | Fix test for generic plugins
| Python | mit | spectresearch/detectem |
ade69178edac1d4d73dedee0ad933d4106e22c82 | knox/crypto.py | knox/crypto.py | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from OpenSSL.rand import bytes as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hex... | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
... | Use os.urandom instead of OpenSSL.rand.bytes | Use os.urandom instead of OpenSSL.rand.bytes
Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1 | Python | mit | James1345/django-rest-knox,James1345/django-rest-knox |
d0ca3952a34a74f0167b76bbedfa3cf8875a399c | var/spack/repos/builtin/packages/py-scikit-learn/package.py | var/spack/repos/builtin/packages/py-scikit-learn/package.py | from spack import *
class PyScikitLearn(Package):
""""""
homepage = "https://pypi.python.org/pypi/scikit-learn"
url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz"
version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d')
version('0.16.1', '363ddda501e3b6b617... | from spack import *
class PyScikitLearn(Package):
""""""
homepage = "https://pypi.python.org/pypi/scikit-learn"
url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz"
version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d')
version('0.16.1', '363ddda501e3b6b617... | Add version 0.17.1 of scikit-learn. | Add version 0.17.1 of scikit-learn.
| Python | lgpl-2.1 | matthiasdiener/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spack,iulian787/spack,iulian787/spack,iulian787/spack,mfherbst/spack,tmerrick1/spack,mfherbst/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,mfherbst... |
1d017e9e07e48a8a1960de4c16fd49b4b40abbc2 | ldap-helper.py | ldap-helper.py | # Handles queries to the LDAP backend
# Reads the LDAP server configuration from a JSON file
import json
import ldap
first_connect = True
# The default config filename
config_file = 'config.json'
def load_config():
with open(config_file, 'r') as f:
config = json.load(f)
ldap_server = config['ldap_ser... | # Handles queries to the LDAP backend
# Reads the LDAP server configuration from a JSON file
import json
import ldap
first_connect = True
# The default config filename
config_file = 'config.json'
def load_config():
with open(config_file, 'r') as f:
config = json.load(f)
ldap_server = config['ldap_ser... | Add LDAP version to depend on config instead | Add LDAP version to depend on config instead
| Python | mit | motorolja/ldap-updater |
2a241bd07a4abd66656e3fb505310798f398db7f | respawn/cli.py | respawn/cli.py | """
CLI Entry point for respawn
"""
from docopt import docopt
from schema import Schema, Use, Or
from subprocess import check_call, CalledProcessError
from pkg_resources import require
import respawn
def generate():
"""Generate CloudFormation Template from YAML Specifications
Usage:
respawn <yaml>
respawn --... | """
CLI Entry point for respawn
"""
from docopt import docopt
from schema import Schema, Use, Or
from subprocess import check_call, CalledProcessError
from pkg_resources import require
import respawn
import os
def generate():
"""Generate CloudFormation Template from YAML Specifications
Usage:
respawn <yaml>
... | Remove test print and use better practice to get path of gen.py | Remove test print and use better practice to get path of gen.py
| Python | isc | dowjones/respawn,dowjones/respawn |
6795e8f5c97ba2f10d05725faf4999cfba785fdd | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host)... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
... | Fix test in Ubuntu 20.04. | Fix test in Ubuntu 20.04.
| Python | apache-2.0 | Graylog2/graylog-ansible-role |
c830d67e6b640791e1a8d9117c75ca146ea5d6c8 | spyral/core.py | spyral/core.py | import spyral
import pygame
def init():
spyral.event.init()
pygame.init()
pygame.font.init()
def quit():
pygame.quit()
spyral.director._stack = [] | import spyral
import pygame
_inited = False
def init():
global _inited
if _inited:
return
_inited = True
spyral.event.init()
pygame.init()
pygame.font.init()
def quit():
pygame.quit()
spyral.director._stack = [] | Remove poor way of doing default styles | Remove poor way of doing default styles
Signed-off-by: Robert Deaton <eb00a885478926d5d594195591fb94a03acb1062@udel.edu>
| Python | lgpl-2.1 | platipy/spyral |
6bfe3ee375847d9a71181d618732d747614aede4 | electro/api.py | electro/api.py | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch... | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch... | Raise with endpoint when duplicated. | Raise with endpoint when duplicated.
| Python | mit | soasme/electro |
91853432d2e57bd7c01403c943fff4c2dad1cf5a | openquake/__init__.py | openquake/__init__.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake 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 Licen... | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake 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 Licen... | Make the openquake namespace compatible with old setuptools | Make the openquake namespace compatible with old setuptools
Former-commit-id: b1323f4831645a19d5e927fc342abe4b319a76bb [formerly 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc] [formerly 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc [formerly e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb]]
Former-commit-id: e01df405c03f37a89cdf889c4... | Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine |
4443f6d2493ce6ff9d49cf4049c6a89d2a61eddf | cmt/printers/nc/tests/test_ugrid_read.py | cmt/printers/nc/tests/test_ugrid_read.py | import unittest
import os
from cmt.printers.nc.read import field_fromfile
class DataTestFileMixIn(object):
def data_file(self, name):
return os.path.join(self.data_dir(), name)
def data_dir(self):
return os.path.join(os.path.dirname(__file__), 'data')
class TestNetcdfRead(unittest.TestCase... | import unittest
import os
import urllib2
from cmt.printers.nc.read import field_fromfile
def fetch_data_file(filename):
url = ('http://csdms.colorado.edu/thredds/fileServer/benchmark/ugrid/' +
filename)
remote_file = urllib2.urlopen(url)
with open(filename, 'w') as netcdf_file:
netcdf_... | Read test data files from a remote URL. | Read test data files from a remote URL.
Changed
-------
* Instead of reading test netcdf files from a data directory in the repository, fetch them from a URL.
| Python | mit | csdms/coupling,csdms/coupling,csdms/pymt |
70458f45f3419927271f51872252834f08ef13f2 | workshopvenues/venues/tests.py | workshopvenues/venues/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from .models import Address
class ModelsTest(TestCase):
def test_create_address(self):
a ... | Add Address model creation test case | Add Address model creation test case
| Python | bsd-3-clause | andreagrandi/workshopvenues |
0d2525de51edd99b821f32b3bfd962f3d673a6e1 | Instanssi/admin_store/forms.py | Instanssi/admin_store/forms.py | # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.store.models import StoreItem
class StoreItemForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(StoreItemForm, s... | # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.store.models import StoreItem
class StoreItemForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(StoreItemForm, se... | Remove deprecated fields from form | admin_store: Remove deprecated fields from form
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org |
00fc915c09e0052289fa28d7da174e44f838c15b | quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py | quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "AC6062f793ce5918fef56b1681e6446e87"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = cli... | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = cli... | Use placeholder for account sid :facepalm: | Use placeholder for account sid :facepalm:
| 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 |
2307942c6e29ae24d6d4fdc42a646e4f6843fca8 | echo_client.py | echo_client.py | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_so... | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
buffer = 16
# sends command line message to server, closes socket to writing
client_socket.sendall(ms... | Update client to receive packets larger than buffer | Update client to receive packets larger than buffer
| Python | mit | jwarren116/network-tools,jwarren116/network-tools |
ce963503cea617cb552739b49caeba450e5fb55e | backslash/api_object.py | backslash/api_object.py |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... | Add without_fields method to API objects | Add without_fields method to API objects
Helps with unit-testing Backslash - allowing more percise comparisons
| Python | bsd-3-clause | slash-testing/backslash-python,vmalloc/backslash-python |
7bc736b9a31d532930e9824842f7adb84436a7b8 | django_filters/rest_framework/filters.py | django_filters/rest_framework/filters.py |
from ..filters import *
from ..widgets import BooleanWidget
class BooleanFilter(BooleanFilter):
def __init__(self, *args, **kwargs):
kwargs.setdefault('widget', BooleanWidget)
super().__init__(*args, **kwargs)
|
from ..filters import BooleanFilter as _BooleanFilter
from ..filters import *
from ..widgets import BooleanWidget
class BooleanFilter(_BooleanFilter):
def __init__(self, *args, **kwargs):
kwargs.setdefault('widget', BooleanWidget)
super().__init__(*args, **kwargs)
| Fix mypy error: circular inheritance | Fix mypy error: circular inheritance
Closes #832, #833
| Python | bsd-3-clause | alex/django-filter,alex/django-filter |
8d789a822a34f59d79f0e1129ab7ce5fa945a746 | OctaHomeAppInterface/models.py | OctaHomeAppInterface/models.py | from django.contrib.auth.models import *
from django.contrib.auth.backends import ModelBackend
from django.utils.translation import ugettext_lazy as _
from OctaHomeCore.basemodels import *
from OctaHomeCore.authmodels import *
import string
import random
import hashlib
import time
from authy.api import AuthyApiClient... | from django.contrib.auth.models import *
from django.contrib.auth.backends import ModelBackend
from django.utils.translation import ugettext_lazy as _
from OctaHomeCore.basemodels import *
from OctaHomeCore.authmodels import *
import datetime
import string
import random
import hashlib
import time
from authy.api impor... | Update to make sure the auth date is on utc for time zone support on devices | Update to make sure the auth date is on utc for time zone support on devices
| Python | mit | Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation |
6e4daa3745cf51443550d559493a0cf8c2dbd8f1 | grid_map_demos/scripts/image_publisher.py | grid_map_demos/scripts/image_publisher.py | #!/usr/bin/env python
# simple script to publish a image from a file.
import rospy
import cv2
import sensor_msgs.msg
#change these to fit the expected topic names
IMAGE_MESSAGE_TOPIC = 'grid_map_image'
IMAGE_PATH = 'test2.png'
def callback(self):
""" Convert a image to a ROS compatible message
(sensor_msg... | #!/usr/bin/env python
# simple script to publish a image from a file.
import rospy
import cv2
import sensor_msgs.msg
#change these to fit the expected topic names
IMAGE_MESSAGE_TOPIC = 'grid_map_image'
IMAGE_PATH = 'test2.png'
def callback(self):
""" Convert a image to a ROS compatible message
(sensor_msg... | Read gray scale image with alpha channel | Read gray scale image with alpha channel
| Python | bsd-3-clause | uzh-rpg/grid_map,chen0510566/grid_map,ANYbotics/grid_map,ysonggit/grid_map,ANYbotics/grid_map,ysonggit/grid_map,ethz-asl/grid_map,ethz-asl/grid_map,uzh-rpg/grid_map,chen0510566/grid_map |
0a1056bd1629cc5c2423b83cf1d667ba46274fc9 | scikits/image/io/__init__.py | scikits/image/io/__init__.py | """Utilities to read and write images in various formats."""
from _plugins import load as load_plugin
from _plugins import use as use_plugin
from _plugins import available as plugins
# Add this plugin so that we can read images by default
load_plugin('pil')
from sift import *
from collection import *
from io import... | __doc__ = """Utilities to read and write images in various formats.
The following plug-ins are available:
"""
from _plugins import load as load_plugin
from _plugins import use as use_plugin
from _plugins import available as plugins
from _plugins import info as plugin_info
# Add this plugin so that we can read image... | Add table of available plugins to module docstring. | io: Add table of available plugins to module docstring.
| Python | bsd-3-clause | oew1v07/scikit-image,oew1v07/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,almarklein/scikit-image,robintw/scikit-image,GaelVaroquaux/scikits.image,keflavich/scikit-image,SamHames/scikit-image,almarklein/scikit-image,Warre... |
fd5742bf48691897640d117330d3c1f89276e907 | fft/convert.py | fft/convert.py | from scikits.audiolab import Sndfile
import matplotlib.pyplot as plt
import os
dt = 0.05
Fs = int(1.0/dt)
current_dir = os.path.dirname(__file__)
for (dirpath, dirnames, filenames) in os.walk(current_dir):
for filename in filenames:
path = os.path.join(current_dir + "/" + filename)
print (path)
fname, exte... | from scikits.audiolab import Sndfile
import matplotlib.pyplot as plt
import os
dt = 0.05
Fs = int(1.0/dt)
print 'started...'
current_dir = os.path.dirname(__file__)
print current_dir
for (dirpath, dirnames, filenames) in os.walk(current_dir):
for filename in filenames:
path = os.path.join(current_dir + "/" + fi... | Update spectrogram plot file size | Update spectrogram plot file size
| Python | mit | ritazh/EchoML,ritazh/EchoML,ritazh/EchoML |
d7ce69c7b07782902970a9b21713295f6b1f59ad | audiorename/__init__.py | audiorename/__init__.py | """Rename audio files from metadata tags."""
import sys
from .args import fields, parse_args
from .batch import Batch
from .job import Job
from .message import job_info, stats
fields
__version__: str = '0.0.0'
def execute(*argv: str):
"""Main function
:param list argv: The command line arguments specifie... | """Rename audio files from metadata tags."""
import sys
from importlib import metadata
from .args import fields, parse_args
from .batch import Batch
from .job import Job
from .message import job_info, stats
fields
__version__: str = metadata.version('audiorename')
def execute(*argv: str):
"""Main function
... | Use the version number in pyproject.toml as the single source of truth | Use the version number in pyproject.toml as the single source of truth
From Python 3.8 on we can use importlib.metadata.version('package_name')
to get the current version.
| Python | mit | Josef-Friedrich/audiorename |
dd27eea0ea43447dad321b4b9ec88f24e5ada268 | asv/__init__.py | asv/__init__.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
... | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
... | Add version check for incompatible Python 3.x/virtualenv 1.11 combination | Add version check for incompatible Python 3.x/virtualenv 1.11 combination
| Python | bsd-3-clause | pv/asv,mdboom/asv,airspeed-velocity/asv,waylonflinn/asv,airspeed-velocity/asv,giltis/asv,cpcloud/asv,spacetelescope/asv,mdboom/asv,giltis/asv,edisongustavo/asv,qwhelan/asv,airspeed-velocity/asv,pv/asv,cpcloud/asv,airspeed-velocity/asv,spacetelescope/asv,mdboom/asv,ericdill/asv,ericdill/asv,pv/asv,cpcloud/asv,mdboom/asv... |
16c567f27e1e4979321d319ddb334c263b43443f | gitcv/gitcv.py | gitcv/gitcv.py | import os
import yaml
from git import Repo
class GitCv:
def __init__(self, cv_path, repo_path):
self._cv = self._load_cv(cv_path)
self._repo_path = os.path.join(repo_path, 'cv')
def _load_cv(self, cv_path):
with open(cv_path, "r") as f:
cv = yaml.load(f)
return cv... | import os
import yaml
from git import Repo
class GitCv:
def __init__(self, cv_path, repo_path):
self._repo_path = os.path.join(repo_path, 'cv')
self._cv_path = cv_path
self._load_cv()
def _load_cv(self):
with open(self._cv_path, "r") as f:
self._cv = yaml.load(f)
... | Make cv path class attribute | Make cv path class attribute
| Python | mit | jangroth/git-cv,jangroth/git-cv |
ff4c49b9d89d4f92804ce1d827015072b6b60b7b | addons/sale_margin/__init__.py | addons/sale_margin/__init__.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from functools import partial
import openerp
from openerp import api, SUPERUSER_ID
from . import models # noqa
from . import report # noqa
def uninstall_hook(cr, registry):
def recreate_view(dbname):
... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from functools import partial
import odoo
from odoo import api, SUPERUSER_ID
from . import models # noqa
from . import report # noqa
def uninstall_hook(cr, registry):
def recreate_view(dbname):
d... | Use odoo instead of openerp | [IMP] sale_margin: Use odoo instead of openerp
Closes #23451
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo |
84e9995668d8c34993b9fdf1a95f187897328750 | ex6.py | ex6.py | # left out assignment for types_of_people mentioned in intro
types_of_people = 10
# change variable from 10 to types_of_people
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
# left out f in front of strin... | types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_eval... | Remove unnesessary comments for learners | Remove unnesessary comments for learners
| Python | mit | zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code |
ed10111f92b1f75d852647fe55e260974fab5eb4 | apps/approval/api/serializers.py | apps/approval/api/serializers.py | from rest_framework import serializers
from apps.approval.models import CommitteeApplication, CommitteePriority
class CommitteeSerializer(serializers.ModelSerializer):
group_name = serializers.SerializerMethodField(source='group')
class Meta(object):
model = CommitteePriority
fields = ('grou... | from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework import serializers
from apps.approval.models import CommitteeApplication, CommitteePriority
class CommitteeSerializer(serializers.ModelSerializer):
group_name = serializers.SerializerMethodField(source='group')
c... | Raise DRF ValidationError to get APIException base | Raise DRF ValidationError to get APIException base
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
e081c1944506330a3c01cfe90dcf8deb242bd63b | bin/migrate-tips.py | bin/migrate-tips.py | from gratipay.wireup import db, env
from gratipay.models.team import migrate_all_tips
db = db(env())
if __name__ == '__main__':
migrate_all_tips(db)
| from gratipay.wireup import db, env
from gratipay.models.team.mixins.tip_migration import migrate_all_tips
db = db(env())
if __name__ == '__main__':
migrate_all_tips(db)
| Fix imports in tip migration script | Fix imports in tip migration script
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com |
c2da36340d372deb3ebfc16f395bb32a60a9da12 | rps.py | rps.py | from random import choice
class RPSGame:
shapes = ['rock', 'paper', 'scissors']
draws = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')]
first_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')]
def _evaluate(self, player_move, computer_move):
if (player... | from random import choice
import unittest
class RPSGame:
shapes = ['rock', 'paper', 'scissors']
draws = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')]
first_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')]
def _evaluate(self, player_move, computer_move):
... | Add simple unittest to test computer's strategy. | Add simple unittest to test computer's strategy.
| Python | mit | kubkon/ee106-additional-material |
858a68a66e40ecc5d1a592503166e7096544b8c3 | leetcode/ds_hash_contains_duplicate.py | leetcode/ds_hash_contains_duplicate.py | # @file Contains Duplicate
# @brief Given array of integers, find if array contains duplicates
# https://leetcode.com/problems/contains-duplicate/
'''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in
the array, and it shoul... | # @file Contains Duplicate
# @brief Given array of integers, find if array contains duplicates
# https://leetcode.com/problems/contains-duplicate/
'''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in
the array, and it shoul... | Change keyword val to num | Change keyword val to num | Python | mit | ngovindaraj/Python |
c3f5212dbb7452db48420d717c1815ad4e536c40 | cgen_wrapper.py | cgen_wrapper.py | from cgen import *
from codeprinter import ccode
import ctypes
class Ternary(Generable):
def __init__(self, condition, true_statement, false_statement):
self.condition = ccode(condition)
self.true_statement = ccode(true_statement)
self.false_statement = ccode(false_statement)
def gene... | from cgen import *
import ctypes
def convert_dtype_to_ctype(dtype):
conversion_dict = {'int64': ctypes.c_int64, 'float64': ctypes.c_float}
return conversion_dict[str(dtype)]
| Remove the Ternary class from cgen wrapper | Remove the Ternary class from cgen wrapper
This is no longer required since we are not using preprocessor macros
any more
| Python | mit | opesci/devito,opesci/devito |
a9da17d7edb443bbdee7406875717d30dc4e4bf5 | src/scripts/write_hosts.py | src/scripts/write_hosts.py | #!/usr/bin/python
import os
hostnames = eval(os.environ['hostnames'])
addresses = eval(os.environ['addresses'])
def write_hosts(hostnames, addresses, file):
f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n')
f.write('127.0.0.1 localhost\n\n')
for idx, hostname in enumerate(hostnames):
f.write(addres... | #!/usr/bin/python
import os
hostnames = eval(os.environ['hostnames'])
addresses = eval(os.environ['addresses'])
def write_hosts(hostnames, addresses, file):
f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n')
f.write('127.0.0.1 localhost ' + os.uname()[1] + '\n\n')
for idx, hostname in enumerate(hostname... | Add own hostname to /etc/hosts | Add own hostname to /etc/hosts
| Python | mit | evoila/heat-common,evoila/heat-common |
3e374aa6714b677bd9d9225b155adc5b1ffd680d | stubilous/builder.py | stubilous/builder.py | from functools import partial
def response(callback, method, url, body, status=200):
from stubilous.config import Route
callback(Route(method=method, path=url, body=body, status=status, desc=""))
class Builder(object):
def __init__(self):
self.host = None
self.port = None
self.r... | from functools import partial
from stubilous.config import Route
def response(callback,
method,
url,
body,
status=200,
headers=None,
cookies=None):
callback(Route(method=method,
path=url,
body=body... | Allow cookies and headers in response | Allow cookies and headers in response
| Python | mit | CodersOfTheNight/stubilous |
5a3ed191cb29d328976b33a3bc4a2fa68b0be2e4 | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | from openerp import models, fields
class Course(models.Model):
_name = 'openacademy.course'
name = fields.Char(string='Title', required=True)
description = fields.Text(string='Description')
responsible_id = fields.Many2one('res.users',
ondelete='set null',
... | from openerp import api, models, fields
class Course(models.Model):
_name = 'openacademy.course'
name = fields.Char(string='Title', required=True)
description = fields.Text(string='Description')
responsible_id = fields.Many2one('res.users',
ondelete='set null', ... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | arogel/openacademy-project |
fed8d1d85b929dc21cd49cd2cd0ac660f19e7a36 | comics/crawlers/bizarro.py | comics/crawlers/bizarro.py | from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bizarro'
language = 'no'
url = 'http://www.start.no/tegneserier/bizarro/'
start_date = '1985-01-01'
end_date = '2009-06-24' # No longer hosted at start.no
histo... | from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bizarro'
language = 'no'
url = 'http://underholdning.no.msn.com/tegneserier/bizarro/'
start_date = '1985-01-01'
history_capable_days = 12
schedule = 'Mo,Tu,We,T... | Update 'Bizarro' crawler to use msn.no instead of start.no | Update 'Bizarro' crawler to use msn.no instead of start.no
| Python | agpl-3.0 | klette/comics,datagutten/comics,datagutten/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,jodal/comics |
51aca89cfcac99ffb0fa9304e55fad34a911bdc9 | sconsole/manager.py | sconsole/manager.py | # Import third party libs
import urwid
# Import sconsole libs
import sconsole.cmdbar
import sconsole.static
import sconsole.jidtree
FOOTER = [
('title', 'Salt Console'), ' ',
('key', 'UP'), ' ',
('key', 'DOWN'), ' ']
class Manager(object):
def __init__(self, opts):
self.opts =... | # Import third party libs
import urwid
# Import sconsole libs
import sconsole.cmdbar
import sconsole.static
import sconsole.jidtree
FOOTER = [
('title', 'Salt Console'), ' ',
('key', 'UP'), ' ',
('key', 'DOWN'), ' ']
class Manager(object):
def __init__(self, opts):
self.opts =... | Call an update method to manage incoming jobs | Call an update method to manage incoming jobs
| Python | apache-2.0 | saltstack/salt-console |
2510e85a0b09c3b8a8909d74a25b444072c740a8 | test/test_integration.py | test/test_integration.py | import unittest
import http.client
import time
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google")
response... | import unittest
import http.client
import time
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/httpbin")
respons... | Fix tests to use httpbin.org, return always 200 | Fix tests to use httpbin.org, return always 200
| Python | apache-2.0 | dhiaayachi/dynx,dhiaayachi/dynx |
765dd18fb05c0cef21b9dce7cbddda3c079f0b7d | logtoday/tests.py | logtoday/tests.py | from django.test import TestCase
from django.urls import resolve
class HomePageTest(TestCase):
fixtures = ['tests/functional/auth_dump.json']
def test_root_url_resolves_to_index_page_view(self):
found = resolve("/")
self.assertEqual(found.view_name, "index")
def test_uses_login_template(... | from django.test import TestCase
from django.urls import resolve
class HomePageTest(TestCase):
fixtures = ['tests/functional/auth_dump.json']
def test_root_url_resolves_to_index_page_view(self):
found = resolve("/")
self.assertEqual(found.view_name, "index")
def test_uses_login_template(... | Add unittest for dashboard redirection and template | Add unittest for dashboard redirection and template
Test that checks template rendered by /dashboard endpoint.
| Python | mit | sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily |
2c95054842db106883a400e5d040aafc31b123dd | comics/meta/base.py | comics/meta/base.py | import datetime as dt
from comics.core.models import Comic
class MetaBase(object):
# Required values
name = None
language = None
url = None
# Default values
start_date = None
end_date = None
rights = ''
@property
def slug(self):
return self.__module__.split('.')[-1]
... | import datetime as dt
from comics.core.models import Comic
class MetaBase(object):
# Required values
name = None
language = None
url = None
# Default values
active = True
start_date = None
end_date = None
rights = ''
@property
def slug(self):
return self.__module_... | Add new boolean field MetaBase.active | Add new boolean field MetaBase.active
| Python | agpl-3.0 | jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,datagutten/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics |
7c9b93106d741568e64917ddb4c989a9fecdea17 | typesetter/typesetter.py | typesetter/typesetter.py | from flask import Flask, render_template, jsonify
app = Flask(__name__)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typesetter/data/words.txt') as f:
WORDS = f.read().split('\n')
@app.route('/')
def index():
return render_tem... | from functools import lru_cache
from flask import Flask, render_template, jsonify
app = Flask(__name__)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typesetter/data/words.txt') as f:
WORDS = f.read().split('\n')
@app.route('/')
d... | Use LRU cache to further improve search response times | Use LRU cache to further improve search response times
| Python | mit | rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter |
ec30ac35feb0708414cfa70e8c42425fa25f74c2 | components/utilities.py | components/utilities.py | """Utilities for general operations."""
def IsNumeric(num_str):
try:
val = int(num_str)
except ValueError:
return False
else:
return True
def GuaranteeUnicode(obj):
if type(obj) == unicode:
return obj
elif type(obj) == str:
return unicode(obj, "utf-8")
... | """Utilities for general operations."""
def IsNumeric(num_str):
try:
val = int(num_str)
except ValueError:
return False
else:
return True
def GuaranteeUnicode(obj):
if type(obj) == unicode:
return obj
elif type(obj) == str:
return unicode(obj, "utf-8")
... | Add EscapeHtml function (need to change it to a class) | Add EscapeHtml function (need to change it to a class)
| Python | mit | lnishan/SQLGitHub |
a1acbcfc41a3f55e58e0f240eedcdf6568de4850 | test/contrib/test_securetransport.py | test/contrib/test_securetransport.py | # -*- coding: utf-8 -*-
import contextlib
import socket
import ssl
import pytest
try:
from urllib3.contrib.securetransport import (
WrappedSocket, inject_into_urllib3, extract_from_urllib3
)
except ImportError as e:
pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e)
from ..... | # -*- coding: utf-8 -*-
import contextlib
import socket
import ssl
import pytest
try:
from urllib3.contrib.securetransport import WrappedSocket
except ImportError:
pass
def setup_module():
try:
from urllib3.contrib.securetransport import inject_into_urllib3
inject_into_urllib3()
exce... | Fix skip logic in SecureTransport tests | Fix skip logic in SecureTransport tests | Python | mit | urllib3/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3 |
e2234d41831d513b4da17d1031e2856785d23089 | ui/__init__.py | ui/__init__.py | import multiprocessing as mp
class UI:
def __init__(self, game):
parent_conn, child_conn = mp.Pipe(duplex=False)
self.ui_event_pipe = parent_conn
self.game = game
def get_move(self):
raise Exception("Method 'get_move' not implemented.")
def update(self):
raise Ex... | class UI:
def __init__(self, game):
self.game = game
def get_move(self):
raise Exception("Method 'get_move' not implemented.")
def update(self):
raise Exception("Method 'update' not implemented.")
def run(self, mainloop):
return mainloop()
| Remove unused UI event pipe | Remove unused UI event pipe
| Python | mit | ethanal/othello,ethanal/othello |
f61ba51f92ff47716128bb9d607b4cb46e7bfa4b | gblinks/cli.py | gblinks/cli.py | # -*- coding: utf-8 -*-
import click
import json
import sys
from gblinks import Gblinks
def check_broken_links(gblinks):
broken_links = gblinks.check_broken_links()
if broken_links:
print_links(broken_links)
click.echo(
click.style(
'%d broken links found in the ... | # -*- coding: utf-8 -*-
import click
import json
import sys
from gblinks import Gblinks
def check_broken_links(gblinks):
broken_links = gblinks.check_broken_links()
if broken_links:
print_links(broken_links)
click.echo(
click.style(
'%d broken links found in the ... | Add code to handle exception | Add code to handle exception
| Python | mit | davidmogar/gblinks |
045192dd0a69dfe581075e76bbb7ca4676d321b8 | test_project/urls.py | test_project/urls.py | from django.conf.urls import url
from django.contrib import admin
from django.http import HttpResponse
urlpatterns = [
url(r'^$', lambda request, *args, **kwargs: HttpResponse()),
url(r'^admin/', admin.site.urls),
]
| from django.urls import re_path
from django.contrib import admin
from django.http import HttpResponse
urlpatterns = [
re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()),
re_path(r'^admin/', admin.site.urls),
]
| Replace url() with re_path() available in newer Django | Replace url() with re_path() available in newer Django
| Python | bsd-3-clause | ecometrica/django-vinaigrette |
c30347f34967ee7634676e0e4e27164910f9e52b | regparser/tree/xml_parser/note_processor.py | regparser/tree/xml_parser/note_processor.py | from regparser.tree.depth import markers as mtypes, optional_rules
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor)
class IgnoreNotesHeader(paragraph_processor.BaseMatcher):
"""We don't want to include "Note:" and "Notes:" headers"... | import re
from regparser.tree.depth import markers as mtypes, optional_rules
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor)
class IgnoreNotesHeader(paragraph_processor.BaseMatcher):
"""We don't want to include "Note:" and "Notes... | Use regex rather than string match for Note: | Use regex rather than string match for Note:
Per suggestion from @tadhg-ohiggins
| Python | cc0-1.0 | eregs/regulations-parser,tadhg-ohiggins/regulations-parser,tadhg-ohiggins/regulations-parser,cmc333333/regulations-parser,cmc333333/regulations-parser,eregs/regulations-parser |
49d67984d318d64528244ff525062210f94bd033 | tests/helpers.py | tests/helpers.py | import numpy as np
import glfw
def step_env(env, max_path_length=100, iterations=1):
"""Step env helper."""
for _ in range(iterations):
env.reset()
for _ in range(max_path_length):
_, _, done, _ = env.step(env.action_space.sample())
env.render()
if done:
... | import numpy as np
import glfw
def step_env(env, max_path_length=100, iterations=1):
"""Step env helper."""
for _ in range(iterations):
env.reset()
for _ in range(max_path_length):
_, _, done, _ = env.step(env.action_space.sample())
env.render()
if done:
... | Fix indentation to pass the tests | Fix indentation to pass the tests
| Python | mit | rlworkgroup/metaworld,rlworkgroup/metaworld |
e159465d4495ed2ebcbd1515d82f4f85fc28c8f7 | corral/views/private.py | corral/views/private.py | # -*- coding: utf-8 -*-
"""These JSON-formatted views require authentication."""
from flask import Blueprint, jsonify, request, current_app, g
from werkzeug.exceptions import NotFound
from os.path import join
from ..dl import download
from ..error import handle_errors
from ..util import enforce_auth
private = Bluepri... | # -*- coding: utf-8 -*-
"""These JSON-formatted views require authentication."""
from flask import Blueprint, jsonify, request, current_app, g
from werkzeug.exceptions import NotFound
from os.path import join
from ..dl import download
from ..error import handle_errors
from ..util import enforce_auth
private = Bluepri... | Use a better example error message | Use a better example error message
| Python | mit | nickfrostatx/corral,nickfrostatx/corral,nickfrostatx/corral |
592be8dc73b4da45c948eac133ceb018c60c3be7 | src/pysme/matrix_form.py | src/pysme/matrix_form.py | """Code for manipulating expressions in matrix form
.. module:: matrix_form.py
:synopsis:Code for manipulating expressions in matrix form
.. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com>
"""
import numpy as np
def comm(A, B):
'''Calculate the commutator of two matrices
'''
retur... | """Code for manipulating expressions in matrix form
.. module:: matrix_form.py
:synopsis:Code for manipulating expressions in matrix form
.. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com>
"""
import numpy as np
def comm(A, B):
'''Calculate the commutator of two matrices
'''
retur... | Change euler integrator to return list, not array | Change euler integrator to return list, not array
The state of the system is a heterogeneous data type for some
applications, so the array isn't appropriate.
| Python | mit | CQuIC/pysme |
763077f355386b8a5fdb4bda44f5d2856563f674 | sklearn_porter/estimator/EstimatorApiABC.py | sklearn_porter/estimator/EstimatorApiABC.py | # -*- coding: utf-8 -*-
from typing import Union, Optional, Tuple
from pathlib import Path
from abc import ABC, abstractmethod
from sklearn_porter.enums import Method, Language, Template
class EstimatorApiABC(ABC):
"""
An abstract interface to ensure equal methods between the
main class `sklearn_porter.... | # -*- coding: utf-8 -*-
from typing import Union, Optional, Tuple
from pathlib import Path
from abc import ABC, abstractmethod
from sklearn_porter.enums import Language, Template
class EstimatorApiABC(ABC):
"""
An abstract interface to ensure equal methods between the
main class `sklearn_porter.Estimato... | Remove unused imports and `pass` keywords | feature/oop-api-refactoring: Remove unused imports and `pass` keywords
| Python | bsd-3-clause | nok/sklearn-porter |
605202c7be63f2676b24b5f2202bfa0aa09c9e08 | javelin/ase.py | javelin/ase.py | """Theses functions read the legacy DISCUS stru file format in ASE Atoms."""
from __future__ import absolute_import
from ase.atoms import Atoms
from javelin.utils import unit_cell_to_vectors
def read_stru(filename):
f = open(filename)
lines = f.readlines()
f.close()
a = b = c = alpha = beta = gamma ... | """Theses functions read the legacy DISCUS stru file format in ASE Atoms."""
from __future__ import absolute_import
from ase.atoms import Atoms
from javelin.utils import unit_cell_to_vectors
def read_stru(filename):
with open(filename) as f:
lines = f.readlines()
a = b = c = alpha = beta = gamma = 0... | Use with to open file in read_stru | Use with to open file in read_stru
| Python | mit | rosswhitfield/javelin |
8c5dba68915bb1cdba3c56eff15fdf67c5feed00 | tests/test_global.py | tests/test_global.py |
import unittest
import cbs
class MySettings(cbs.GlobalSettings):
PROJECT_NAME = 'tests'
@property
def TEMPLATE_LOADERS(self):
return super(MySettings, self).TEMPLATE_LOADERS + ('test',)
class GlobalSettingsTest(unittest.TestCase):
def test_precedence(self):
g = {}
cbs.appl... |
import unittest
import cbs
class MySettings(cbs.GlobalSettings):
PROJECT_NAME = 'tests'
@property
def INSTALLED_APPS(self):
return super(MySettings, self).INSTALLED_APPS + ('test',)
class GlobalSettingsTest(unittest.TestCase):
def test_precedence(self):
g = {}
cbs.apply(My... | Update tests for new default globals | Update tests for new default globals
| Python | bsd-2-clause | funkybob/django-classy-settings |
8fb574900a6680f8342487e32979829efa33a11a | spacy/about.py | spacy/about.py | # fmt: off
__title__ = "spacy"
__version__ = "3.0.0.dev14"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/explo... | # fmt: off
__title__ = "spacy_nightly"
__version__ = "3.0.0a0"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/e... | Update parent package and version | Update parent package and version
| Python | mit | explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy |
668f5f588998040cadc320eccc2689551d348bc3 | anki/statsbg.py | anki/statsbg.py | # from subtlepatterns.com
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUPnfzZ0JNZh6kkQus5NUmR7g4Jpxv5XN6nYWNmtlq9o3zuK6w3XRsE1pQIEGPIsdtTP3m2cYwlPv6... | # from subtlepatterns.com
#
# The lines are too long.
# flake8: noqa
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUPnfzZ0JNZh6kkQus5NUmR7g4Jpxv5XN6n... | Make flake8 ignore the bg image. | Make flake8 ignore the bg image.
| Python | agpl-3.0 | ospalh/libanki3 |
ec96669641c9b753c3ce74ce432213a17b0403fe | tests/aggregate_tests.py | tests/aggregate_tests.py | #!/usr/bin/env python
"""
<Program Name>
aggregate_tests.py
<Author>
Konstantin Andrianov.
Zane Fisher.
<Started>
January 26, 2013.
August 2013.
Modified previous behavior that explicitly imported individual
unit tests. -Zane Fisher
<Copyright>
See LICENSE for licensing information.
<Purpose>
Ru... | #!/usr/bin/env python
"""
<Program Name>
aggregate_tests.py
<Author>
Konstantin Andrianov.
Zane Fisher.
<Started>
January 26, 2013.
August 2013.
Modified previous behavior that explicitly imported individual
unit tests. -Zane Fisher
<Copyright>
See LICENSE for licensing information.
<Purpose>
Ru... | Copy and call in-toto's check_usable_gpg function | Copy and call in-toto's check_usable_gpg function
Set environment variable in test aggregate script that may be
used to skip tests if gpg is not available on the test system.
| Python | mit | secure-systems-lab/securesystemslib,secure-systems-lab/securesystemslib |
593d152bd6eec64bc8ee504020ba0e5e2345966c | wafer/pages/views.py | wafer/pages/views.py | from django.http import Http404
from django.core.exceptions import PermissionDenied
from django.views.generic import DetailView, TemplateView, UpdateView
from wafer.pages.models import Page
from wafer.pages.forms import PageForm
class ShowPage(DetailView):
template_name = 'wafer.pages/page.html'
model = Page... | from django.http import Http404
from django.core.exceptions import PermissionDenied
from django.views.generic import DetailView, TemplateView, UpdateView
from wafer.pages.models import Page
from wafer.pages.forms import PageForm
class ShowPage(DetailView):
template_name = 'wafer.pages/page.html'
model = Page... | Remove unneeded field specifier from EditPage form to make Django 1.8 happy | Remove unneeded field specifier from EditPage form to make Django 1.8 happy
| Python | isc | CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer |
3e12e61144fe4cd08f755130dde23066879521d1 | InteractiveCommandLine.UnitTest.py | InteractiveCommandLine.UnitTest.py | import unittest
import MockMockMock
from InteractiveCommandLine import *
class CommandLineCommandExecution( unittest.TestCase ):
def setUp( self ):
self.command = Command()
self.optionHandler = MockMockMock.Mock( "optionHandler" )
self.command.addOption( "option", self.optionHandler )
... | import unittest
import MockMockMock
from InteractiveCommandLine import *
class CommandLineCommandExecution( unittest.TestCase ):
def setUp( self ):
self.command = Command()
self.optionHandler = MockMockMock.Mock( "optionHandler" )
self.command.addOption( "option", self.optionHandler )
... | Fix unit tests for CommandContainer | Fix unit tests for CommandContainer
| Python | mit | jacquev6/InteractiveCommandLine |
22f94c5bb08ee6ae816109bdc06eab9e1974884a | app/models/cnes_professional.py | app/models/cnes_professional.py | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesProfessional(db.Model):
__tablename__ = 'cnes_professional'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
mic... | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesProfessional(db.Model):
__tablename__ = 'cnes_professional'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
mic... | Add CBO column to cnes professional | Add CBO column to cnes professional
| Python | mit | daniel1409/dataviva-api,DataViva/dataviva-api |
66e0e8e2cb202ca3f4832bf728bfd53c084d6f62 | appengine_config.py | appengine_config.py | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom A... | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom A... | Improve custom appstats path normalization. | Improve custom appstats path normalization.
| Python | apache-2.0 | rietveld-codereview/rietveld,openlabs/cr.openlabs.co.in,salomon1184/rietveld,foolonhill/rietveld,andyzsf/rietveld,arg0/rietveld,google-code-export/rietveld,berkus/rietveld,aungzanbaw/rietveld,v3ss0n/rietveld,DeanHere/rietveld,draem0507/rietveld,rietveld-codereview/rietveld,andyzsf/rietveld,dushmis/rietveld,robfig/rietv... |
8868cc4e8379002c62db7f69ca77ec8449930321 | src/adhocracy_core/adhocracy_core/scripts/import_resources.py | src/adhocracy_core/adhocracy_core/scripts/import_resources.py | """Import/create resources into the system.
This is registered as console script 'import_resources' in setup.py.
"""
# pragma: no cover
import argparse
import inspect
import logging
import sys
import transaction
from pyramid.paster import bootstrap
from adhocracy_core import scripts
def import_resources():
"... | """Import/create resources into the system.
This is registered as console script 'import_resources' in setup.py.
"""
# pragma: no cover
import argparse
import inspect
import logging
import sys
import transaction
from pyramid.paster import bootstrap
from . import import_resources as main_import_resources
def impo... | Fix import resources command line wrapper | Fix import resources command line wrapper
| Python | agpl-3.0 | liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.merca... |
dec3aaaefe2afdf4d3ce19dc808257ea49cc2b00 | hsml.py | hsml.py | # -*- coding: utf-8 -*-
"""A small module for computing the smoothing length of a Gadget/Arepo simulation."""
import numpy as np
def get_smooth_length(bar):
"""Figures out if the particles are from AREPO or GADGET
and computes the smoothing length.
Note the Volume array in HDF5 is comoving and this return... | # -*- coding: utf-8 -*-
"""A small module for computing the smoothing length of a Gadget/Arepo simulation."""
import numpy as np
def get_smooth_length(bar):
"""Figures out if the particles are from AREPO or GADGET
and computes the smoothing length.
Note the Volume array in HDF5 is comoving and this return... | Fix for old numpy versions without cbrt | Fix for old numpy versions without cbrt
| Python | mit | sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.