input stringlengths 0 2.17k | instruction stringlengths 18 2.94k | output stringlengths 47 3.36k |
|---|---|---|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | Fix comment header on init
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.ch>
#
# The licence is in the f... |
from species import CODES
def all_region_codes():
return CODES.keys
def all_species_codes():
return species_codes_for_regions(all_region_codes)
def species_codes_for_regions(region_codes):
if region_codes is None:
return None
species_codes = []
for region_code in region_codes:
... | Fix typo that prevented instance creation
| from species import CODES
def all_region_codes():
return CODES.keys
def all_species_codes():
return species_codes_for_regions(all_region_codes())
def species_codes_for_regions(region_codes):
if region_codes is None:
return None
species_codes = []
for region_code in region_codes:
... |
from functools import lru_cache
import boto3
from pydantic import BaseSettings, Field, root_validator
@lru_cache
def get_secrets_client():
return boto3.client("secretsmanager")
@lru_cache
def get_secret(secret_id):
client = get_secrets_client()
secret_value = client.get_secret_value(SecretId=secret_id)... | Set default logging to info
| from functools import lru_cache
import boto3
from pydantic import BaseSettings, Field, root_validator
@lru_cache
def get_secrets_client():
return boto3.client("secretsmanager")
@lru_cache
def get_secret(secret_id):
client = get_secrets_client()
secret_value = client.get_secret_value(SecretId=secret_id)... |
import sys
sys.path.insert(1, "../../../")
import h2o
def bigcatRF(ip,port):
# Connect to h2o
h2o.init(ip,port)
# Training set has 100 categories from cat001 to cat100
# Categories cat001, cat003, ... are perfect predictors of y = 1
# Categories cat002, cat004, ... are perfect predictors of y = 0
... | Add usage of nbins_cats to RF pyunit.
| import sys
sys.path.insert(1, "../../../")
import h2o
def bigcatRF(ip,port):
# Connect to h2o
h2o.init(ip,port)
# Training set has 100 categories from cat001 to cat100
# Categories cat001, cat003, ... are perfect predictors of y = 1
# Categories cat002, cat004, ... are perfect predictors of y = 0
... |
"""Test GitHub issue #4.
Diagram could not be loaded due to JuggleError (presumed cyclic
resolving of diagram items).
"""
from gi.repository import GLib, Gtk
from gaphor.storage.storage import load
class TestCyclicDiagram:
def test_bug(self, case, test_models):
"""Load file.
Thi... | Convert load_model tests to pytest functions
| # flake8: noqa F401,F811
"""Diagram could not be loaded due to JuggleError (presumed cyclic resolving of
diagram items)."""
from gi.repository import GLib, Gtk
from gaphor.diagram.tests.fixtures import (
element_factory,
event_manager,
modeling_language,
)
from gaphor.storage.storage import loa... |
from __future__ import print_function
import json
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import GithubAPIClient
parser = ArghParser(description="Browse the GitHub API")
@arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")')
@arg('url', help='URL to browse')... | Add missed json to json() tweak
| from __future__ import print_function
import json
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import GithubAPIClient
parser = ArghParser(description="Browse the GitHub API")
@arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")')
@arg('url', help='URL to browse')... |
import sys
def lowest_unique(int_list):
numbers = {}
for index in range(len(int_list)):
group = numbers.setdefault(int(int_list[index]), [])
group.append(index)
for number in numbers:
retval = numbers[number]
if len(retval) == 1:
return retval[0] + 1
return ... | Improve solution by using enumerate
| import sys
def lowest_unique(int_list):
numbers = {}
for index, number in enumerate(int_list):
group = numbers.setdefault(int(number), [])
group.append(index)
for number in sorted(numbers.keys()):
retval = numbers[number]
if len(retval) == 1:
return retval[0] + ... |
from distutils.core import setup
setup(
name='python3-indy',
version='1.6.1',
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Vyacheslav Gudkov',
author_email='vyacheslav.gudkov@dsr-company.com',
description='This is the official SDK f... | Fix pytest version in python wrapper deps.
Signed-off-by: Sergey Minaev <322af3f2df10918c6ef5280f56be0b711278b1ae@dsr-company.com>
| from distutils.core import setup
setup(
name='python3-indy',
version='1.6.1',
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Vyacheslav Gudkov',
author_email='vyacheslav.gudkov@dsr-company.com',
description='This is the official SDK f... |
import RDF
import zope.interface
import interfaces
import rdf_helper
class Jurisdiction(object):
zope.interface.implements(interfaces.IJurisdiction)
def __init__(self, short_name):
'''@param short_name can be e.g. mx'''
model = rdf_helper.init_model(
rdf_helper.JURI_RDF_PATH)
... | Add documentation and make Jurisdiction calls not fail when some of the values aren't found.
| import RDF
import zope.interface
import interfaces
import rdf_helper
class Jurisdiction(object):
zope.interface.implements(interfaces.IJurisdiction)
def __init__(self, short_name):
"""Creates an object representing a jurisdiction.
short_name is a (usually) two-letter code representing
... |
#
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from mint import amiperms
class AWSHandler(object):
def __init__(self, cfg, db):
self.db = db
self.amiPerms = amiperms.AMIPermissionsManager(cfg, db)
def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None):
... | Fix typo when setting up handler.
| #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from mint import amiperms
class AWSHandler(object):
def __init__(self, cfg, db):
self.db = db
self.amiPerms = amiperms.AMIPermissionsManager(cfg, db)
def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None):
... |
import sys
import time
import bracoujl.processor.gb_z80 as proc
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines):
res = ''
for line in lines:
op = proc.CPU_CONF['parse_line'](line)
if op is None:
continue
res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassembl... | Fix and enhance disassemble miscellaneous script.
| import argparse
import sys
import time
import bracoujl.processor.gb_z80 as proc
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines, keep_logs=False):
res = []
for line in lines:
op, gline = proc.CPU_CONF['parse_line'](line), ''
if keep_logs:
gline += line + (' | DIS: ' if ... |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('interfaces', parent_package, top_path)
config.add_data_dir('tests')
config.add_data_dir('script_templates')
return config
if __name__ == '__main__':
from numpy.dist... | Add fsl subpackage on install.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1050 ead46cd0-7350-4e37-8683-fc4c6f79bf00
| def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('interfaces', parent_package, top_path)
config.add_subpackage('fsl')
config.add_data_dir('tests')
config.add_data_dir('script_templates')
return config
if __name__ ... |
#!/usr/bin/python
from pytun import TunTapDevice
from binascii import hexlify
if __name__ == '__main__':
tun = TunTapDevice(name='ipsec-tun')
tun.up()
tun.persist(True)
while True:
try:
buf = tun.read(tun.mtu)
print hexlify(buf[4:])
IPpayload = buf[4:]
# TODO encrypt buf
# TODO send to wlan0
... | Change shebang to use python from environment. Fix Indentation.
| #!/usr/bin/env python
from pytun import TunTapDevice
from binascii import hexlify
if __name__ == '__main__':
tun = TunTapDevice(name='ipsec-tun')
tun.up()
tun.persist(True)
while True:
try:
buf = tun.read(tun.mtu)
print hexlify(buf[4:])
IPpayload = buf[4:]
... |
import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if frappe.db.exists("DocType", "Desk Page"):
if frappe.db.exists('DocType', 'Workspace'):
# this patch was not added initially, so this page might still exist
frappe.delete_doc('DocType', 'Desk Page')
else:
rename_doc('DocType', ... | fix(Patch): Rename Desk Link only if it exists
| import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if frappe.db.exists("DocType", "Desk Page"):
if frappe.db.exists('DocType', 'Workspace'):
# this patch was not added initially, so this page might still exist
frappe.delete_doc('DocType', 'Desk Page')
else:
rename_doc('DocType', ... |
#!/usr/bin/env python
from gevent.wsgi import WSGIServer
import werkzeug.serving
from werkzeug.debug import DebuggedApplication
from app import get_app
APP_PORT = 5000
DEBUG = True
@werkzeug.serving.run_with_reloader
def main():
"""Starts web application
"""
app = get_app()
app.debug = DEBUG
# ap... | Apply gevent monkey patching, so it will get invoked when main
is called via the entry point script and not via shell script
| #!/usr/bin/env python
import gevent.monkey
gevent.monkey.patch_all()
from gevent.wsgi import WSGIServer
import werkzeug.serving
from werkzeug.debug import DebuggedApplication
from app import get_app
APP_PORT = 5000
DEBUG = True
@werkzeug.serving.run_with_reloader
def main():
"""Starts web application
"""
... |
"""Utiltiy functions for workign on the NinaPro Databases (1 & 2)."""
from setuptools import setup, find_packages
setup(name='nina_helper',
version='2.1',
description='Utiltiy functions for workign on the NinaPro Databases (1 & 2)',
author='Lif3line',
author_email='adamhartwell2@gmail.com',
... | Use local upload for release
| """Utiltiy functions for workign on the NinaPro Databases (1 & 2)."""
from setuptools import setup, find_packages
setup(name='nina_helper',
version='2.2',
description='Utiltiy functions for workign on the NinaPro Databases (1 & 2)',
author='Lif3line',
author_email='adamhartwell2@gmail.com',
... |
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testprojec... | Add test for externally-generated request IDs
| import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testprojec... |
import eventlet
import os
import sys
from oslo.config import cfg
from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history
LOG = logging.getLogger(__name__)
eventlet.monkey_patch(
os=Tr... | Move code from _run_worker into main
| import eventlet
import os
import sys
from oslo.config import cfg
from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history
LOG = logging.getLogger(__name__)
eventlet.monkey_patch(
os=Tr... |
from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date):
"""
Gets all cases with a specified owner ID that... | Make get_case_ids_modified_with_owner_since accept an end date as well
| from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specif... |
Allow django-money to be specified as read-only in a model
Monkey patch the Django admin so that we can display django-money fields
read-only. In order to do this, we simply catch the exception that
results from trying to convert a money object (e.g. '10 USD') into a
floating field.
And then we call just ask for the ... | from django.db import models
from django.utils.encoding import smart_unicode
from django.utils import formats
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.admin.util import lookup_field
from django.utils.safestring import mark_safe
from django.utils.html i... | |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \
DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView
urlpatterns = [
url(r'^$',... | Remove obsolete import (removed in Django 1.10)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \
DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView
urlpatterns = [
url(r'^$', HomePageV... |
import pytest
from pyhocon.config_tree import ConfigTree
from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException
class TestConfigParser(object):
def test_config_tree_quoted_string(self):
config_tree = ConfigTree()
config_tree.put("a.b.c", "value")
assert config_tre... | Add failing tests for iteration and logging config
| import pytest
from pyhocon.config_tree import ConfigTree
from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException
class TestConfigParser(object):
def test_config_tree_quoted_string(self):
config_tree = ConfigTree()
config_tree.put("a.b.c", "value")
assert config_tre... |
"""Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1"
| Make OrderedChoices available at the package root
| """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1"... |
from functools import wraps
from django.db import connection
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
return wr... | Fix circular import when used with other add-ons that import django.db
eg sorl_thumbnail:
Traceback (most recent call last):
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module>
sys.exit(manage.main())
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/mana... | from functools import wraps
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
from django.db import connection
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
retur... |
#!/usr/bin/env python
from twisted.web.server import Site
from webtest.session import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
logger = log.get_logger()
class RedisSite(Site):
sessionFactory = RedisSessionFactory
requestFactory = RedisRequest
def makeSession(s... | Move RedisSessionFactory into its own module
| #!/usr/bin/env python
from twisted.web.server import Site
from webtest.session_factory import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
logger = log.get_logger()
class RedisSite(Site):
sessionFactory = RedisSessionFactory
requestFactory = RedisRequest
def makeS... |
class LocalNodeMiddleware(object):
"""
Ensures a Node that represents the local server always exists.
No other suitable hook for code that's run once and can access the server's host name
was found. A migration was not suitable for the second reason.
"""
def __init__(self):
self.local_n... | Add TODO to fix bug at later date
| class LocalNodeMiddleware(object):
"""
Ensures a Node that represents the local server always exists.
No other suitable hook for code that's run once and can access the server's host name
was found. A migration was not suitable for the second reason.
"""
def __init__(self):
self.local_n... |
from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
| Use port 80 to serve the API
| from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
|
from rest_framework import serializers
from registries.models import Organization
from gwells.models import ProvinceState
class DrillerListSerializer(serializers.ModelSerializer):
province_state = serializers.ReadOnlyField()
class Meta:
model = Organization
# Using all fields for now
... | Add fields to driller list serializer
| from rest_framework import serializers
from registries.models import Organization
from gwells.models import ProvinceState
class DrillerListSerializer(serializers.ModelSerializer):
"""
Serializer for Driller model "list" view.
"""
province_state = serializers.ReadOnlyField(source="province_state.code"... |
from django.conf import settings
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
}
}
| Make settings.DEBUG available to templates
It's used in the default base.html template so makes sense for it to actually appear in the context.
| from django.conf import settings
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
'DEBUG': settings.DEBUG,
}
}
|
#!/usr/bin/python
import os
import sys
import api
import json
import getpass
# Banks
banks = {}
import bankofamerica
banks["bankofamerica"] = bankofamerica
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpass()
if not api.callapi("login",{"username": username, "passwor... | Read bank list from config file.
| #!/usr/bin/python
import os
import sys
import api
import json
import getpass
sys.path.append("../")
import config
# Banks
banks = {}
for bank in config.banks:
exec "import %s" % (bank)
banks[bank] = eval(bank)
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpa... |
# Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | Fix the handling of missing prefixes
Twisted defaults to an empty string, while IRCBase defaults to None.
| # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... |
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
... | Add a ProjectDetailSerializer and EntryDetailSerializer
| # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class... |
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_plugin = False
jump_url = None
handshake_url = None
... |
import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
ppelm_json = []
if fname is None:
# ToDo Get from S3
pass
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
columns = next(csv_reader... | Move iterator to own function
| import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
if fname is None:
# ToDo Get from S3
return []
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
ppelm_json = _get_json_from_entry_rows(c... |
class Neuron:
pass
class NeuronNetwork:
neurons = []
| Create 2D list of Neurons in NeuronNetwork's init
| class Neuron:
pass
class NeuronNetwork:
neurons = []
def __init__(self, rows, columns):
self.neurons = []
for row in xrange(rows):
self.neurons.append([])
for column in xrange(columns):
self.neurons[row].append(Neuron())
|
from distutils.core import setup
from setuptools import find_packages
setup(name='geventconnpool',
version = "0.1",
description = 'TCP connection pool for gevent',
url="https://github.com/rasky/geventconnpool",
author="Giovanni Bajo",
author_email="rasky@develer.com",
packages=find_packages('sr... | Add long description to the package.
| from distutils.core import setup
from setuptools import find_packages
with open('README.rst') as file:
long_description = file.read()
setup(name='geventconnpool',
version = "0.1a",
description = 'TCP connection pool for gevent',
long_description = long_description,
url="https://github.com/rasky/ge... |
"""
Py-Tree-sitter
"""
import platform
from setuptools import setup, Extension
setup(
name = "tree_sitter",
version = "0.0.8",
maintainer = "Max Brunsfeld",
maintainer_email = "maxbrunsfeld@gmail.com",
author = "Max Brunsfeld",
author_email = "maxbrunsfeld@gmail.com",
url = "https://gith... | Remove an incorrect documentation URL
Fixes #9.
| """
Py-Tree-sitter
"""
import platform
from setuptools import setup, Extension
setup(
name = "tree_sitter",
version = "0.0.8",
maintainer = "Max Brunsfeld",
maintainer_email = "maxbrunsfeld@gmail.com",
author = "Max Brunsfeld",
author_email = "maxbrunsfeld@gmail.com",
url = "https://gith... |
from setuptools import setup, find_packages
setup(
name='bfg9000',
version='0.1.0pre',
license='BSD',
author='Jim Porter',
author_email='porterj@alum.rit.edu',
packages=find_packages(exclude=['test']),
entry_points={
'console_scripts': ['bfg9000=bfg9000.driver:main'],
},
... | Fix version number to comply with PEP 440
| from setuptools import setup, find_packages
setup(
name='bfg9000',
version='0.1.0-dev',
license='BSD',
author='Jim Porter',
author_email='porterj@alum.rit.edu',
packages=find_packages(exclude=['test']),
entry_points={
'console_scripts': ['bfg9000=bfg9000.driver:main'],
},
... |
from setuptools import find_packages, setup
setup(
name='txkazoo',
version='0.0.4',
description='Twisted binding for Kazoo',
maintainer='Manish Tomar',
maintainer_email='manish.tomar@rackspace.com',
license='Apache 2.0',
packages=find_packages(),
install_requires=['twisted==13.2.0', 'ka... | Add long_description from README + URL
| from setuptools import find_packages, setup
setup(
name='txkazoo',
version='0.0.4',
description='Twisted binding for Kazoo',
long_description=open("README.md").read(),
url="https://github.com/rackerlabs/txkazoo",
maintainer='Manish Tomar',
maintainer_email='manish.tomar@rackspace.com',
... |
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Fix missing raven.processors in build
| import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... |
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errco... | Add entry point for quick_add_keys_to_file
| from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytes... |
#!/usr/bin/env python
import os
from setuptools import find_packages, setup
SCRIPT_DIR = os.path.dirname(__file__)
if not SCRIPT_DIR:
SCRIPT_DIR = os.getcwd()
SRC_PREFIX = 'src'
packages = find_packages(SRC_PREFIX)
setup(
name='cmdline',
version='0.0.0',
description='Utilities for consistent... | Add markdown content type for README
| #!/usr/bin/env python
import os
from setuptools import find_packages, setup
SCRIPT_DIR = os.path.dirname(__file__)
if not SCRIPT_DIR:
SCRIPT_DIR = os.getcwd()
SRC_PREFIX = 'src'
def readme():
with open('README.md') as f:
return f.read()
packages = find_packages(SRC_PREFIX)
setup(
name='cmd... |
import json
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_templa... | Return Status 422 on bad JSON content
| import json
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_templa... |
"""
WSGI config for classicalguitar project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "classicalguitar.settings")
fr... | Correct some remaining classical guitar refs
| """
WSGI config for website project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")
from django.core.w... |
"""
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
__all__ = ['load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round trip YAML ... | Add YAML load for single document.
| """
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
__all__ = ['load', 'load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round tr... |
#!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
... | Add initialization before get url
| #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report im... |
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| Add function for linear interpolation (lerp)
| def lerp(a, b, t):
return (1.0 - t) * a + t * b
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
|
# -*- coding: utf-8 -*-
import sys
import os
from glob import glob
# -------------------------------------------------------------------------
# Configure extensions
extensions = [
'sphinx.ext.autodoc',
]
# -------------------------------------------------------------------------
# General configuration
projec... | Add retrieval of docs version from VERSION.txt
| # -*- coding: utf-8 -*-
import sys
import os
from glob import glob
# -------------------------------------------------------------------------
# Configure extensions
extensions = [
'sphinx.ext.autodoc',
]
# -------------------------------------------------------------------------
# Helper function for retrievin... |
from fabric.api import env
env.client = 'zsoobhan'
env.project_code = 'prometheus'
env.web_dir = 'www'
# Environment-agnostic folders
env.project_dir = '/var/www/%(client)s/%(project_code)s' % env
env.static_dir = '/mnt/static/%(client)s/%(project_code)s' % env
env.builds_dir = '%(project_dir)s/builds' % env
def _... | Switch to new ec2 instance
| from fabric.api import env
env.client = 'zsoobhan'
env.project_code = 'prometheus'
env.web_dir = 'www'
# Environment-agnostic folders
env.project_dir = '/var/www/%(client)s/%(project_code)s' % env
env.static_dir = '/mnt/static/%(client)s/%(project_code)s' % env
env.builds_dir = '%(project_dir)s/builds' % env
def _... |
from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
f... | Convert tabs to spaces per PEP 8.
| from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
for i in ... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file _... | Fix bug in write project.
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file _... |
import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp... | Set the publication with a parameter. | import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp... |
from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint... | Add API endpoint for logging in
| from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint... |
from functools import wraps
import os
from functools import wraps
def restoring_chdir(fn):
@wraps(fn)
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
... | Kill _changed from the Base so subclassing makes more sense. | from functools import wraps
import os
from functools import wraps
def restoring_chdir(fn):
@wraps(fn)
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
... |
from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
def source_counts():
return bucket_to_dataframe(
'total_source_counts',
basic_search.execute().aggregations.sourceAgg.buckets
)
| Make total_source_counts always be a full query
| from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
def source_counts():
return bucket_to_dataframe(
'total_source_counts',
ShareSearch().execute().aggregations.sourceAgg.buckets
)
|
from collections import Counter
class APMTracker(object):
def handleInitGame(self, event, replay):
for player in replay.players:
player.apm = Counter()
player.aps = Counter()
player.seconds_played = replay.length.seconds
def handlePlayerActionEvent(self, event, rep... | Fix the engine's APM plugin and add some documentation.
| from collections import Counter
class APMTracker(object):
"""
Builds ``player.aps`` and ``player.apm`` dictionaries where an action is
any Selection, Hotkey, or Ability event.
Also provides ``player.avg_apm`` which is defined as the sum of all the
above actions divided by the number of seconds pla... |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | Fix an incorrect policy rule in Admin > Instances
Change-Id: I765ae0c36d19c88138fbea9545a2ca4791377ffb
Closes-Bug: #1703066
| # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-02-28 16:47
from __future__ import unicode_literals
from django.db import migrations, models
def instance_types_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.ob... | Fix migration. Custom triggers are not run in data migrations.
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-02-28 16:47
from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration"... |
import re
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
def test_constituencies_page(self):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'... | Make test_constituencies_page work without PopIt
| import re
from mock import patch
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
@patch('candidates.popit.PopIt')
def test_constituencies_page(self, mock_popit):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
... | Revert pubsub roll on FYI
BUG=
TBR=estaab
Review URL: https://codereview.chromium.org/1688503002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298680 0039d316-1c4b-4281-b951-d872f2087c98
| # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
... |
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
| Add __unicode__ to Dependency model
| from __future__ import unicode_literals
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
def __unicode__(s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)) + '/src')
import DataVisualizing
if len(sys.argv) != 2:
print 'usage: create_heatmap.py <data file>'
print ' expected infile is a datafile containing tracking data'
print ' this is a... | Add raw line data to output
| #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)) + '/src')
import DataVisualizing
if len(sys.argv) != 2:
print 'usage: create_heatmap.py <data file>'
print ' expected infile is a datafile containing tracking data'
print ' this is a... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tests.db',
},
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
... | Remove tz context processor (not available in 1.3)
| DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tests.db',
},
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
... |
Add a small test for renderer
| import mfr
import json
from tests import utils
from tornado import testing
class TestRenderHandler(utils.HandlerTestCase):
@testing.gen_test
def test_options_skips_prepare(self):
# Would crash b/c lack of mocks
yield self.http_client.fetch(
self.get_url('/render'),
met... | |
#!/usr/bin/env python
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
ro... | Add setGrid and resetGrid functions
| #!/usr/bin/env python
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
ro... |
# from jaraco.util.itertools
def always_iterable(item):
"""
Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item.
>>> always_iterable([1,2,3])
[1, 2, 3]
>>> always_iterable('foo')
('foo',)
>>> always_iterable(None)
... | Use float so test passes on Python 2.6
| # from jaraco.util.itertools
def always_iterable(item):
"""
Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item.
>>> always_iterable([1,2,3])
[1, 2, 3]
>>> always_iterable('foo')
('foo',)
>>> always_iterable(None)
... |
import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"... | Fix the location path of OpenIPSL
| import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"... |
Add sane log output formatter
| ###############################################################################
#
# Copyright (c) 2012 Ruslan Spivak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, inc... | |
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTru... | Add test to check that person has been given office
| import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTru... |
from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
def run():
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_action_callback(screen.after_loop)
main_run_loop.run()
| Allow run argument to avoid @every template
| from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_a... |
import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
BBC_id= "bbc-news"
@app.route("/")
def index():
r = requests.get(
f"https://newsapi.org/v1/articles?source={BBC_id}&sortBy=top&apiKey={app.config['API_KEY']... | Create dynamic routing for supported sources.
| import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https:... |
# -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... | Update a version number from trunk r9016
| # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search... | Add additional logging for users'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search... |
from django.conf.urls import url, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'categories', views.CategoryViewSet)
router.register(r'commodities', views.CommodityViewSet)
router.register(r'economies', views.EconomyViewSet)
router.register(r'facti... | Fix for the api at root url.
| from django.conf.urls import url, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'categories', views.CategoryViewSet)
router.register(r'commodities', views.CommodityViewSet)
router.register(r'economies', views.EconomyViewSet)
router.register(r'facti... |
#!/usr/bin/env python3
# coding=utf-8
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
... | Clarify where packager.json validation error originates
| #!/usr/bin/env python3
# coding=utf-8
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
... |
def YilmIndexVector(i, l, m):
"""
Compute the index of an 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of an 1D array of spherical harmonic coefficients correspo... | Add error checks to YilmIndexVector (and update docs)
| def YilmIndexVector(i, l, m):
"""
Compute the index of a 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of a 1D array of spherical harmonic coefficients correspond... |
"""
Harvester of pubmed for the SHARE notification service
"""
from __future__ import unicode_literals
from scrapi.base import schemas
from scrapi.base import helpers
from scrapi.base import OAIHarvester
def oai_extract_url_pubmed(identifiers):
identifiers = [identifiers] if not isinstance(identifiers, list) e... | Add API call to top docstring
| """
Harvester of PubMed Central for the SHARE notification service
Example API call: http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=ListRecords&metadataPrefix=oai_dc&from=2015-04-13&until=2015-04-14
"""
from __future__ import unicode_literals
from scrapi.base import schemas
from scrapi.base import helpers
from s... |
from .KEYNOTFOUND import KEYNOTFOUNDIN1
from .dict_diff import dict_diff
def get_old_dict_values(old, new):
# Returns the "old" value for two dicts.
diff = dict_diff(old, new)
return {key: diff[key][0] if diff[key][0] != KEYNOTFOUNDIN1 else None for key in diff}
| Expand an object comprehension onto several lines
| from .KEYNOTFOUND import KEYNOTFOUNDIN1
from .dict_diff import dict_diff
def get_old_dict_values(old, new):
# Returns the "old" value for two dicts.
diff = dict_diff(old, new)
return {key: diff[key][0]
if diff[key][0] != KEYNOTFOUNDIN1
else None
for key in diff}
|
import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher
"""
def __ini... | Create example usage. Rename bypass_level
| import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher,
unless given ... |
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 18.6.0
from . import AWSObject
from troposphere import Tags
class Assignment(AWSObject):
resource_type = "AW... | Update SSO per 2020-12-18 changes
| # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 25.0.0
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class Assignment(AWSObject... |
# third party
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=T... | ADD vpn_endpoint and vpn_key columns
| # third party
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=T... |
from setuptools import setup, find_packages
setup(
name='acc_provision',
version='1.9.6',
description='Tool to provision ACI for ACI Containers Controller',
author="Cisco Systems, Inc.",
author_email="apicapi@noironetworks.com",
url='http://github.com/noironetworks/aci-containers/',
license... | Update acc-provision version to 1.9.7
| from setuptools import setup, find_packages
setup(
name='acc_provision',
version='1.9.7',
description='Tool to provision ACI for ACI Containers Controller',
author="Cisco Systems, Inc.",
author_email="apicapi@noironetworks.com",
url='http://github.com/noironetworks/aci-containers/',
license... |
from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str | Change titles for the site
| from django.contrib import admin
from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str
admin.site.site_header = 'SENK... |
import sublime, sublime_plugin, webbrowser
QD_URL = "http://localhost:5000/"
class GoToQuantifiedDevDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit):
SETTINGS = {}
SETTINGS_FILE = "QuantifiedDev.sublime-settings"
SETTINGS = sublime.load_settings(SETTINGS_FILE)
strea... | Fix url to be consistent. | import sublime, sublime_plugin, webbrowser
QD_URL = "http://localhost:5000"
class GoToQuantifiedDevDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit):
SETTINGS = {}
SETTINGS_FILE = "QuantifiedDev.sublime-settings"
SETTINGS = sublime.load_settings(SETTINGS_FILE)
stream... |
from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
| Throw exception for not existing XSLT_FILES_DIR setting
| from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
|
from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
]
| Add /v2/logs/log_id/added_contributors/ to list of URL's.
| from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
url(r'^(?P<log_id>\w+)/added_contribut... |
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
description = 'The official Python3 Domo API SDK - Domo, Inc.'
long_description = 'See https://github.com/domoinc/domo-python-sdk for more details.'
setup(
name='pydomo',
version='0.3.0.01',
descrip... | Update to prep for v0.3.0.2
| from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
description = 'The official Python3 Domo API SDK - Domo, Inc.'
long_description = 'See https://github.com/domoinc/domo-python-sdk for more details.'
setup(
name='pydomo',
version='0.3.0.2',
descript... |
#!/usr/bin/env python
from flask import Flask, abort, make_response
from socket import inet_aton, error as socket_error
from .db import Database
app = Flask(__name__)
db = Database()
@app.route('/ip/<ip>')
def lookup(ip):
try:
k = inet_aton(ip)
except socket_error:
abort(400)
info_as_j... | Use WHIP_SETTINGS environment var for Flask app
| #!/usr/bin/env python
from flask import Flask, abort, make_response
from socket import inet_aton, error as socket_error
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS')
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
try:
k = inet_a... |
from setuptools import setup
setup(
name='syslog2IRC',
version='0.8',
description='A proxy to forward syslog messages to IRC',
url='http://homework.nwsnet.de/releases/c474/#syslog2irc',
author='Jochen Kupperschmidt',
author_email='homework@nwsnet.de',
license='MIT',
classifiers=[
... | Include README content as long description.
| # -*- coding: utf-8 -*-
import codecs
from setuptools import setup
with codecs.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name='syslog2IRC',
version='0.8',
description='A proxy to forward syslog messages to IRC',
long_description=long_description,
url='ht... |
#!/usr/bin/env python
from setuptools import setup
execfile('kronos/version.py')
setup(
name = 'django-kronos',
version = __version__,
description = 'Kronos is a Django application that makes it easy to define and schedule tasks with cron.',
long_description = open('README.rst').read(),
author = ... | Add history to long description
| #!/usr/bin/env python
from setuptools import setup
execfile('kronos/version.py')
readme = open('README.rst').read()
history = open('HISTORY.rst').read()
setup(
name = 'django-kronos',
version = __version__,
description = 'Kronos is a Django application that makes it easy to define and schedule tasks wit... |
__author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'libpebble2==0.0.14',
'httplib2==0.9.1',
'oauth2client==1.4.12',
'progressbar2==2.7.3',
'pyasn1==0.1.8',
'pyasn1-modules==0.0.6',
'pypng==0.0.17',
'pyqrcode==1.1',
'requests==2.7.0',
'r... | Make sure our python alias is included in packaged versions.
| __author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'libpebble2==0.0.14',
'httplib2==0.9.1',
'oauth2client==1.4.12',
'progressbar2==2.7.3',
'pyasn1==0.1.8',
'pyasn1-modules==0.0.6',
'pypng==0.0.17',
'pyqrcode==1.1',
'requests==2.7.0',
'r... |
# Python imports
from setuptools import setup
# Project imports
from notable import app
# Attributes
AUTHOR = 'John McFarlane'
DESCRIPTION = 'A very simple note taking application'
EMAIL = 'john.mcfarlane@rockfloat.com'
NAME = 'Notable'
PYPI = 'http://pypi.python.org/packages/source/N/Notable'
URL = 'https://github.c... | Set nose.collector as the test_suite
| # Python imports
from setuptools import setup
# Project imports
from notable import app
# Attributes
AUTHOR = 'John McFarlane'
DESCRIPTION = 'A very simple note taking application'
EMAIL = 'john.mcfarlane@rockfloat.com'
NAME = 'Notable'
PYPI = 'http://pypi.python.org/packages/source/N/Notable'
URL = 'https://github.c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
def version():
"""Return version string."""
with open('autopep8.py') as input_file:
for line in input_file:
if line.startswith('__version__'):
import ast
return ast.literal_eval(line... | Make pep8 dependency more explicit
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
def version():
"""Return version string."""
with open('autopep8.py') as input_file:
for line in input_file:
if line.startswith('__version__'):
import ast
return ast.literal_eval(line... |
from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import... | [Chaco] Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
| from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_... |
#
# Copyright (c) 2011 rPath, Inc.
#
# All Rights Reserved
#
BAD_REQUEST = 400
NOT_FOUND = 404
INTERNAL_SERVER_ERROR = 500
class RbuilderError(Exception):
"An unknown error has occured."
status = INTERNAL_SERVER_ERROR
def __init__(self, **kwargs):
cls = self.__class__
self.msg = cls.__d... | Fix typo in exception name
| #
# Copyright (c) 2011 rPath, Inc.
#
# All Rights Reserved
#
BAD_REQUEST = 400
NOT_FOUND = 404
INTERNAL_SERVER_ERROR = 500
class RbuilderError(Exception):
"An unknown error has occured."
status = INTERNAL_SERVER_ERROR
def __init__(self, **kwargs):
cls = self.__class__
self.msg = cls.__d... |
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps
from feincms.models import Page
def add_page_to_extra_context(view_func):
def inner(request, *args, **kwargs):
kwargs.setdefault('extra_context', {})
kwargs['extra_context']['feincms_page'] = Pa... | Fix page import path in view decorator module
| try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps
from feincms.module.page.models import Page
def add_page_to_extra_context(view_func):
def inner(request, *args, **kwargs):
kwargs.setdefault('extra_context', {})
kwargs['extra_context']['feincms... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def make_set():
pass
def link():
pass
def find():
pass
def union():
pass
def kruskal():
"""Kruskal's algorithm for minimum spanning tree
in weighted graph.
Time complexity for graph G(V, E)... | Revise doc string by adding "undirected"
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def make_set():
pass
def link():
pass
def find():
pass
def union():
pass
def kruskal():
"""Kruskal's algorithm for minimum spanning tree
in weighted undirected graph.
Time complexity for gr... |
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
random.seed(None)
def test_select(self):
s = RandomSelector()
r = s.select([1, 2... | Add more tests for pool
| import asyncio
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool
from aioes.transport import Endpoint
from aioes.connection import Connection
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
... |
#import spam
import filter_lta
#VALID_FILES = filter_lta.VALID_OBS().split('\n')
print filter_lta.VALID_OBS()
#def extract_basename():
def main():
#Convert the LTA file to the UVFITS format
#Generates UVFITS file with same basename as LTA file
spam.convert_lta_to_uvfits('Name of the file')
#Take g... | Add code for thread to filter valid files for processing
| #import spam
import filter_lta
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print THREAD_FILES
def main():
for i in THREAD_FILES:
LTA_FILES = os.chdir(... |
import rospy
from time import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure logging ... | UTILS: Add init-helper 'wait for subscriber'
For integration-testing purposes it is often useful to wait until a
particular node subscribes to you
| import rospy
import rostest
import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.