commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
fc5714951bac61f17509eacf8ec2413e14a79ddc | txircd/modules/core/sno_oper.py | txircd/modules/core/sno_oper.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoOper(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeOper"
core = True
def hookIRCd(self, ircd):
self.ircd = ircd
def actions(se... | Add a snomask for OPER attempts | Add a snomask for OPER attempts
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoOper(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeOper"
core = True
def hookIRCd(self, ircd):
self.ircd = ircd
def actions(se... | Add a snomask for OPER attempts
| |
864f5be90fb31529f8ae9b0cf765fcf77504c0c5 | comics/comics/mortenm.py | comics/comics/mortenm.py | # encoding: utf-8
from comics.aggregator.crawler import BaseComicCrawler
from comics.meta.base import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Morten M (vg.no)'
language = 'no'
url = 'http://www.vg.no/spesial/mortenm/'
start_date = '1978-01-01'
history_capable_days = 120
schedule ... | # encoding: utf-8
from comics.aggregator.crawler import BaseComicCrawler
from comics.meta.base import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Morten M (vg.no)'
language = 'no'
url = 'http://www.vg.no/spesial/mortenm/'
start_date = '1978-01-01'
history_capable_days = 120
schedule ... | Add missing chars in URL for 'Morten M' crawler | Add missing chars in URL for 'Morten M' crawler
| Python | agpl-3.0 | klette/comics,jodal/comics,datagutten/comics,datagutten/comics,klette/comics,datagutten/comics,jodal/comics,jodal/comics,klette/comics,datagutten/comics,jodal/comics | # encoding: utf-8
from comics.aggregator.crawler import BaseComicCrawler
from comics.meta.base import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Morten M (vg.no)'
language = 'no'
url = 'http://www.vg.no/spesial/mortenm/'
start_date = '1978-01-01'
history_capable_days = 120
schedule ... | Add missing chars in URL for 'Morten M' crawler
# encoding: utf-8
from comics.aggregator.crawler import BaseComicCrawler
from comics.meta.base import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Morten M (vg.no)'
language = 'no'
url = 'http://www.vg.no/spesial/mortenm/'
start_date = '1978-01... |
fb99c40fa0dcf59aaaf45a14b238a240a453bcaa | climlab/__init__.py | climlab/__init__.py | __version__ = '0.2.4'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation... | __version__ = '0.2.5'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation... | Increment version number to 0.2.5 | Increment version number to 0.2.5
| Python | mit | brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab | __version__ = '0.2.5'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation... | Increment version number to 0.2.5
__version__ = '0.2.4'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convad... |
7a1254fa530b02d32f39e2210ec864f78dd9504a | groundstation/transfer/response_handlers/describeobjects.py | groundstation/transfer/response_handlers/describeobjects.py | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... | Remove hook that snuck in | Remove hook that snuck in
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... | Remove hook that snuck in
from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
... |
7b14e846f08f69601372266ed82f91ba5bd306f6 | devito/core/__init__.py | devito/core/__init__.py | """
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
... | """
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
... | Change autotuning 'none' to 'off' | core: Change autotuning 'none' to 'off'
| Python | mit | opesci/devito,opesci/devito | """
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
... | core: Change autotuning 'none' to 'off'
"""
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, Advance... |
3befcbaf3a78a46edc31cc1910fcd8e0a9381102 | money_conversion/money.py | money_conversion/money.py |
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
| from currency_rates import rates
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
def to_currency(self, new_currency):
new_currency = new_c... | Add to_currency method in order to be able to convert to a new currency | Add to_currency method in order to be able to convert to a new currency
| Python | mit | mdsrosa/money-conversion-py | from currency_rates import rates
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
def to_currency(self, new_currency):
new_currency = new_c... | Add to_currency method in order to be able to convert to a new currency
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
|
6b9c9f98ce10db9e9a767c1ae81c0655c9d4d28c | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_lin... | #!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_lin... | Fix typo is -> as | Fix typo is -> as
| Python | mit | henriquebastos/django-test-without-migrations,henriquebastos/django-test-without-migrations | #!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_lin... | Fix typo is -> as
#!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execu... |
1945a200cb8d517ce16eb039ecb4c3afc67acb9b | bin/checkpypi.py | bin/checkpypi.py | #!/usr/bin/env python
# Adapted from http://code.activestate.com/recipes/577708-check-for-package-updates-on-pypi-works-best-in-pi/
# Changelog:
# - patch to python 3.6
# - include hidden releases
import xmlrpc
import pip
pypi = xmlrpc.client.ServerProxy('https://pypi.python.org/pypi')
for dist in pip.get_installed_... | Check latest version of Python modules in Pypi | Check latest version of Python modules in Pypi | Python | apache-2.0 | verdimrc/linuxcfg,verdimrc/linuxcfg,verdimrc/linuxcfg | #!/usr/bin/env python
# Adapted from http://code.activestate.com/recipes/577708-check-for-package-updates-on-pypi-works-best-in-pi/
# Changelog:
# - patch to python 3.6
# - include hidden releases
import xmlrpc
import pip
pypi = xmlrpc.client.ServerProxy('https://pypi.python.org/pypi')
for dist in pip.get_installed_... | Check latest version of Python modules in Pypi
| |
e2f9c0c0e8b96e44c5410c242d0609ef36b5ee4e | tests/test_ghostscript.py | tests/test_ghostscript.py | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.com... | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
universal_newlines=True,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)... | Make Popen.communicate return output as strings not bytes. | Make Popen.communicate return output as strings not bytes.
| Python | mit | YPlan/treepoem | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
universal_newlines=True,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)... | Make Popen.communicate return output as strings not bytes.
import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=sub... |
abe11541d94a185456a79286bb9e5800c44305c7 | vote.py | vote.py | #!/usr/bin/python
import commands
counter =0
while counter <=100 :
#alocate new Elastic IP, and get the allocation id
(stauts,output) = commands.getstatusoutput("aws ec2 allocate-address")
allocation_id = output.split('\t') [0]
#associate the allocated ip to indicated ec2 instance
(status,output) = commands.... | Add one script to use AWS CLI to allocate/associate/release EIP automatically. | Add one script to use AWS CLI to allocate/associate/release EIP automatically.
| Python | mit | yuecong/tools,yuecong/tools,yuecong/tools,yuecong/tools | #!/usr/bin/python
import commands
counter =0
while counter <=100 :
#alocate new Elastic IP, and get the allocation id
(stauts,output) = commands.getstatusoutput("aws ec2 allocate-address")
allocation_id = output.split('\t') [0]
#associate the allocated ip to indicated ec2 instance
(status,output) = commands.... | Add one script to use AWS CLI to allocate/associate/release EIP automatically.
| |
ff80cf04452c85ff0b93666feb867afa6e4d94f0 | examples/apc2016/train_fcn8s.py | examples/apc2016/train_fcn8s.py | #!/usr/bin/env python
import argparse
import os
import os.path as osp
import chainer
from chainer import cuda
import fcn
import datasets
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--fcn16s', required=True)
parser.add_argument('--gpu', type=int, default=0)
parser.add_argume... | Add trainer for fcn8s on apc2016 | Add trainer for fcn8s on apc2016
| Python | mit | wkentaro/fcn | #!/usr/bin/env python
import argparse
import os
import os.path as osp
import chainer
from chainer import cuda
import fcn
import datasets
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--fcn16s', required=True)
parser.add_argument('--gpu', type=int, default=0)
parser.add_argume... | Add trainer for fcn8s on apc2016
| |
4bcc0aae53def04e16e87499b1321256ff35a7c1 | pyconll/__init__.py | pyconll/__init__.py | """
A library whose purpose is to provide a low level layer between the CoNLL format
and python code.
"""
__all__ = ['exception', 'load', 'tree', 'unit', 'util']
from .load import load_from_string, load_from_file, load_from_url, \
iter_from_string, iter_from_file, iter_from_url
| """
A library whose purpose is to provide a low level layer between the CoNLL format
and python code.
"""
__all__ = ['conllable', 'exception', 'load', 'tree', 'unit', 'util']
from .load import load_from_string, load_from_file, load_from_url, \
iter_from_string, iter_from_file, iter_from_url
| Add conllable to all list. | Add conllable to all list.
| Python | mit | pyconll/pyconll,pyconll/pyconll | """
A library whose purpose is to provide a low level layer between the CoNLL format
and python code.
"""
__all__ = ['conllable', 'exception', 'load', 'tree', 'unit', 'util']
from .load import load_from_string, load_from_file, load_from_url, \
iter_from_string, iter_from_file, iter_from_url
| Add conllable to all list.
"""
A library whose purpose is to provide a low level layer between the CoNLL format
and python code.
"""
__all__ = ['exception', 'load', 'tree', 'unit', 'util']
from .load import load_from_string, load_from_file, load_from_url, \
iter_from_string, iter_from_file, iter_from_url
|
4a1ea1545c6428f3695c001ef9960ea696d20a36 | test_utilities/src/d1_test/instance_generator/sciobj.py | test_utilities/src/d1_test/instance_generator/sciobj.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import re
import StringIO
import d1_common.xml
import d1_test.d1_test_case
import d1_test.instance_generator.identifier
import d1_test.instance_generator.system_metadata
def generate_reproducible(client, pid=None, option_dict=None):
"""Generate science o... | Add instance generator for complete reproducible objects | Add instance generator for complete reproducible objects
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import re
import StringIO
import d1_common.xml
import d1_test.d1_test_case
import d1_test.instance_generator.identifier
import d1_test.instance_generator.system_metadata
def generate_reproducible(client, pid=None, option_dict=None):
"""Generate science o... | Add instance generator for complete reproducible objects
| |
52c2205804d8dc38447bca1ccbf5599e00cd1d7b | main.py | main.py | #!/usr/bin/env python3
import requests
CONFIG_DIR = "config"
class Bot:
def __init__(self):
self.config = Config(CONFIG_DIR)
self.api = TelegramBotApi(self.config.get_auth_token())
def run(self):
self.api.send_message(self.config.get_user_id(), "test")
class TelegramBotApi:
de... | #!/usr/bin/env python3
import requests
CONFIG_DIR = "config"
class Bot:
def __init__(self):
self.config = Config(CONFIG_DIR)
self.api = TelegramBotApi(self.config.get_auth_token())
def run(self):
self.api.send_message(self.config.get_admin_user_id(), "test")
class TelegramBotApi:
... | Rename user_id config key to admin_user_id | Rename user_id config key to admin_user_id
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | #!/usr/bin/env python3
import requests
CONFIG_DIR = "config"
class Bot:
def __init__(self):
self.config = Config(CONFIG_DIR)
self.api = TelegramBotApi(self.config.get_auth_token())
def run(self):
self.api.send_message(self.config.get_admin_user_id(), "test")
class TelegramBotApi:
... | Rename user_id config key to admin_user_id
#!/usr/bin/env python3
import requests
CONFIG_DIR = "config"
class Bot:
def __init__(self):
self.config = Config(CONFIG_DIR)
self.api = TelegramBotApi(self.config.get_auth_token())
def run(self):
self.api.send_message(self.config.get_user_... |
ba3544fc18d5c5e827b1c1777b7811201545a8c5 | boto/pyami/scriptbase.py | boto/pyami/scriptbase.py | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... | Add the command that failed to the error log and the error email to help debug problems where the error produces no output. | Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
| Python | mit | appneta/boto,dimdung/boto,j-carl/boto,ekalosak/boto,drbild/boto,acourtney2015/boto,bryx-inc/boto,darjus-amzn/boto,ddzialak/boto,alfredodeza/boto,vijaylbais/boto,clouddocx/boto,israelbenatar/boto,alex/boto,podhmo/boto,cyclecomputing/boto,shipci/boto,kouk/boto,jindongh/boto,felix-d/boto,Timus1712/boto,alex/boto,lochiicon... | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... | Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self... |
80d052df13653943bc2a2369cfbea4cf0e77ce12 | django_tables/__init__.py | django_tables/__init__.py | __version__ = (0, 3, 'dev')
from memory import *
from models import *
from columns import *
from options import *
| __version__ = (0, 2, 1)
from memory import *
from models import *
from columns import *
from options import *
| Prepare to fix a new version. | Prepare to fix a new version.
| Python | bsd-2-clause | PolicyStat/django-tables,miracle2k/django-tables,isolationism/mongoengine-tables | __version__ = (0, 2, 1)
from memory import *
from models import *
from columns import *
from options import *
| Prepare to fix a new version.
__version__ = (0, 3, 'dev')
from memory import *
from models import *
from columns import *
from options import *
|
5255b69390caa52d7eab096cf95d62bb54fd6dd2 | Lib/test/test_unary.py | Lib/test/test_unary.py | """Test compiler changes for unary ops (+, -, ~) introduced in Python 2.2"""
import unittest
from test_support import run_unittest
class UnaryOpTestCase(unittest.TestCase):
def test_negative(self):
self.assert_(-2 == 0 - 2)
self.assert_(-0 == 0)
self.assert_(--2 == 2)
self.assert_... | Test the unary operator changes to the compiler | Test the unary operator changes to the compiler
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | """Test compiler changes for unary ops (+, -, ~) introduced in Python 2.2"""
import unittest
from test_support import run_unittest
class UnaryOpTestCase(unittest.TestCase):
def test_negative(self):
self.assert_(-2 == 0 - 2)
self.assert_(-0 == 0)
self.assert_(--2 == 2)
self.assert_... | Test the unary operator changes to the compiler
| |
6c20f8a2c722fca1b2f811d4f06ea5480ec6d945 | telethon/events/messagedeleted.py | telethon/events/messagedeleted.py | from .common import EventBuilder, EventCommon, name_inner_event
from ..tl import types
@name_inner_event
class MessageDeleted(EventBuilder):
"""
Event fired when one or more messages are deleted.
"""
def build(self, update):
if isinstance(update, types.UpdateDeleteMessages):
event ... | from .common import EventBuilder, EventCommon, name_inner_event
from ..tl import types
@name_inner_event
class MessageDeleted(EventBuilder):
"""
Event fired when one or more messages are deleted.
"""
def build(self, update):
if isinstance(update, types.UpdateDeleteMessages):
event ... | Set is private/group=True for messages deleted out of channels | Set is private/group=True for messages deleted out of channels
| Python | mit | LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon | from .common import EventBuilder, EventCommon, name_inner_event
from ..tl import types
@name_inner_event
class MessageDeleted(EventBuilder):
"""
Event fired when one or more messages are deleted.
"""
def build(self, update):
if isinstance(update, types.UpdateDeleteMessages):
event ... | Set is private/group=True for messages deleted out of channels
from .common import EventBuilder, EventCommon, name_inner_event
from ..tl import types
@name_inner_event
class MessageDeleted(EventBuilder):
"""
Event fired when one or more messages are deleted.
"""
def build(self, update):
if is... |
5d634511af87150cf1e1b57c52b2bb7136890eb4 | twilix/cmd.py | twilix/cmd.py | import os
import subprocess
import errno
def cmd_pwd(*args):
return subprocess.check_output(['pwd'])
def cmd_ls(*args):
return subprocess.check_output(*args)
def cmd_cd(*args):
if path[0] == '~':
path[0] = os.path.expanduser(path[0])
os.chdir(path[0])
return run_pwd()
def cmd_mkdir(*args... | import os
import subprocess
import errno
def cmd_pwd(*args):
return subprocess.check_output(['pwd'])
def cmd_ls(*args):
return subprocess.check_output(*args)
def cmd_cd(*args):
if args[0][1] == '~':
args[0][1] = os.path.expanduser(args[0][1])
os.chdir(args[0][1])
return cmd_pwd()
def cmd... | Add option tu run piped commands | Add option tu run piped commands
| Python | mit | ueg1990/twilix,ueg1990/twilix | import os
import subprocess
import errno
def cmd_pwd(*args):
return subprocess.check_output(['pwd'])
def cmd_ls(*args):
return subprocess.check_output(*args)
def cmd_cd(*args):
if args[0][1] == '~':
args[0][1] = os.path.expanduser(args[0][1])
os.chdir(args[0][1])
return cmd_pwd()
def cmd... | Add option tu run piped commands
import os
import subprocess
import errno
def cmd_pwd(*args):
return subprocess.check_output(['pwd'])
def cmd_ls(*args):
return subprocess.check_output(*args)
def cmd_cd(*args):
if path[0] == '~':
path[0] = os.path.expanduser(path[0])
os.chdir(path[0])
ret... |
69e081afd1d2b24d40a4992c6af4538aba86ca1c | brew_journal/brew_journal/urls.py | brew_journal/brew_journal/urls.py | from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
... | from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
... | Reset the base url matching regex to correctly reroute to the home page when provided an unknown url | Reset the base url matching regex to correctly reroute to the home page when provided an unknown url
| Python | apache-2.0 | moonboy13/brew-journal,moonboy13/brew-journal,moonboy13/brew-journal | from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
... | Reset the base url matching regex to correctly reroute to the home page when provided an unknown url
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.Sim... |
3e842228beba066000eac536635e7e9d4d87c8e2 | instruments/Instrument.py | instruments/Instrument.py | from traits.api import HasTraits
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items():
setattr(self, key, value)
| from traits.api import HasTraits, Bool
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items(... | Add enabled to top-level instrument class. | Add enabled to top-level instrument class.
| Python | apache-2.0 | Plourde-Research-Lab/PyQLab,rmcgurrin/PyQLab,calebjordan/PyQLab,BBN-Q/PyQLab | from traits.api import HasTraits, Bool
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items(... | Add enabled to top-level instrument class.
from traits.api import HasTraits
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items():
setattr(self, key, v... |
e9d5143b8751bee1d74a5cfebeca848225426d68 | tests/test_special_tokens.py | tests/test_special_tokens.py | from tests import TestCase
class SignedIntegerTokenTestCase(TestCase):
def setup_method(self, method):
TestCase.setup_method(self, method)
self.session.add(
self.TextItem(name=u'index', content=u'some 12-14')
)
self.session.commit()
class TestSignedIntegersWithRemoveH... | Add test case for special tokens | Add test case for special tokens
| Python | bsd-3-clause | cristen/sqlalchemy-searchable | from tests import TestCase
class SignedIntegerTokenTestCase(TestCase):
def setup_method(self, method):
TestCase.setup_method(self, method)
self.session.add(
self.TextItem(name=u'index', content=u'some 12-14')
)
self.session.commit()
class TestSignedIntegersWithRemoveH... | Add test case for special tokens
| |
233d52247d89bb39ccc9ada3a591296baae9cff5 | notification/backends/web.py | notification/backends/web.py | from notification.backends.base import NotificationBackend
class WebBackend(NotificationBackend):
slug = u'web'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def send(self, sender, recipient, notice_type, context, on_site=False,
*args, **kwargs):
"""Always "sends" (i... | from notification.backends.base import NotificationBackend
class WebBackend(NotificationBackend):
slug = u'web'
display_name = u'Web'
formats = ['short.txt', 'full.txt']
def send(self, sender, recipient, notice_type, context, on_site=False,
*args, **kwargs):
"""Always "sends" (i.e.... | Use correct slug for Web backend. | Use correct slug for Web backend.
| Python | mit | theatlantic/django-notification,theatlantic/django-notification | from notification.backends.base import NotificationBackend
class WebBackend(NotificationBackend):
slug = u'web'
display_name = u'Web'
formats = ['short.txt', 'full.txt']
def send(self, sender, recipient, notice_type, context, on_site=False,
*args, **kwargs):
"""Always "sends" (i.e.... | Use correct slug for Web backend.
from notification.backends.base import NotificationBackend
class WebBackend(NotificationBackend):
slug = u'web'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def send(self, sender, recipient, notice_type, context, on_site=False,
*args, **kw... |
12dab867a97241e27eeca44b3919113d379c1850 | setup.py | setup.py | try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='porick',
version='0.1',
description='',
author='',
author_email='',
url='',
install_requires=[
... | try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='porick',
version='0.1',
description='',
author='',
author_email='',
url='',
install_requires=[
... | Use sqlalchemy 0.7.7 instead of 0.6 | Use sqlalchemy 0.7.7 instead of 0.6
| Python | apache-2.0 | kopf/porick,kopf/porick,kopf/porick | try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='porick',
version='0.1',
description='',
author='',
author_email='',
url='',
install_requires=[
... | Use sqlalchemy 0.7.7 instead of 0.6
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='porick',
version='0.1',
description='',
author='',
author_email='',... |
4ba1ea670b208a734aa3f36c694b20e4bb5d6dda | alembic/versions/14ef1fe33bd_add_checkpoint_evaluation_table.py | alembic/versions/14ef1fe33bd_add_checkpoint_evaluation_table.py | """Add checkpoint_evaluation table
Revision ID: 14ef1fe33bd
Revises: 3d0a468b38f
Create Date: 2015-07-10 02:35:06.655075
"""
# revision identifiers, used by Alembic.
revision = '14ef1fe33bd'
down_revision = '3d0a468b38f'
branch_labels = None
depends_on = None
from alembic import op
from bnd.models import Checkpoint... | Write an Alembic migration script | Write an Alembic migration script
| Python | mit | suminb/bnd,suminb/bnd,suminb/bnd | """Add checkpoint_evaluation table
Revision ID: 14ef1fe33bd
Revises: 3d0a468b38f
Create Date: 2015-07-10 02:35:06.655075
"""
# revision identifiers, used by Alembic.
revision = '14ef1fe33bd'
down_revision = '3d0a468b38f'
branch_labels = None
depends_on = None
from alembic import op
from bnd.models import Checkpoint... | Write an Alembic migration script
| |
02363de7bdd7a069243da09248816f3caf38b2e6 | scripts/get-month.py | scripts/get-month.py | #!/usr/bin/env python
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime... | #!/usr/bin/env python
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime... | Update "Active Records" PDF URL | Update "Active Records" PDF URL
| Python | mit | BuzzFeedNews/nics-firearm-background-checks | #!/usr/bin/env python
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime... | Update "Active Records" PDF URL
#!/usr/bin/env python
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).g... |
d30c3b9c574566d9c69fc1322b6a2dfec3a6eb67 | opps/core/admin/article.py | opps/core/admin/article.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from opps.core.models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
def save_model(self, request, obj, form, change):
if not obj.user:
obj.user = request.user
obj.save()
admin.si... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from opps.core.models import Post
from redactor.widgets import RedactorEditor
class PostAdminForm(forms.ModelForm):
class Meta:
model = Post
widgets = {'content': RedactorEditor(),}
class PostAdmin(admin.ModelAd... | Create post admin form, custom content field add texteditor | Create post admin form, custom content field
add texteditor
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from opps.core.models import Post
from redactor.widgets import RedactorEditor
class PostAdminForm(forms.ModelForm):
class Meta:
model = Post
widgets = {'content': RedactorEditor(),}
class PostAdmin(admin.ModelAd... | Create post admin form, custom content field
add texteditor
# -*- coding: utf-8 -*-
from django.contrib import admin
from opps.core.models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
def save_model(self, request, obj, form, change):
if not obj.user:
... |
fd77e3211e2298457b9778f409c56c70a36bf3db | farmers_api/farmers/views.py | farmers_api/farmers/views.py | from rest_framework import viewsets
from .models import Farmer
from .serializers import FarmerSerializer
class FarmerViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializer
filter_fields = ('town',)
| from rest_framework import viewsets, permissions
from .models import Farmer
from .serializers import FarmerSerializer
class FarmerViewSet(viewsets.ModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializer
filter_fields = ('town',)
permissions = permissions.DjangoModelPermissi... | Add permission settings on FarmerViewSet | Add permission settings on FarmerViewSet
| Python | bsd-2-clause | tm-kn/farmers-api | from rest_framework import viewsets, permissions
from .models import Farmer
from .serializers import FarmerSerializer
class FarmerViewSet(viewsets.ModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializer
filter_fields = ('town',)
permissions = permissions.DjangoModelPermissi... | Add permission settings on FarmerViewSet
from rest_framework import viewsets
from .models import Farmer
from .serializers import FarmerSerializer
class FarmerViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializer
filter_fields = ('town',)
|
2f4483440a98f34b650ea09a75f6dc941548f8b2 | zeus/vcs/db.py | zeus/vcs/db.py | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... | Disable asyncpg prepared statement cache | Disable asyncpg prepared statement cache
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... | Disable asyncpg prepared statement cache
import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._co... |
bae805afa67bbced9a968b12c38e1b22e05f8f61 | Findminn.py | Findminn.py | __author__ = "Claytonbat"
from random import randrange
import time
def findMin(alist):
overallmin = alist[0]
for i in alist:
issmallest = True
for j in alist :
if i > j:
issmallest = False
if issmallest:
overallmin = i
return overallmin
d... | Add FindMinn.py file, which contains O(n) and O(n**2) methods in finding the minimum number in a random list. | Add FindMinn.py file, which contains O(n) and O(n**2) methods in finding the minimum number in a random list.
Add author and email.
| Python | mit | mcsoo/Exercises | __author__ = "Claytonbat"
from random import randrange
import time
def findMin(alist):
overallmin = alist[0]
for i in alist:
issmallest = True
for j in alist :
if i > j:
issmallest = False
if issmallest:
overallmin = i
return overallmin
d... | Add FindMinn.py file, which contains O(n) and O(n**2) methods in finding the minimum number in a random list.
Add author and email.
| |
6bec22cd51288c94dff40cf0c973b975538040d5 | tests/integration/minion/test_timeout.py | tests/integration/minion/test_timeout.py | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing fu... | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing fu... | Increase timeout for test_long_running_job test | Increase timeout for test_long_running_job test
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing fu... | Increase timeout for test_long_running_job test
# -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestC... |
fac97130396057802f1ebf21928667a971395ba9 | examples/ex_tabler.py | examples/ex_tabler.py | from tabler import Tabler
table = """<table>
<thead>
<tr>
<th>Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
</tr>
<tr>
<td>1</td>
<td>Bob</td>
<td>Evans</td>
<td>(847) 332-0461</td>
</tr>
<tr>
<td>2</td>
<td>Mary</td>
<td>Newell</td>
... | Add a basic example of the Tabler API. | Add a basic example of the Tabler API.
| Python | bsd-3-clause | bschmeck/tabler | from tabler import Tabler
table = """<table>
<thead>
<tr>
<th>Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
</tr>
<tr>
<td>1</td>
<td>Bob</td>
<td>Evans</td>
<td>(847) 332-0461</td>
</tr>
<tr>
<td>2</td>
<td>Mary</td>
<td>Newell</td>
... | Add a basic example of the Tabler API.
| |
5d0c7b7d209b0487c0a12e995a11efa9d695a50e | pq/management/commands/pqcreate.py | pq/management/commands/pqcreate.py | from django.core.management.base import BaseCommand
from optparse import make_option
from django.conf import settings
from pq.queue import PQ_DEFAULT_JOB_TIMEOUT
class Command(BaseCommand):
help = "Create a queue"
args = "<queue queue ...>"
option_list = BaseCommand.option_list + (
make_option... | Add a command to pre-create queues. | Add a command to pre-create queues.
| Python | bsd-2-clause | bretth/django-pq | from django.core.management.base import BaseCommand
from optparse import make_option
from django.conf import settings
from pq.queue import PQ_DEFAULT_JOB_TIMEOUT
class Command(BaseCommand):
help = "Create a queue"
args = "<queue queue ...>"
option_list = BaseCommand.option_list + (
make_option... | Add a command to pre-create queues.
| |
601d0183674b555c231954dbf92955e8d8918d0a | contrib_bots/bots/wikipedia/test_wikipedia.py | contrib_bots/bots/wikipedia/test_wikipedia.py | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
our_dir = os.path.dirname(os.path.abspath(__file__))
# For dev setups, we can find the API in the repo itself.
if os.path.exists(os.path.join(our_dir, '..')):
sys.path.insert(0, '..')
from bots... | Add tests for wikipedia bot in contrib_bots. | testsuite: Add tests for wikipedia bot in contrib_bots.
Add test file 'Test_wikipedia.py'.
Since wikipedia links for the same query may different according
to relevance. This test will also be written by mocking HTTP
traffic. But this can work for now.
| Python | apache-2.0 | jackrzhang/zulip,verma-varsha/zulip,brockwhittaker/zulip,rishig/zulip,vaidap/zulip,andersk/zulip,dhcrzf/zulip,zulip/zulip,shubhamdhama/zulip,showell/zulip,jrowan/zulip,Galexrt/zulip,rht/zulip,timabbott/zulip,rht/zulip,rishig/zulip,shubhamdhama/zulip,hackerkid/zulip,vabs22/zulip,zulip/zulip,andersk/zulip,kou/zulip,rishi... | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
our_dir = os.path.dirname(os.path.abspath(__file__))
# For dev setups, we can find the API in the repo itself.
if os.path.exists(os.path.join(our_dir, '..')):
sys.path.insert(0, '..')
from bots... | testsuite: Add tests for wikipedia bot in contrib_bots.
Add test file 'Test_wikipedia.py'.
Since wikipedia links for the same query may different according
to relevance. This test will also be written by mocking HTTP
traffic. But this can work for now.
| |
815c246f1ef185e24991efc4075b2358c7955c6c | onadata/libs/utils/storage.py | onadata/libs/utils/storage.py | # coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.j... | # coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
stora... | Use `isinstance()` at the cost of an extra import | Use `isinstance()` at the cost of an extra import
| Python | bsd-2-clause | kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat | # coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
stora... | Use `isinstance()` at the cost of an extra import
# coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for f... |
cb4d916a23792f92f0929693d58350e7b045fb3d | plugins/coinflip.py | plugins/coinflip.py | import random
from plugin import CommandPlugin, PluginException
class CoinFlip(CommandPlugin):
"""
Flip a coin
"""
max_coin_flips = 1000000
def __init__(self):
CommandPlugin.__init__(self)
self.triggers = ['coin', 'coinflip']
self.short_help = 'Flip a coin'
self.he... | Add CoinFlip plugin for some coin flipping fun | Add CoinFlip plugin for some coin flipping fun
| Python | mit | Brottweiler/nimbus,itsmartin/nimbus,Plastix/nimbus,bcbwilla/nimbus | import random
from plugin import CommandPlugin, PluginException
class CoinFlip(CommandPlugin):
"""
Flip a coin
"""
max_coin_flips = 1000000
def __init__(self):
CommandPlugin.__init__(self)
self.triggers = ['coin', 'coinflip']
self.short_help = 'Flip a coin'
self.he... | Add CoinFlip plugin for some coin flipping fun
| |
d20f04d65437138559445bf557be52a87690c7f2 | test/checker/test_checker_ipaddress.py | test/checker/test_checker_ipaddress.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
from ipaddress import ip_address
import itertools
import pytest
import six
from typepy import (
Typecode,
StrictLevel,
)
from typepy.type import IpAddress
nan = float("nan")
i... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
from ipaddress import ip_address
import itertools
import pytest
import six
from typepy import (
Typecode,
StrictLevel,
)
from typepy.type import IpAddress
nan = float("nan")
i... | Change class definitions from old style to new style | Change class definitions from old style to new style
| Python | mit | thombashi/typepy | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
from ipaddress import ip_address
import itertools
import pytest
import six
from typepy import (
Typecode,
StrictLevel,
)
from typepy.type import IpAddress
nan = float("nan")
i... | Change class definitions from old style to new style
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
from ipaddress import ip_address
import itertools
import pytest
import six
from typepy import (
Typecode,
StrictLevel,
)
fr... |
53b9eff3ffc1768d3503021e7248351e24d59af7 | tests/httpd.py | tests/httpd.py | import SimpleHTTPServer
import BaseHTTPServer
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_POST(s):
s.send_response(200)
s.end_headers()
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class(('0.0.0.0', 8328), Handler)
try:
... | import BaseHTTPServer
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
content_type = self.headers.getheader('content-type')
content_length = int(self.headers.getheader('content-length'))
self.send_response(200)
self.send_header('Content-Type', content_type)
... | Fix test http server, change to echo back request body | Fix test http server, change to echo back request body | Python | bsd-2-clause | chop-dbhi/django-webhooks,pombredanne/django-webhooks,pombredanne/django-webhooks,chop-dbhi/django-webhooks | import BaseHTTPServer
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
content_type = self.headers.getheader('content-type')
content_length = int(self.headers.getheader('content-length'))
self.send_response(200)
self.send_header('Content-Type', content_type)
... | Fix test http server, change to echo back request body
import SimpleHTTPServer
import BaseHTTPServer
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_POST(s):
s.send_response(200)
s.end_headers()
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = se... |
26f1506607a2042d508dc69f5a155ed88668d22a | setup.py | setup.py | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "ideone",
version = "0.0.1",
author = "Joe Schafer",
author_email = "joe@jschaf.com",
url = "http://github.com/jschaf",
description = "A Python binding t... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "ideone",
version = "0.0.1",
author = "Joe Schafer",
author_email = "joe@jschaf.com",
url = "http://github.com/jschaf/ideone-api/",
description = "A Pyth... | Fix url to point to repository. | Fix url to point to repository.
| Python | bsd-3-clause | jschaf/ideone-api | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "ideone",
version = "0.0.1",
author = "Joe Schafer",
author_email = "joe@jschaf.com",
url = "http://github.com/jschaf/ideone-api/",
description = "A Pyth... | Fix url to point to repository.
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "ideone",
version = "0.0.1",
author = "Joe Schafer",
author_email = "joe@jschaf.com",
url = "http://github.com/jschaf",
... |
bf36831f062c8262e9d7f8a5f63b5b4a0f413c5f | 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')
# check if MongoDB package is installed
def test_mongodb_is_installed(host):
package = host.package('mongodb-org')
assert package.is_ins... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB package is installed
def test_mongodb_is_installed(host):
package = host.package('mongodb-org')
assert package.is_ins... | Add test of mongodb package version | Add test of mongodb package version
| Python | bsd-2-clause | jugatsu-infra/ansible-role-mongodb | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB package is installed
def test_mongodb_is_installed(host):
package = host.package('mongodb-org')
assert package.is_ins... | Add test of mongodb package version
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB package is installed
def test_mongodb_is_installed(host):
package = host.package('mo... |
c407c067495d76ebed7c36ef005861c80fdcfdce | textx/__init__.py | textx/__init__.py | __version__ = "1.6.dev"
| from textx.metamodel import metamodel_from_file, metamodel_from_str # noqa
from textx.langapi import get_language, iter_languages # noqa
__version__ = "1.6.dev"
| Make metamodel factory methods and lang API available in textx package. | Make metamodel factory methods and lang API available in textx package.
| Python | mit | igordejanovic/textX,igordejanovic/textX,igordejanovic/textX | from textx.metamodel import metamodel_from_file, metamodel_from_str # noqa
from textx.langapi import get_language, iter_languages # noqa
__version__ = "1.6.dev"
| Make metamodel factory methods and lang API available in textx package.
__version__ = "1.6.dev"
|
dad58aa0162290627e9d96a5047a507237a49b76 | calculate.py | calculate.py |
operators = {'+', '-', '*', '/', '(', ')'}
def parse_formula(text):
tokens = []
buffer = ''
for c in text:
if '0' <= c <= '9':
buffer += c
elif c in operators:
if buffer:
tokens.append(int(buffer))
tokens.append(c)
buffer =... | # List of operators along with their associated precedence
operators = {None: 100, '+': 3, '-': 3, '*': 2, '/': 2, '(': 1, ')': 1}
def operation(v1, v2, operator):
if item == '+':
return v1 + v2
elif item == '-':
return v1 - v2
elif item == '*':
return v1 * v2
elif item == '/':... | Add support for basic binary operations | Add support for basic binary operations
| Python | mit | MichaelAquilina/Simple-Calculator | # List of operators along with their associated precedence
operators = {None: 100, '+': 3, '-': 3, '*': 2, '/': 2, '(': 1, ')': 1}
def operation(v1, v2, operator):
if item == '+':
return v1 + v2
elif item == '-':
return v1 - v2
elif item == '*':
return v1 * v2
elif item == '/':... | Add support for basic binary operations
operators = {'+', '-', '*', '/', '(', ')'}
def parse_formula(text):
tokens = []
buffer = ''
for c in text:
if '0' <= c <= '9':
buffer += c
elif c in operators:
if buffer:
tokens.append(int(buffer))
... |
3f39c9d89da004556bcf53fa815f88a3092f600e | syft/frameworks/torch/tensors/native.py | syft/frameworks/torch/tensors/native.py | import random
from syft.frameworks.torch.tensors import PointerTensor
import syft
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = syft.local_worker
def ... | import random
from syft.frameworks.torch.tensors import PointerTensor
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = None
def create_pointer(
se... | Set local worker as default for SyftTensor owner | Undone: Set local worker as default for SyftTensor owner
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | import random
from syft.frameworks.torch.tensors import PointerTensor
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = None
def create_pointer(
se... | Undone: Set local worker as default for SyftTensor owner
import random
from syft.frameworks.torch.tensors import PointerTensor
import syft
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.... |
b8359e6b04d13f550aec308308f2e91e194bc372 | uberlogs/handlers/kill_process.py | uberlogs/handlers/kill_process.py | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | Remove repetitive getMessage calls in KillProcesshandler | Remove repetitive getMessage calls in KillProcesshandler
| Python | mit | odedlaz/uberlogs,odedlaz/uberlogs | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | Remove repetitive getMessage calls in KillProcesshandler
import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for ... |
cf0193adcf6c58d82b577f09842c265bc09a685a | candidates/csv_helpers.py | candidates/csv_helpers.py | import csv
import StringIO
from .models import CSV_ROW_FIELDS
def encode_row_values(d):
return {
k: unicode('' if v is None else v).encode('utf-8')
for k, v in d.items()
}
def list_to_csv(candidates_list):
output = StringIO.StringIO()
writer = csv.DictWriter(
output,
f... | import csv
import StringIO
from .models import CSV_ROW_FIELDS
def encode_row_values(d):
return {
k: unicode('' if v is None else v).encode('utf-8')
for k, v in d.items()
}
def candidate_sort_key(row):
return (row['constituency'], row['name'].split()[-1])
def list_to_csv(candidates_list):... | Sort the rows in CSV output on (constituency, last name) | Sort the rows in CSV output on (constituency, last name)
| Python | agpl-3.0 | datamade/yournextmp-popit,openstate/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit... | import csv
import StringIO
from .models import CSV_ROW_FIELDS
def encode_row_values(d):
return {
k: unicode('' if v is None else v).encode('utf-8')
for k, v in d.items()
}
def candidate_sort_key(row):
return (row['constituency'], row['name'].split()[-1])
def list_to_csv(candidates_list):... | Sort the rows in CSV output on (constituency, last name)
import csv
import StringIO
from .models import CSV_ROW_FIELDS
def encode_row_values(d):
return {
k: unicode('' if v is None else v).encode('utf-8')
for k, v in d.items()
}
def list_to_csv(candidates_list):
output = StringIO.StringI... |
bc20949f8e5461d6ffa901d24677acb1bae922dd | mangopaysdk/types/payinexecutiondetailsdirect.py | mangopaysdk/types/payinexecutiondetailsdirect.py | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | Add StatementDescriptor for card direct payins | Add StatementDescriptor for card direct payins | Python | mit | chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | Add StatementDescriptor for card direct payins
from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.Secu... |
984dd9d20814e3190ee197b47c756f2b8f4ecb52 | django_prometheus/testutils.py | django_prometheus/testutils.py | from prometheus_client import REGISTRY
METRIC_EQUALS_ERR_EXPLANATION = """
%s%s = %s, expected %s.
The values for %s are:
%s"""
class PrometheusTestCaseMixin(object):
"""A collection of utilities that make it easier to write test cases
that interact with metrics.
"""
def setUp(self):
self.cl... | Add a mixin to test exported metrics. | Add a mixin to test exported metrics.
Most of this mixin should be moved to prometheus_client eventually,
since it relies heavily on its internals.
| Python | apache-2.0 | wangwanzhong/django-prometheus,obytes/django-prometheus,obytes/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus,DingaGa/django-prometheus,korfuri/django-prometheus | from prometheus_client import REGISTRY
METRIC_EQUALS_ERR_EXPLANATION = """
%s%s = %s, expected %s.
The values for %s are:
%s"""
class PrometheusTestCaseMixin(object):
"""A collection of utilities that make it easier to write test cases
that interact with metrics.
"""
def setUp(self):
self.cl... | Add a mixin to test exported metrics.
Most of this mixin should be moved to prometheus_client eventually,
since it relies heavily on its internals.
| |
cb30232b201934622efb2f972cca5087a1373cf7 | src/waldur_mastermind/marketplace_remote/extension.py | src/waldur_mastermind/marketplace_remote/extension.py | from waldur_core.core import WaldurExtension
class MarketplaceRemoteExtension(WaldurExtension):
@staticmethod
def django_app():
return 'waldur_mastermind.marketplace_remote'
@staticmethod
def is_assembly():
return True
@staticmethod
def django_urls():
from .urls impor... | from waldur_core.core import WaldurExtension
class MarketplaceRemoteExtension(WaldurExtension):
@staticmethod
def django_app():
return 'waldur_mastermind.marketplace_remote'
@staticmethod
def is_assembly():
return True
@staticmethod
def django_urls():
from .urls impor... | Increase frequency of order items pulling. | Increase frequency of order items pulling.
| Python | mit | opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind | from waldur_core.core import WaldurExtension
class MarketplaceRemoteExtension(WaldurExtension):
@staticmethod
def django_app():
return 'waldur_mastermind.marketplace_remote'
@staticmethod
def is_assembly():
return True
@staticmethod
def django_urls():
from .urls impor... | Increase frequency of order items pulling.
from waldur_core.core import WaldurExtension
class MarketplaceRemoteExtension(WaldurExtension):
@staticmethod
def django_app():
return 'waldur_mastermind.marketplace_remote'
@staticmethod
def is_assembly():
return True
@staticmethod
... |
0261a0f9a1dde9f9f6167e3630561219e3dca124 | statsmodels/datasets/__init__.py | statsmodels/datasets/__init__.py | """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
| """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
| Switch to relative imports and fix pep-8 | STY: Switch to relative imports and fix pep-8
| Python | bsd-3-clause | bsipocz/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,hlin117/statsmodels,bashtage/statsmodels,nguyentu1602/statsmodels,hlin117/statsmodels,musically-ut/statsmodels,yl565/statsmodels,jstoxrocky/statsmodels,wwf5067/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,bert9bert/statsmodels,astocko/statsmodels,jse... | """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
| STY: Switch to relative imports and fix pep-8
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair,... |
421dbe962dae44cad7aa734a397cb16fe9b1632f | reactive/datanode.py | reactive/datanode.py | from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
... | from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDF... | Update charms.hadoop reference to follow convention | Update charms.hadoop reference to follow convention
| Python | apache-2.0 | johnsca/layer-apache-hadoop-datanode,juju-solutions/layer-apache-hadoop-datanode | from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDF... | Update charms.hadoop reference to follow convention
from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
... |
17f4e610e272d24c9178e43caa79a6f7c17a568b | tests/test_orderbook.py | tests/test_orderbook.py | from src import orderbook as ob
def test_create_msg_incrementing_message_id():
first_message = ob.create_msg()
second_message = ob.create_msg()
assert first_message['message-id'] == 0, 'Expected 0, got {}'.format(first_message['message-id'])
assert second_message['message-id'] == 1, 'Expected 1, got ... | Add some basic testing for orderbook.create_msg. | Add some basic testing for orderbook.create_msg.
| Python | mit | Tribler/decentral-market | from src import orderbook as ob
def test_create_msg_incrementing_message_id():
first_message = ob.create_msg()
second_message = ob.create_msg()
assert first_message['message-id'] == 0, 'Expected 0, got {}'.format(first_message['message-id'])
assert second_message['message-id'] == 1, 'Expected 1, got ... | Add some basic testing for orderbook.create_msg.
| |
c8a41bbf11538dbc17de12e32ba5af5e93fd0b2c | src/utils/plugins.py | src/utils/plugins.py | from utils import models
class Plugin:
plugin_name = None
display_name = None
description = None
author = None
short_name = None
stage = None
manager_url = None
version = None
janeway_version = None
is_workflow_plugin = False
jump_url = None
handshake_url = None
... | from utils import models
class Plugin:
plugin_name = None
display_name = None
description = None
author = None
short_name = None
stage = None
manager_url = None
version = None
janeway_version = None
is_workflow_plugin = False
jump_url = None
handshake_url = None
... | Add get_self and change get_or_create to avoid mis-creation. | Add get_self and change get_or_create to avoid mis-creation.
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | from utils import models
class Plugin:
plugin_name = None
display_name = None
description = None
author = None
short_name = None
stage = None
manager_url = None
version = None
janeway_version = None
is_workflow_plugin = False
jump_url = None
handshake_url = None
... | Add get_self and change get_or_create to avoid mis-creation.
from utils import models
class Plugin:
plugin_name = None
display_name = None
description = None
author = None
short_name = None
stage = None
manager_url = None
version = None
janeway_version = None
is_workflow_p... |
424aa401806ddf536b9bc75efb1493561a5c2a5b | product/views.py | product/views.py | from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.shortcuts import render
from django.contrib.messages.views import SuccessMessageMixin
from product.models import ProductCategory
# Create your ... | from django.http import HttpResponseRedirect
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.shortcuts import render
from django.contrib import messages
from django.contrib.messages.views impo... | Make messages show in delete view. | Make messages show in delete view.
| Python | mit | borderitsolutions/amadaa,borderitsolutions/amadaa,borderitsolutions/amadaa | from django.http import HttpResponseRedirect
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.shortcuts import render
from django.contrib import messages
from django.contrib.messages.views impo... | Make messages show in delete view.
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.shortcuts import render
from django.contrib.messages.views import SuccessMessageMixin
from product.models im... |
2b8869bb508f4fb67867385f3058372bde664ca5 | CheckProxy/CheckProxy.py | CheckProxy/CheckProxy.py | import discord
import requests
from discord.ext import commands
class checkproxy:
"""Cog for proxy checking"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def checkproxy(self, ctx, proxy):
"""Checks the provided proxy."""
p = proxy
... | import discord
import requests
from discord.ext import commands
class checkproxy:
"""Cog for proxy checking"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def checkproxy(self, ctx, proxy):
"""Checks the provided proxy."""
p = proxy
... | Add 5s timeout to checkproxy (in an effort to prevent bot hanging | Add 5s timeout to checkproxy (in an effort to prevent bot hanging
| Python | agpl-3.0 | FrostTheFox/RocketMap-cogs | import discord
import requests
from discord.ext import commands
class checkproxy:
"""Cog for proxy checking"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def checkproxy(self, ctx, proxy):
"""Checks the provided proxy."""
p = proxy
... | Add 5s timeout to checkproxy (in an effort to prevent bot hanging
import discord
import requests
from discord.ext import commands
class checkproxy:
"""Cog for proxy checking"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def checkproxy(self, ctx, proxy... |
6448691ed77be2fd74761e056eeb5f16a881fd54 | test_settings.py | test_settings.py | from foundry.settings import *
# We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
# in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
... | from foundry.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# Need this last line until django-setuptest is improved.
| Adjust test settings to be in line with jmbo-skeleton | Adjust test settings to be in line with jmbo-skeleton
| Python | bsd-3-clause | praekelt/jmbo-competition,praekelt/jmbo-competition | from foundry.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# Need this last line until django-setuptest is improved.
| Adjust test settings to be in line with jmbo-skeleton
from foundry.settings import *
# We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
# in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': '... |
f9343573e2d1b3f3960c99eb90b5df7aad1573ca | python/problem4.py | python/problem4.py | for i in range(10, 100):
for j in range(i, 100):
n = i * j
if str(n) == str(n)[::-1]:
print "{} x {} = {}".format(i, j, n)
for i in range(100, 1000):
for j in range(i, 1000):
n = i * j
if str(n) == str(n)[::-1]:
print "{} x {} = {}".format(i, j, n)
| Solve problem 4 with python. | Solve problem 4 with python.
| Python | mit | a-suenami/challenge-project-euler,a-suenami/challenge-project-euler | for i in range(10, 100):
for j in range(i, 100):
n = i * j
if str(n) == str(n)[::-1]:
print "{} x {} = {}".format(i, j, n)
for i in range(100, 1000):
for j in range(i, 1000):
n = i * j
if str(n) == str(n)[::-1]:
print "{} x {} = {}".format(i, j, n)
| Solve problem 4 with python.
| |
202fba50c287d3df99b22a4f30a96a3d8d9c8141 | tests/test_pypi.py | tests/test_pypi.py | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
... | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
... | Update test after adding cleaning of dist | test: Update test after adding cleaning of dist
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
... | test: Update test after adding cleaning of dist
from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username'... |
925864a916e5c06b58cac1caa3f2bac5907bbbd3 | grader/grader/grade/__init__.py | grader/grader/grade/__init__.py | '''TODO: Grade package docs
'''
from grader.grade.main import grade
from docker import Client
help = "Grade assignments"
def setup_parser(parser):
parser.add_argument('folder', metavar='folder',
help='Folder of tarballs or assignment folders.')
parser.add_argument('--image', default='... | '''TODO: Grade package docs
'''
from grader.grade.main import grade
from docker import Client
help = "Grade assignments"
def setup_parser(parser):
parser.add_argument('folder', metavar='folder',
help='Folder of tarballs or assignment folders.')
parser.add_argument('--image', default='... | Fix a flake style issue | Fix a flake style issue
| Python | mit | redkyn/grader,grade-it/grader,redkyn/grader | '''TODO: Grade package docs
'''
from grader.grade.main import grade
from docker import Client
help = "Grade assignments"
def setup_parser(parser):
parser.add_argument('folder', metavar='folder',
help='Folder of tarballs or assignment folders.')
parser.add_argument('--image', default='... | Fix a flake style issue
'''TODO: Grade package docs
'''
from grader.grade.main import grade
from docker import Client
help = "Grade assignments"
def setup_parser(parser):
parser.add_argument('folder', metavar='folder',
help='Folder of tarballs or assignment folders.')
parser.add_argu... |
2c7b64ea22ebe7e35945550f5726a72a721213b4 | minitests/litex/src.yosys/missing_bit_report.py | minitests/litex/src.yosys/missing_bit_report.py | """ Generates a missing feature/bit report for LiteX design.
This script is fairly fragile, because it depends on the specific observation
that all of the remaining bits appear to either belong to HCLK_IOI or IOI3
tiles. A more general version of this script could be created, but that was
not the point of this scrip... | Create script for generating remaining bit report. | Create script for generating remaining bit report.
This report is fairly fragile, but works well enough for the remaining
LiteX bits.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
| Python | isc | SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray | """ Generates a missing feature/bit report for LiteX design.
This script is fairly fragile, because it depends on the specific observation
that all of the remaining bits appear to either belong to HCLK_IOI or IOI3
tiles. A more general version of this script could be created, but that was
not the point of this scrip... | Create script for generating remaining bit report.
This report is fairly fragile, but works well enough for the remaining
LiteX bits.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
| |
429bd22a98895252dfb993d770c9b3060fef0fe3 | tests/runalldoctests.py | tests/runalldoctests.py | import doctest
import glob
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
testfiles = glob.glob('*.txt')
for file in testfiles:
doctest.testfile(file)
| import doctest
import getopt
import glob
import sys
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
def run(pattern):
if pattern is None:
testfiles = glob.glob('*.txt')
else:
testfiles = glob.glob(pattern)
fo... | Add option to pick single test file from the runner | Add option to pick single test file from the runner
| Python | bsd-3-clause | datagovuk/OWSLib,kwilcox/OWSLib,QuLogic/OWSLib,KeyproOy/OWSLib,tomkralidis/OWSLib,menegon/OWSLib,datagovuk/OWSLib,datagovuk/OWSLib,dblodgett-usgs/OWSLib,ocefpaf/OWSLib,mbertrand/OWSLib,gfusca/OWSLib,jaygoldfinch/OWSLib,daf/OWSLib,JuergenWeichand/OWSLib,bird-house/OWSLib,geographika/OWSLib,kalxas/OWSLib,Jenselme/OWSLib,... | import doctest
import getopt
import glob
import sys
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
def run(pattern):
if pattern is None:
testfiles = glob.glob('*.txt')
else:
testfiles = glob.glob(pattern)
fo... | Add option to pick single test file from the runner
import doctest
import glob
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
testfiles = glob.glob('*.txt')
for file in testfiles:
doctest.testfile(file)
|
affad020348ca8aa6a7b9431811d707ab8f6d99a | pyramid/__init__.py | pyramid/__init__.py | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0-dev"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except Nam... | Bump version for v0.7.0 release | Bump version for v0.7.0 release
| Python | mit | tgsmith61591/pyramid,alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except Nam... | Bump version for v0.7.0 release
# -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0-dev"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodu... |
33524fe8cad5f8bf4448c7dd7426d1e1452bb324 | example_of_usage.py | example_of_usage.py | # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: GPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprint... | # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: AGPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprin... | Change license according to project license | Change license according to project license
| Python | agpl-3.0 | schmijos/html-table-parser-python3,schmijos/html-table-parser-python3 | # -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: AGPLv3
#
# Sample script for parsing HTML tables
# -----------------------------------------------------------------------------
import urllib.request
from pprin... | Change license according to project license
# -----------------------------------------------------------------------------
# Created: 04.03.2014
# Copyright: (c) Josua Schmid 2014
# Licence: GPLv3
#
# Sample script for parsing HTML tables
# -------------------------------------------------------------------... |
8fc4713375c4eadd83ec376c3e839d921c39b5dc | src/encoded/predicates.py | src/encoded/predicates.py | from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
se... | from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if... | Allow specification of multiple subpath_segments | Allow specification of multiple subpath_segments
| Python | mit | 4dn-dcic/fourfront,ClinGen/clincoded,kidaa/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,hms-dbmi/fourfront,philiptzou/clincoded,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/encoded,ENCODE-DCC/encoded,ClinGen/clincoded,T2DREAM/t2dream-portal,kidaa/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,ClinGen/clinco... | from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if... | Allow specification of multiple subpath_segments
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object... |
7b5de280562f5984b04c63432de8f28e03b57cbd | firecares/firestation/migrations/0020_update_greeley_headquarters_location.py | firecares/firestation/migrations/0020_update_greeley_headquarters_location.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.gis.geos import Point
from django.db import models, migrations
from genericm2m.utils import monkey_patch
class Migration(migrations.Migration):
dependencies = [
('firestation', '0019_assign-station-number-2'),
('... | Move Union Colony Fire rescue authority to correct location | Move Union Colony Fire rescue authority to correct location
| Python | mit | HunterConnelly/firecares,HunterConnelly/firecares,HunterConnelly/firecares,meilinger/firecares,FireCARES/firecares,FireCARES/firecares,HunterConnelly/firecares,FireCARES/firecares,FireCARES/firecares,meilinger/firecares,meilinger/firecares,meilinger/firecares,FireCARES/firecares | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.gis.geos import Point
from django.db import models, migrations
from genericm2m.utils import monkey_patch
class Migration(migrations.Migration):
dependencies = [
('firestation', '0019_assign-station-number-2'),
('... | Move Union Colony Fire rescue authority to correct location
| |
95e1d4c2ec42f09fddf48c5a32f0fe409132380b | lab/monitors/nova_service_list.py | lab/monitors/nova_service_list.py | def start(lab, log, args):
import time
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
duration = args['duration']
period = args['period']
statuses = {'up': 1, 'down': 0}
server = lab.director()
start_time = time.time()
while start_tim... | def start(lab, log, args):
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
statuses = {'up': 1, 'down': 0}
server = lab.director()
with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_N... | Verify services status if FI is rebooted | Verify services status if FI is rebooted
Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2
| Python | apache-2.0 | CiscoSystems/os-sqe,CiscoSystems/os-sqe,CiscoSystems/os-sqe | def start(lab, log, args):
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
statuses = {'up': 1, 'down': 0}
server = lab.director()
with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_N... | Verify services status if FI is rebooted
Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2
def start(lab, log, args):
import time
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
duration = args['duration']
period = args['period']
statuses = {'... |
eb33d70bfda4857fbd76616cf3bf7fb7d7feec71 | spoj/00005/palin.py | spoj/00005/palin.py | #!/usr/bin/env python3
def next_palindrome(k):
palin = list(k)
n = len(k)
mid = n // 2
# case 1: forward right
just_copy = False
for i in range(mid, n):
mirrored = n - 1 - i
if k[i] < k[mirrored]:
just_copy = True
if just_copy:
palin[i] = palin[mirrored]
# case 2: backward left
if not just_copy:... | #!/usr/bin/env python3
def next_palindrome(k):
palin = list(k)
n = len(k)
mid = n // 2
# case 1: forward right
just_copy = False
for i in range(mid, n):
mirrored = n - 1 - i
if k[i] < k[mirrored]:
just_copy = True
if just_copy:
palin[i] = palin[mirrored]
# case 2: backward left
if not just_copy:... | Fix bug in ranges (to middle) | Fix bug in ranges (to middle)
- in SPOJ palin
Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
| Python | mit | mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming | #!/usr/bin/env python3
def next_palindrome(k):
palin = list(k)
n = len(k)
mid = n // 2
# case 1: forward right
just_copy = False
for i in range(mid, n):
mirrored = n - 1 - i
if k[i] < k[mirrored]:
just_copy = True
if just_copy:
palin[i] = palin[mirrored]
# case 2: backward left
if not just_copy:... | Fix bug in ranges (to middle)
- in SPOJ palin
Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
#!/usr/bin/env python3
def next_palindrome(k):
palin = list(k)
n = len(k)
mid = n // 2
# case 1: forward right
just_copy = False
for i in range(mid, n):
mirrored = n - 1 - i
if k[i] ... |
4bc31e675659af54ee26fe5df16a0ee3ebeb5947 | firefed/__main__.py | firefed/__main__.py | import argparse
import os
import re
from firefed import Firefed
from feature import feature_map, Summary
def feature_type(val):
try:
return feature_map()[val]
except KeyError as key:
raise argparse.ArgumentTypeError(
'Feature %s not found. Choose from: {%s}' %
(key, ', ... | import argparse
import os
import re
from firefed import Firefed
from feature import feature_map, Summary
def feature_type(val):
try:
return feature_map()[val]
except KeyError as key:
raise argparse.ArgumentTypeError(
'Feature %s not found. Choose from: {%s}' %
(key, ', ... | Add default argument for profile | Add default argument for profile
| Python | mit | numirias/firefed | import argparse
import os
import re
from firefed import Firefed
from feature import feature_map, Summary
def feature_type(val):
try:
return feature_map()[val]
except KeyError as key:
raise argparse.ArgumentTypeError(
'Feature %s not found. Choose from: {%s}' %
(key, ', ... | Add default argument for profile
import argparse
import os
import re
from firefed import Firefed
from feature import feature_map, Summary
def feature_type(val):
try:
return feature_map()[val]
except KeyError as key:
raise argparse.ArgumentTypeError(
'Feature %s not found. Choose f... |
faae5df8648afbfa5921bd67a7f3e082ba626a95 | poyo/__init__.py | poyo/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
from .parser import parse_string
__all__ = ['parse_string']
| # -*- coding: utf-8 -*-
from .parser import parse_string
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
__all__ = ['parse_string']
| Move module level import to top of file | Move module level import to top of file
| Python | mit | hackebrot/poyo | # -*- coding: utf-8 -*-
from .parser import parse_string
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
__all__ = ['parse_string']
| Move module level import to top of file
# -*- coding: utf-8 -*-
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
from .parser import parse_string
__all__ = ['parse_string']
|
4604cf73a45e8bcecf38238366cfdac37cdb7897 | pyfr/readers/base.py | pyfr/readers/base.py | # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _op... | # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
... | Fix a bug in the mesh optimizer. | Fix a bug in the mesh optimizer.
| Python | bsd-3-clause | iyer-arvind/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,tjcorona/PyFR | # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
... | Fix a bug in the mesh optimizer.
# -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfr... |
e1240aa33b286ba52507128458fc6d6b3b68dfb3 | statsmodels/stats/multicomp.py | statsmodels/stats/multicomp.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 18:27:25 2012
Author: Josef Perktold
"""
from statsmodels.sandbox.stats.multicomp import MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapper around ... | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 18:27:25 2012
Author: Josef Perktold
"""
from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapp... | Put back an import that my IDE incorrectly flagged as unused | Put back an import that my IDE incorrectly flagged as unused
| Python | bsd-3-clause | gef756/statsmodels,detrout/debian-statsmodels,detrout/debian-statsmodels,bzero/statsmodels,YihaoLu/statsmodels,wzbozon/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,musically-ut/statsmodels,josef-pkt/statsmodels,cbmoore/statsmodels,rgommers/statsmodels,hlin117/statsmodels,ChadFulton/statsmodels,edhuckle/statsmod... | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 18:27:25 2012
Author: Josef Perktold
"""
from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with TukeyHSD confidence intervals
this is just a wrapp... | Put back an import that my IDE incorrectly flagged as unused
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 18:27:25 2012
Author: Josef Perktold
"""
from statsmodels.sandbox.stats.multicomp import MultiComparison
def pairwise_tukeyhsd(endog, groups, alpha=0.05):
'''calculate all pairwise comparisons with Tuk... |
c1785e0713a5af6b849baaa1b314a13ac777f3f5 | tests/test_str_py3.py | tests/test_str_py3.py | from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
import fastavro
from fastavro.compat import BytesIO
letters = ascii_uppercase + digits
id_size = 100
seed('str_py3') # Repeatable results
def gen_id():
return ''.join(choice(letters) for _ in range(id_size))
k... | # -*- coding: utf-8 -*-
"""Python3 string tests for fastavro"""
from __future__ import absolute_import
from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
import fastavro
... | Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually. | Test files shouldn't import 'fastavro.compat'. Just import BytesIO
manually.
| Python | mit | e-heller/fastavro,e-heller/fastavro | # -*- coding: utf-8 -*-
"""Python3 string tests for fastavro"""
from __future__ import absolute_import
from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
import fastavro
... | Test files shouldn't import 'fastavro.compat'. Just import BytesIO
manually.
from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
import fastavro
from fastavro.compat import BytesIO
letters = ascii_uppercase + digits
id_size = 100
seed('str_py3') # Repeatable results
... |
a08604f85b82300a4a3b4f2e70f91c3ee129859b | openelex/tests/test_fetch.py | openelex/tests/test_fetch.py | from unittest import TestCase
from openelex.base.fetch import ErrorHandlingURLopener, HTTPError
class TestErrorHandlingURLopener(TestCase):
def setUp(self):
self.opener = ErrorHandlingURLopener()
def test_404(self):
url = "http://example.com/test.csv"
self.assertRaises(HTTPError, self... | Add missing test for ErrorHandlingURLopener | Add missing test for ErrorHandlingURLopener
I forgot to add this with commit
df9cfda52e952bb4d69cc0ee724e713cd6f468d5
| Python | mit | cathydeng/openelections-core,datamade/openelections-core,openelections/openelections-core,datamade/openelections-core,openelections/openelections-core,cathydeng/openelections-core | from unittest import TestCase
from openelex.base.fetch import ErrorHandlingURLopener, HTTPError
class TestErrorHandlingURLopener(TestCase):
def setUp(self):
self.opener = ErrorHandlingURLopener()
def test_404(self):
url = "http://example.com/test.csv"
self.assertRaises(HTTPError, self... | Add missing test for ErrorHandlingURLopener
I forgot to add this with commit
df9cfda52e952bb4d69cc0ee724e713cd6f468d5
| |
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 | # -*- 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... | [IMP] sale_margin: Use odoo instead of openerp
Closes #23451
# -*- 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 u... |
10a0d12f39760d2c2d57f66bc445f0cb87cde69f | django_website/aggregator/management/commands/mark_defunct_feeds.py | django_website/aggregator/management/commands/mark_defunct_feeds.py | import urllib2
from django.core.management.base import BaseCommand
from django_website.apps.aggregator.models import Feed
class Command(BaseCommand):
"""
Mark people with 404'ing feeds as defunct.
"""
def handle(self, *args, **kwargs):
verbose = kwargs.get('verbosity')
for f in Feed.obj... | import urllib2
from django.core.management.base import BaseCommand
from django_website.apps.aggregator.models import Feed
class Command(BaseCommand):
"""
Mark people with 404'ing feeds as defunct.
"""
def handle(self, *args, **kwargs):
verbose = kwargs.get('verbosity')
for f in Feed.obj... | Set feed update timeouts in a more modern way. | Set feed update timeouts in a more modern way.
| Python | bsd-3-clause | vxvinh1511/djangoproject.com,gnarf/djangoproject.com,hassanabidpk/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,nanuxbe/django,django/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoprojec... | import urllib2
from django.core.management.base import BaseCommand
from django_website.apps.aggregator.models import Feed
class Command(BaseCommand):
"""
Mark people with 404'ing feeds as defunct.
"""
def handle(self, *args, **kwargs):
verbose = kwargs.get('verbosity')
for f in Feed.obj... | Set feed update timeouts in a more modern way.
import urllib2
from django.core.management.base import BaseCommand
from django_website.apps.aggregator.models import Feed
class Command(BaseCommand):
"""
Mark people with 404'ing feeds as defunct.
"""
def handle(self, *args, **kwargs):
verbose = k... |
6dfc5a3d7845633570b83aac06c47756292cf8ac | st2common/tests/unit/test_db_model_uids.py | st2common/tests/unit/test_db_model_uids.py | # 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 this file except in compliance with
# the License. You may obtain a ... | Add tests for get_uid() method for common DB models. | Add tests for get_uid() method for common DB models.
| Python | apache-2.0 | dennybaa/st2,StackStorm/st2,pixelrebel/st2,Itxaka/st2,Plexxi/st2,pixelrebel/st2,nzlosh/st2,punalpatel/st2,nzlosh/st2,Itxaka/st2,emedvedev/st2,dennybaa/st2,tonybaloney/st2,Plexxi/st2,punalpatel/st2,peak6/st2,dennybaa/st2,StackStorm/st2,tonybaloney/st2,peak6/st2,StackStorm/st2,StackStorm/st2,armab/st2,alfasin/st2,nzlosh/... | # 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 this file except in compliance with
# the License. You may obtain a ... | Add tests for get_uid() method for common DB models.
| |
c1dc3c503d09e95321fc6f3fe3d7ab114ff58fc9 | patty/segmentation/pointCloudMeasurer.py | patty/segmentation/pointCloudMeasurer.py | import numpy as np
from sklearn.decomposition import PCA
def measureLength(pointCloud):
"""Returns the length of a point cloud in its longest direction."""
if len(pointCloud) == 0:
return 0
pca = PCA(n_components = 1)
pca.fit(np.asarray(pointCloud))
primary_axis = np... | import numpy as np
from sklearn.decomposition import PCA
def measureLength(pointCloud):
"""Returns the length of a point cloud in its longest direction."""
if len(pointCloud) == 0:
return 0
pca = PCA(n_components = 1)
pc_array = np.asarray(pointCloud)
pca.fit(pc_arra... | Make sure np.array is used for PCA in measureLength | Make sure np.array is used for PCA in measureLength
| Python | apache-2.0 | NLeSC/PattyAnalytics | import numpy as np
from sklearn.decomposition import PCA
def measureLength(pointCloud):
"""Returns the length of a point cloud in its longest direction."""
if len(pointCloud) == 0:
return 0
pca = PCA(n_components = 1)
pc_array = np.asarray(pointCloud)
pca.fit(pc_arra... | Make sure np.array is used for PCA in measureLength
import numpy as np
from sklearn.decomposition import PCA
def measureLength(pointCloud):
"""Returns the length of a point cloud in its longest direction."""
if len(pointCloud) == 0:
return 0
pca = PCA(n_components = 1)
... |
44e5d35b6d43a22a480000b39a4e85335a27904b | corehq/apps/es/management/commands/wipe_es.py | corehq/apps/es/management/commands/wipe_es.py | from django.core.management import BaseCommand
from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new
class Command(BaseCommand):
"""
Wipe all data from BlobDB.
"""
def add_arguments(self, parser):
parser.add_argument(
'--commit',... | from django.core.management import BaseCommand
from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new
from corehq.util.es.elasticsearch import IndicesClient
class Command(BaseCommand):
"""
Wipe all data from BlobDB.
"""
def add_arguments(self, parser... | Use IndicesClient to get full URL | Use IndicesClient to get full URL
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from django.core.management import BaseCommand
from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new
from corehq.util.es.elasticsearch import IndicesClient
class Command(BaseCommand):
"""
Wipe all data from BlobDB.
"""
def add_arguments(self, parser... | Use IndicesClient to get full URL
from django.core.management import BaseCommand
from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new
class Command(BaseCommand):
"""
Wipe all data from BlobDB.
"""
def add_arguments(self, parser):
parser.ad... |
2f1bcd83bf9069e5fc599aa20e1ed533bebd5e67 | Detect_Face_Sides.py | Detect_Face_Sides.py | import numpy as np
def get_leftside_average(self):
"""Return Array of Left Most Points."""
width = self.size[0]
height = self.size[1]
left_most_points = []
for row in range(height):
for column in range(width):
if image.getpixel(row, column) > 200:
left_most_point... | import numpy as np
def get_leftside_average(self):
"""Return the value of the Average of the left_most_points."""
width = self.size[0]
height = self.size[1]
left_most_points = []
for row in range(height):
for column in range(width):
if image.getpixel(row, column) > 200:
... | Add get_rightside_face and Fix bug | Add get_rightside_face and Fix bug
| Python | mit | anassinator/codejam-2014,anassinator/codejam | import numpy as np
def get_leftside_average(self):
"""Return the value of the Average of the left_most_points."""
width = self.size[0]
height = self.size[1]
left_most_points = []
for row in range(height):
for column in range(width):
if image.getpixel(row, column) > 200:
... | Add get_rightside_face and Fix bug
import numpy as np
def get_leftside_average(self):
"""Return Array of Left Most Points."""
width = self.size[0]
height = self.size[1]
left_most_points = []
for row in range(height):
for column in range(width):
if image.getpixel(row, column) > ... |
2c2c51d5fa0594aa2d160d28c15895ece358cafe | setup.py | setup.py | #!/usr/bin/env python3
from os import curdir, pardir
from os.path import join
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "VapourSynth",
description = "A frameserver for the 21st century",
url = "http://www.vapoursynth.com... | #!/usr/bin/env python3
from os import curdir, pardir
from os.path import join
from distutils.core import setup
from Cython.Distutils import Extension, build_ext
setup(
name = "VapourSynth",
description = "A frameserver for the 21st century",
url = "http://www.vapoursynth.com/",
download_url = "http://... | Use the Cython Extension class so we can place generated C files in the build dir. | Use the Cython Extension class so we can place generated C files in the build dir.
git-svn-id: ac1113e4705722bd5ee69cef058b32c421e857b8@491 f9120d27-2007-6f97-8312-0f4ebfa7710f
| Python | lgpl-2.1 | Kamekameha/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth,Kamekameha/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth | #!/usr/bin/env python3
from os import curdir, pardir
from os.path import join
from distutils.core import setup
from Cython.Distutils import Extension, build_ext
setup(
name = "VapourSynth",
description = "A frameserver for the 21st century",
url = "http://www.vapoursynth.com/",
download_url = "http://... | Use the Cython Extension class so we can place generated C files in the build dir.
git-svn-id: ac1113e4705722bd5ee69cef058b32c421e857b8@491 f9120d27-2007-6f97-8312-0f4ebfa7710f
#!/usr/bin/env python3
from os import curdir, pardir
from os.path import join
from distutils.core import setup
from distutils.extension imp... |
dbb9becd09bbb9808060272b74e664afc354dfa8 | modeltranslation/tests/settings.py | modeltranslation/tests/settings.py | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
from django.conf import settings
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
LANGUAGES = (('de', 'Deutsch'),
('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'de'
USE_I18N... | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import django
from django.conf import settings
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
LANGUAGES = (('de', 'Deutsch'),
('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = ... | Set empty MIGRATION_MODULES setting for Django 1.11. Should make the tests run again. | Set empty MIGRATION_MODULES setting for Django 1.11. Should make the tests run again.
| Python | bsd-3-clause | deschler/django-modeltranslation,deschler/django-modeltranslation | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import django
from django.conf import settings
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
LANGUAGES = (('de', 'Deutsch'),
('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = ... | Set empty MIGRATION_MODULES setting for Django 1.11. Should make the tests run again.
# -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
from django.conf import settings
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
LANGUAGES = (('de', 'Deutsch'),
('e... |
4bf26b6d976171b5a388134ad9716af639f15a3b | setup.py | setup.py | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()
requires = [
'oauth2client',
]
tests_require = []
testing_requires = tests_require + [
'no... | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()
requires = [
'oauth2client',
'google-api-python-client',
]
tests_require = []
testing_r... | Add the Google API client as a requirement | Add the Google API client as a requirement
| Python | isc | GuardedRisk/Google-Apps-Auditing | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()
requires = [
'oauth2client',
'google-api-python-client',
]
tests_require = []
testing_r... | Add the Google API client as a requirement
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()
requires = [
'oauth2client',
]
tests_require = []
t... |
72fb6ca12b685809bd5de0c5df9f051eef1163c4 | test/TestBaseUtils.py | test/TestBaseUtils.py | import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
def test_word_segmenter(self):
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
def test_word_segmente... | ''' Tests for BaseUtils
'''
import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
''' Main test class for the BaseUtils '''
def test_word_segmenter_with_empty(self):
''' For an empty string, the segmenter returns
just an empty list '''
... | Add test for empty string; cleanup | Add test for empty string; cleanup
| Python | bsd-2-clause | ambidextrousTx/RNLTK | ''' Tests for BaseUtils
'''
import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
''' Main test class for the BaseUtils '''
def test_word_segmenter_with_empty(self):
''' For an empty string, the segmenter returns
just an empty list '''
... | Add test for empty string; cleanup
import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
def test_word_segmenter(self):
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sen... |
5d448435477ce94273051b8351275d8c18838b8b | icekit/utils/fluent_contents.py | icekit/utils/fluent_contents.py | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, page, ... | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | Change argument name to stop probable name clash. | Change argument name to stop probable name clash.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | Change argument name to stop probable name clash.
from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def c... |
922c6350fda965068927611348bdd9127ee405d9 | scaffolder/commands/vcs.py | scaffolder/commands/vcs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS
class VcsCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"-u",
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS
class VcsCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"-u",
... | Remove __init__ method, not needed. | VcsCommand: Remove __init__ method, not needed.
| Python | mit | goliatone/minions | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS
class VcsCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"-u",
... | VcsCommand: Remove __init__ method, not needed.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS
class VcsCommand(BaseCommand):
option_list = BaseCommand.option_list +... |
79358f9eb3b12b45d3e1ebe8840aed9e9d8a7274 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-oscar-fancypages',
version=":versiontools:fancypages:",
url='https://github.com/tangentlabs/django-oscar-fancypages',
author="Sebastian Vetter",
author_email="sebastian.vetter@tangentsnowball.com.au",
descript... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-oscar-fancypages',
version=":versiontools:fancypages:",
url='https://github.com/tangentlabs/django-oscar-fancypages',
author="Sebastian Vetter",
author_email="sebastian.vetter@tangentsnowball.com.au",
descript... | Update django to use latest security release | Update django to use latest security release
| Python | bsd-3-clause | tangentlabs/django-oscar-fancypages,tangentlabs/django-oscar-fancypages | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-oscar-fancypages',
version=":versiontools:fancypages:",
url='https://github.com/tangentlabs/django-oscar-fancypages',
author="Sebastian Vetter",
author_email="sebastian.vetter@tangentsnowball.com.au",
descript... | Update django to use latest security release
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-oscar-fancypages',
version=":versiontools:fancypages:",
url='https://github.com/tangentlabs/django-oscar-fancypages',
author="Sebastian Vetter",
author_email="sebastia... |
d425fa64ece6826d299ca2daadb9a08afa6e87b5 | test/test_searchentities.py | test/test_searchentities.py | import unittest
from . import models
from sir.schema.searchentities import SearchEntity as E, SearchField as F
class QueryResultToDictTest(unittest.TestCase):
def setUp(self):
self.entity = E(models.B, [
F("id", "id"),
F("c_bar", "c.bar"),
F("c_bar_trans", "c.bar", tra... | Add a test for query_result_to_dict | Add a test for query_result_to_dict
| Python | mit | jeffweeksio/sir | import unittest
from . import models
from sir.schema.searchentities import SearchEntity as E, SearchField as F
class QueryResultToDictTest(unittest.TestCase):
def setUp(self):
self.entity = E(models.B, [
F("id", "id"),
F("c_bar", "c.bar"),
F("c_bar_trans", "c.bar", tra... | Add a test for query_result_to_dict
| |
0b1a4a57a9e8f9e7038fb4330cbac68596f5960c | tests/plugins/test_property_mod_tracker.py | tests/plugins/test_property_mod_tracker.py | import sqlalchemy as sa
from sqlalchemy_continuum.plugins import PropertyModTrackerPlugin
from tests import TestCase
class TestPropertyModificationsTracking(TestCase):
plugins = [PropertyModTrackerPlugin]
def create_models(self):
class User(self.Model):
__tablename__ = 'text_item'
... | Add tests for PropertyModTracker plugin | Add tests for PropertyModTracker plugin
| Python | bsd-3-clause | avilaton/sqlalchemy-continuum,piotr-dobrogost/sqlalchemy-continuum,rmoorman/sqlalchemy-continuum,kvesteri/sqlalchemy-continuum | import sqlalchemy as sa
from sqlalchemy_continuum.plugins import PropertyModTrackerPlugin
from tests import TestCase
class TestPropertyModificationsTracking(TestCase):
plugins = [PropertyModTrackerPlugin]
def create_models(self):
class User(self.Model):
__tablename__ = 'text_item'
... | Add tests for PropertyModTracker plugin
| |
1c7c0f081711654095023a984978cd812ac94fb6 | numpy/tests/typing/reveal/modules.py | numpy/tests/typing/reveal/modules.py | import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: Modul... | import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleT... | Remove `compat` and `core` from the tests | TST: Remove `compat` and `core` from the tests
| Python | bsd-3-clause | anntzer/numpy,numpy/numpy,rgommers/numpy,mhvk/numpy,anntzer/numpy,seberg/numpy,numpy/numpy,madphysicist/numpy,madphysicist/numpy,madphysicist/numpy,mattip/numpy,mattip/numpy,endolith/numpy,numpy/numpy,jakirkham/numpy,grlee77/numpy,simongibbons/numpy,grlee77/numpy,charris/numpy,anntzer/numpy,jakirkham/numpy,seberg/numpy... | import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleT... | TST: Remove `compat` and `core` from the tests
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) ... |
d7eb2dc9eb5f391a6a6742bea3692c8ab1d8aa69 | doc/examples/plot_edge_filter.py | doc/examples/plot_edge_filter.py | import matplotlib.pyplot as plt
from skimage.data import camera
from skimage.filter import roberts, sobel
image = camera()
edge_roberts = roberts(image)
edge_sobel = sobel(image)
fig, (ax0, ax1) = plt.subplots(ncols=2)
ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off'... | """
==============
Edge operators
==============
Edge operators are used in image processing within edge detection algorithms.
They are discrete differentiation operators, computing an approximation of the
gradient of the image intensity function.
"""
import matplotlib.pyplot as plt
from skimage.data import camera
f... | Add short description to edge filter example | Add short description to edge filter example
| Python | bsd-3-clause | ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,bsipocz/scikit-image,oew1v07/scikit-image,michaelaye/scikit-image,SamHames/scikit-image,paalge/scikit-image,almarklein/scikit-image,Midafi/scikit-image,chintak/scikit-image,vighneshbirodkar/scikit-image,juliusbierk/scikit-image,rjeli/scikit-image,chintak/scikit-i... | """
==============
Edge operators
==============
Edge operators are used in image processing within edge detection algorithms.
They are discrete differentiation operators, computing an approximation of the
gradient of the image intensity function.
"""
import matplotlib.pyplot as plt
from skimage.data import camera
f... | Add short description to edge filter example
import matplotlib.pyplot as plt
from skimage.data import camera
from skimage.filter import roberts, sobel
image = camera()
edge_roberts = roberts(image)
edge_sobel = sobel(image)
fig, (ax0, ax1) = plt.subplots(ncols=2)
ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_... |
a116c3eae892a73b11372225a9bdf0194db75598 | glanerbeard/web.py | glanerbeard/web.py | import logging
from flask import (
Flask,
render_template,
abort
)
from glanerbeard.server import Server
app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')
numeric_level = getattr(logging, app.config['LOGLEVEL'].upper(), None)
if not isinst... | import logging
from flask import (
Flask,
render_template,
abort
)
from glanerbeard.server import Server
app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')
numeric_level = getattr(logging, app.config['LOGLEVEL'].upper(), None)
if not isinst... | Use a template to render json. | Use a template to render json.
| Python | apache-2.0 | daenney/glanerbeard | import logging
from flask import (
Flask,
render_template,
abort
)
from glanerbeard.server import Server
app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')
numeric_level = getattr(logging, app.config['LOGLEVEL'].upper(), None)
if not isinst... | Use a template to render json.
import logging
from flask import (
Flask,
render_template,
abort
)
from glanerbeard.server import Server
app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')
numeric_level = getattr(logging, app.config['LOGLEVE... |
63ce9ac2a46f74704810d62e22c0b75ca071442a | minesweeper/minesweeper.py | minesweeper/minesweeper.py | import re
class InvalidBoard(ValueError):
pass
def board(b):
if not is_valid_board(b):
raise InvalidBoard("Board is malformed and thus invalid")
b = [[ch for ch in row] for row in b]
for i in range(1, len(b)-1):
for j in range(1, len(b[0])-1):
if b[i][j] == " ":
... | import re
class InvalidBoard(ValueError):
pass
def board(b):
if not is_valid_board(b):
raise InvalidBoard("Board is malformed and thus invalid")
b = [[ch for ch in row] for row in b]
for i in range(1, len(b)-1):
for j in range(1, len(b[0])-1):
if b[i][j] == " ":
... | Add note regarding use of bool in validation | Add note regarding use of bool in validation
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | import re
class InvalidBoard(ValueError):
pass
def board(b):
if not is_valid_board(b):
raise InvalidBoard("Board is malformed and thus invalid")
b = [[ch for ch in row] for row in b]
for i in range(1, len(b)-1):
for j in range(1, len(b[0])-1):
if b[i][j] == " ":
... | Add note regarding use of bool in validation
import re
class InvalidBoard(ValueError):
pass
def board(b):
if not is_valid_board(b):
raise InvalidBoard("Board is malformed and thus invalid")
b = [[ch for ch in row] for row in b]
for i in range(1, len(b)-1):
for j in range(1, len(b[0]... |
282a8d120d486f15cc1e5cd9e1432c1100e722bf | examples/nogallery/create_a_dummy_hdf5_file.py | examples/nogallery/create_a_dummy_hdf5_file.py | import numpy as np
import km3pipe as kp
class APump(kp.Pump):
def configure(self):
self.index = 0
def process(self, blob):
data = {'a': self.index * np.arange(5),
'b': np.arange(5) ** self.index}
data2 = {'c': self.index * np.arange(10, dtype='f4') + 0.1,
... | Add a dummy script which creates an hdf5 file | Add a dummy script which creates an hdf5 file
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | import numpy as np
import km3pipe as kp
class APump(kp.Pump):
def configure(self):
self.index = 0
def process(self, blob):
data = {'a': self.index * np.arange(5),
'b': np.arange(5) ** self.index}
data2 = {'c': self.index * np.arange(10, dtype='f4') + 0.1,
... | Add a dummy script which creates an hdf5 file
| |
16dda42316176f0ad9c747731764855792fe88d6 | lymph/utils/observables.py | lymph/utils/observables.py | # Taken from https://github.com/delivero/lymph-storage/blob/master/lymph/storage/observables.py
class Observable(object):
def __init__(self):
self.observers = {}
def notify_observers(self, action, *args, **kwargs):
for callback in self.observers.get(action, ()):
callback(*args, **kw... |
class Observable(object):
def __init__(self):
self.observers = {}
def notify_observers(self, action, *args, **kwargs):
kwargs.setdefault('action', action)
for callback in self.observers.get(action, ()):
callback(*args, **kwargs)
def observe(self, actions, callback):
... | Allow observing more than one action at once | Allow observing more than one action at once
| Python | apache-2.0 | lyudmildrx/lymph,mouadino/lymph,Drahflow/lymph,itakouna/lymph,vpikulik/lymph,deliveryhero/lymph,kstrempel/lymph,alazaro/lymph,lyudmildrx/lymph,itakouna/lymph,mamachanko/lymph,torte/lymph,mamachanko/lymph,lyudmildrx/lymph,alazaro/lymph,mouadino/lymph,mamachanko/lymph,mouadino/lymph,alazaro/lymph,itakouna/lymph,dushyant8... |
class Observable(object):
def __init__(self):
self.observers = {}
def notify_observers(self, action, *args, **kwargs):
kwargs.setdefault('action', action)
for callback in self.observers.get(action, ()):
callback(*args, **kwargs)
def observe(self, actions, callback):
... | Allow observing more than one action at once
# Taken from https://github.com/delivero/lymph-storage/blob/master/lymph/storage/observables.py
class Observable(object):
def __init__(self):
self.observers = {}
def notify_observers(self, action, *args, **kwargs):
for callback in self.observers.get... |
122f596f3568d1ee1031733344e7eebb057cc032 | setup.py | setup.py | import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
sys.path.insert(0, here)
from titlecase import __version__
setup(name='titlecase',
version=__version__,
description="Python Port of John G... | import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
sys.path.insert(0, here)
from titlecase import __version__
setup(name='titlecase',
version=__version__,
description="Python Port of John G... | Add python3 support for nosetests | Add python3 support for nosetests
| Python | mit | ppannuto/python-titlecase | import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
sys.path.insert(0, here)
from titlecase import __version__
setup(name='titlecase',
version=__version__,
description="Python Port of John G... | Add python3 support for nosetests
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
sys.path.insert(0, here)
from titlecase import __version__
setup(name='titlecase',
version=__version__,
... |
921bdcc5d6f6ac4be7dfd0015e5b5fd6d06e6486 | runcommands/__main__.py | runcommands/__main__.py | import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfig(run=RunConfig()... | import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
debug = None
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfi... | Raise exception when --debug is specified to main script | Raise exception when --debug is specified to main script
I.e., instead of printing the exception and then exiting.
| Python | mit | wylee/runcommands,wylee/runcommands | import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
debug = None
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfi... | Raise exception when --debug is specified to main script
I.e., instead of printing the exception and then exiting.
import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
try:
... |
86fdcd6575a944a378a9c3f5b292fb33a6c42853 | digestive/hash.py | digestive/hash.py | import hashlib
from digestive.io import Sink
class HashDigest(Sink):
def __init__(self, name, digest):
super().__init__(name)
self._digest = digest
def update(self, data):
self._digest.update(data)
def digest(self):
return self._digest.hexdigest()
class MD5(HashDigest)... | import hashlib
from digestive.io import Sink
class HashDigest(Sink):
def __init__(self, name, digest):
super().__init__(name)
self._digest = digest
def update(self, data):
self._digest.update(data)
def digest(self):
return self._digest.hexdigest()
class MD5(HashDigest)... | Make sha256 and sha512 sink names correspond to their commandline arguments | Make sha256 and sha512 sink names correspond to their commandline arguments
| Python | isc | akaIDIOT/Digestive | import hashlib
from digestive.io import Sink
class HashDigest(Sink):
def __init__(self, name, digest):
super().__init__(name)
self._digest = digest
def update(self, data):
self._digest.update(data)
def digest(self):
return self._digest.hexdigest()
class MD5(HashDigest)... | Make sha256 and sha512 sink names correspond to their commandline arguments
import hashlib
from digestive.io import Sink
class HashDigest(Sink):
def __init__(self, name, digest):
super().__init__(name)
self._digest = digest
def update(self, data):
self._digest.update(data)
def ... |
390fc84183c0f680c5fb1a980ee3c1227b187611 | HowLong/HowLong.py | HowLong/HowLong.py | #!/usr/bin/env python3
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
class HowLong(object):
def __init__(self):
parser = argparse.ArgumentParser(description='Ti... | from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
def log(*args):
print(*args, file=sys.stderr)
sys.stderr.flush()
cla... | Print debug info to stderr | MINOR: Print debug info to stderr
| Python | apache-2.0 | mattjegan/HowLong | from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
def log(*args):
print(*args, file=sys.stderr)
sys.stderr.flush()
cla... | MINOR: Print debug info to stderr
#!/usr/bin/env python3
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
class HowLong(object):
def __init__(self):
parser = argp... |
e120858d5cb123e9f3422ddb15ce79bde8d05d64 | statsd/__init__.py | statsd/__init__.py | import socket
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
... | import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localho... | Read settings from environment, if available | Read settings from environment, if available
| Python | mit | lyft/pystatsd,jsocol/pystatsd,deathowl/pystatsd,Khan/pystatsd,Khan/pystatsd,smarkets/pystatsd,wujuguang/pystatsd,lyft/pystatsd | import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localho... | Read settings from environment, if available
import socket
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getat... |
3093941ebed1f9c726a88776819ee181cdb0b869 | piper/db/core.py | piper/db/core.py | import logbook
# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
"""
Abstract class representing a persistance layer
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def init(self, ns, config):
raise NotImplementedError()
... | import logbook
class LazyDatabaseMixin(object):
"""
A mixin class that gives the subclass lazy access to the database layer
The lazy attribute self.db is added, and the database class is gotten from
self.config, and an instance is made and returned.
"""
_db = None
@property
def db(... | Add first iteration of LazyDatabaseMixin() | Add first iteration of LazyDatabaseMixin()
| Python | mit | thiderman/piper | import logbook
class LazyDatabaseMixin(object):
"""
A mixin class that gives the subclass lazy access to the database layer
The lazy attribute self.db is added, and the database class is gotten from
self.config, and an instance is made and returned.
"""
_db = None
@property
def db(... | Add first iteration of LazyDatabaseMixin()
import logbook
# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
"""
Abstract class representing a persistance layer
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def init(self, ns, con... |
2d5c5a1bf693f428b53f8d4a6e788f7be864aa9e | image_site_app/forms.py | image_site_app/forms.py | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30, label='First name (optional)', required=False)
last_name = forms.CharField(max_length=30, label='Last name (optional)'... | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30,
label='First name (optional)',
required=False,
... | Add placeholder to first_name and last_name fields in signup form | Add placeholder to first_name and last_name fields in signup form
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30,
label='First name (optional)',
required=False,
... | Add placeholder to first_name and last_name fields in signup form
from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30, label='First name (optional)', required=False)
last... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.