Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add tests for .read methods | """Test for `maas.client.viscera.sshkeys`."""
from .. import sshkeys
from ...testing import (
make_string_without_spaces,
TestCase,
)
from ..testing import bind
def make_origin():
return bind(sshkeys.SSHKeys, sshkeys.SSHKey)
class TestSSHKeys(TestCase):
def test__sshkeys_create(self):
""... | """Test for `maas.client.viscera.sshkeys`."""
import random
from .. import sshkeys
from ...testing import (
make_string_without_spaces,
TestCase,
)
from ..testing import bind
from testtools.matchers import Equals
def make_origin():
return bind(sshkeys.SSHKeys, sshkeys.SSHKey)
class TestSSHKeys(Test... |
Initialize takes exactly one parameter | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 10 10:56:16 2017
@author: kangwang
"""
import sys
from permamodel.components import bmi_Ku_component
x=bmi_Ku_component.BmiKuMethod()
x.initialize()
x.update()
x.finalize()
print x._values["ALT"][:]
| #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 10 10:56:16 2017
@author: kangwang
"""
import os
import sys
from permamodel.components import bmi_Ku_component
from permamodel.tests import examples_directory
cfg_file = os.path.join(examples_directory, 'Ku_method.cfg')
x = bmi_Ku_component.BmiKu... |
Revert "Add missing `tests_require` for `mock`" | from setuptools import setup
setup(
name='pyretry',
version="0.9",
description='Separate your retry logic from your business logic',
author='Bob Renwick',
author_email='bob.renwick@gmail.com',
url='https://github.com/bobbyrenwick/pyretry',
packages=['pyretry'],
tests_require=[
... | from setuptools import setup
setup(
name='pyretry',
version="0.9",
description='Separate your retry logic from your business logic',
author='Bob Renwick',
author_email='bob.renwick@gmail.com',
url='https://github.com/bobbyrenwick/pyretry',
packages=['pyretry'],
classifiers=(
'D... |
Bump version (a little late) | from __future__ import unicode_literals
from os.path import abspath, join, dirname
import random
__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_path('dist.male.first'),
... | from __future__ import unicode_literals
from os.path import abspath, join, dirname
import random
__title__ = 'names'
__version__ = '0.2.0.post1'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_path('dist.male.f... |
Add required dependency on "six" package | """CodeJail: manages execution of untrusted code in secure sandboxes."""
from setuptools import setup
setup(
name="codejail",
version="3.0.1",
packages=['codejail'],
zip_safe=False,
classifiers=[
"License :: OSI Approved :: Apache Software License",
"Operating System :: POSIX :: Ub... | """CodeJail: manages execution of untrusted code in secure sandboxes."""
from setuptools import setup
setup(
name="codejail",
version="3.0.2",
packages=['codejail'],
install_requires=['six'],
zip_safe=False,
classifiers=[
"License :: OSI Approved :: Apache Software License",
"O... |
Prepare new package for PyPI publication | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='typogrify',
version='2.0.0',
packages=find_packages(),
author='Christian Metts',
author_email='xian@mintchaos.com',
license='BSD',
description='Typography related template filters for Django & Jinja2 applicatio... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='typogrified',
version='0.0.0',
packages=find_packages(),
author='Justin Mayer',
author_email='entroP@gmail.com',
license='BSD',
description='Filters to enhance web typography, including support for Django & Jinj... |
Add classifier for Python 3.3 | #!/usr/bin/env python3
import sys
from distutils.core import setup
setup(
name='pathlib',
version=open('VERSION.txt').read().strip(),
py_modules=['pathlib'],
license='MIT License',
description='Object-oriented filesystem paths',
long_description=open('README.txt').read(),
author='Antoine P... | #!/usr/bin/env python3
import sys
from distutils.core import setup
setup(
name='pathlib',
version=open('VERSION.txt').read().strip(),
py_modules=['pathlib'],
license='MIT License',
description='Object-oriented filesystem paths',
long_description=open('README.txt').read(),
author='Antoine P... |
Add requirement for version 2.6 and higher | #!/usr/bin/env python
from setuptools import setup
import colors
setup(
name='ansicolors',
version=colors.__version__,
description='ANSI colors for Python',
long_description=open('README.rst').read(),
author='Giorgos Verigakis',
author_email='verigak@gmail.com',
url='http://github.com/ve... | #!/usr/bin/env python
from setuptools import setup
import colors
setup(
name='ansicolors',
version=colors.__version__,
description='ANSI colors for Python',
long_description=open('README.rst').read(),
author='Giorgos Verigakis',
author_email='verigak@gmail.com',
url='http://github.com/ve... |
Enable buildbucket builds to Angle tryserver. | # Copyright 2015 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 TryServerANGLE(Master.Master4a):
project_name = 'ANGLE Try Server'
master_port... | # Copyright 2015 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 TryServerANGLE(Master.Master4a):
project_name = 'ANGLE Try Server'
master_port... |
Update pyyaml requirement from <4.2,>=3.12 to >=3.12,<5.2 | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.0.2',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
... | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.0.2',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
... |
Update completion tests, checking for printed message | import os
import subprocess
import sys
from pathlib import Path
import typer
from typer.testing import CliRunner
from first_steps import tutorial001 as mod
runner = CliRunner()
app = typer.Typer()
app.command()(mod.main)
def test_show_completion():
result = subprocess.run(
[
"bash",
... | import os
import subprocess
import sys
from pathlib import Path
import typer
from typer.testing import CliRunner
from first_steps import tutorial001 as mod
runner = CliRunner()
app = typer.Typer()
app.command()(mod.main)
def test_show_completion():
result = subprocess.run(
[
"bash",
... |
Rename should_call future in test, raise exception on timeout | # -*- coding: utf-8 -*-
import nose.tools as nt
from asyncio import Future, gather, get_event_loop, sleep
from pyee import EventEmitter
def test_async_emit():
"""Test that event_emitters can handle wrapping coroutines
"""
loop = get_event_loop()
ee = EventEmitter(loop=loop)
future = Future()
... | # -*- coding: utf-8 -*-
import nose.tools as nt
from asyncio import Future, gather, get_event_loop, sleep
from pyee import EventEmitter
def test_async_emit():
"""Test that event_emitters can handle wrapping coroutines
"""
loop = get_event_loop()
ee = EventEmitter(loop=loop)
should_call = Future(... |
Put all the rooms under lobby, so it will be easier to configure. | service_room = "FIXME.lobby"
accesslog_room = "FIXME.accesslog"
combined_room = "FIXME.combined"
path = ""
xmpp_jid = ""
xmpp_password = "FIXME"
xmpp_ignore_cert = True
xmpp_extra_ca_certs = None
xmpp_rate_limit = 10
| service_room = "FIXME.lobby"
accesslog_room = service_room + ".accesslog"
combined_room = service_room + ".combined"
path = ""
xmpp_jid = ""
xmpp_password = "FIXME"
xmpp_ignore_cert = True
xmpp_extra_ca_certs = None
xmpp_rate_limit = 10
|
Include channel list in connection | from sockjs.tornado import SockJSConnection
from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider
from .. import route_handler
import json
pub_sub = RedisPubSubProvider()
class ConnectionMixin(object):
def to_json(self, data):
if isinstance(data, dict):
return data
... | from sockjs.tornado import SockJSConnection
from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider
from .. import route_handler
import json
pub_sub = RedisPubSubProvider()
class ConnectionMixin(object):
def to_json(self, data):
if isinstance(data, dict):
return data
... |
Modify exception handling to local config names | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigPa... | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigPa... |
Improve docs and import WebFingerBuilder | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.o... | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFi... |
Change URL used for CSS diagrams | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('... | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-t... |
Fix local dist to see if that fixes things | RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
| RAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
|
Change comment Google -> numpy docstring format | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is p... | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is p... |
Add ability to perform 'duplicate up'. | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.in... | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up... |
Use 'erase' to clear the screen | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
... | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
... |
Add test demonstrating aware comparisons | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6,... | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtime... |
Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`. | # Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
Declare the is_in_defined_group function, even if it is an alias of the is_in_group | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... |
Fix a broken export test |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distr... |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distr... |
Add test, which fails, of the gammatone filtering. | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... |
Use string as node title instead of wikicode | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wi... | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wi... |
Make interface name optional and remove unicode prefixes | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields... | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields... |
Put Flask in debug mode | from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
proc... | from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
proc... |
Add new module, get template path return absolut file path | # coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == ap... | # coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or ... |
Add basic auth create and parse utils. | # Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend fo... | # Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# ... |
Rebase most recent alembic change onto HEAD | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
... | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
... |
Upgrade to 2.0.0 (big refactoring done, tests TODO) | """
PySkCode, Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "1.0.7"
__maintainer__ = "Fabien Batteix"
_... | """
PySkCode, a Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "2.0.0"
__maintainer__ = "Fabien Batteix"... |
Use search.rnacentral.org as the sequence search endpoint | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
Add links to easy check-in in sadmin | from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
| from django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_ch... |
Refactor the code: add error handling of invalid or empty parameters, improve output format. | # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account... | # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano.exceptions import SyncanoDoesNotExist
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute... |
Reword Test Names for Clarity | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBO... | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBO... |
Print more explicit error reports for input file parsing | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a... | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
so... |
Fix CLI api (was missing entrypoint hook) | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorit... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algor... |
Update reference to application version | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " "
... | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " "
... |
Add disallowing of double blind auction highest bids being disclosed | """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
| """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
show_highest_bid = False
|
Add in field for making a `related` field on objects. | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from . import managers
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(mod... | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from . import managers
class RelatedObjectsField(RelatedObjectsDescriptor):
def __init__(self, model=None, from_field="sou... |
Add diagnostic output for when X-SendFile is misconfigured | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entri... | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entri... |
Order workshops by start date before title | from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
ev... | from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
ev... |
Replace Glue interface by more restrictive Unpack. | from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .glue import Glue
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
| from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .unpack import Unpack
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
from .fas... |
Add the base_name to the API routers for the custom query_set | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries'... | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.... |
Mark PDUs as not implemented to avoid false positives in reboots. | class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
| class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
|
Add lost handler for puppet | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleT... | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleT... |
Use 'my_counts' as name for MyCountsListView | from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.contrib.auth.views import login, logout
from cellcounter.main.views import new_count, view_cou... | from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.contrib.auth.views import login, logout
from cellcounter.main.views import new_count, view_cou... |
Fix query to exclude objects without relevant pages | from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand
from sopn_parsing.helpers.extract_tables import extract_ballot_table
from sopn_parsing.helpers.text_helpers import NoTextInDocumentError
class Command(BaseSOPNParsingCommand):
help = """
Parse tables out of PDFs in to ParsedSOPN models fo... | from django.db.models import OuterRef, Subquery
from official_documents.models import OfficialDocument
from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand
from sopn_parsing.helpers.extract_tables import extract_ballot_table
from sopn_parsing.helpers.text_helpers import NoTextInDocumentError
class... |
Add module imports to noweats init. | """
The NowEats application scrapes Twitter for what people are eating now.
"""
| """
The NowEats application scrapes Twitter for what people are eating now.
"""
import analysis
import collection
import extraction
|
Add dev token for licensing_journey bucket | TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token'
}
| TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'licensing_journey': 'licensing_journey-bearer-token'
}
|
Mark dojango as 0.5.6 alpha | VERSION = (0, 5, 5, 'final', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = '%s %... | VERSION = (0, 5, 6, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = '%s %... |
Add simplejson as test requirements for python 2.5 | """
Flask-Testing
--------------
Flask unittest integration.
Links
`````
* `documentation <http://packages.python.org/Flask-Testing>`_
* `development version
<http://bitbucket.org/danjac/flask-testing/get/tip.gz#egg=Flask-Testing-dev>`_
"""
from setuptools import setup
setup(
name='Flask-Testing',
versio... | """
Flask-Testing
--------------
Flask unittest integration.
Links
`````
* `documentation <http://packages.python.org/Flask-Testing>`_
* `development version
<http://bitbucket.org/danjac/flask-testing/get/tip.gz#egg=Flask-Testing-dev>`_
"""
import sys
from setuptools import setup
tests_require = [
'nose',
... |
Add python-keystoneclient to dependencies This is needed for keystone authentication | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-swiftbrowser',
version='0.22',
packages=['swiftbrow... | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-swiftbrowser',
version='0.22',
packages=['swiftbrow... |
Change the command: wonderful_bing -> bing. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from wonderful_bing import wonderful_bing
try:
import pypandoc
long_description = pypandoc.convert('README.md','rst')
except (IOError, ImportError):
with open('README.md') as f:
long_description = f.read()
setup(
name... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from wonderful_bing import wonderful_bing
try:
import pypandoc
long_description = pypandoc.convert('README.md','rst')
except (IOError, ImportError):
with open('README.md') as f:
long_description = f.read()
setup(
name... |
Fix PyPI README.MD showing problem. | from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-heroku-postgresify',
version = '0.4',
py_modules = ('postgresify',),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package de... | from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-heroku-postgresify',
version = '0.4',
py_modules = ('postgresify',),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package de... |
Add pip requirement for humanize. | #!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='ecmcli',
version... | #!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='ecmcli',
version... |
Update trove to remove Python 3.2, add Python 3.5 | from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst').read(),
license='MIT',
author='Brandon Rhodes',
... | from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst').read(),
license='MIT',
author='Brandon Rhodes',
... |
Add newline to end of file | import sys, logging
from rdflib.graph import ConjunctiveGraph
from trustyuri.rdf import RdfUtils, RdfTransformer
from rdflib.term import URIRef
import os
def transform(args):
filename = args[0]
baseuristr = args[1]
with open(filename, "r") as f:
rdfFormat = RdfUtils.get_format(filename)
... | import sys, logging
from rdflib.graph import ConjunctiveGraph
from trustyuri.rdf import RdfUtils, RdfTransformer
from rdflib.term import URIRef
import os
def transform(args):
filename = args[0]
baseuristr = args[1]
with open(filename, "r") as f:
rdfFormat = RdfUtils.get_format(filename)
... |
Implement a bad sig test | #!/usr/bin/env python
'''
Copyright 2009 Slide, Inc.
'''
import unittest
import pyecc
DEFAULT_DATA = 'This message will be signed\n'
DEFAULT_SIG = '$HPI?t(I*1vAYsl$|%21WXND=6Br*[>k(OR9B!GOwHqL0s+3Uq'
DEFAULT_PUBKEY = '8W;>i^H0qi|J&$coR5MFpR*Vn'
DEFAULT_PRIVKEY = 'my private key'
class ECC_Verify_Tests(unittest... | #!/usr/bin/env python
'''
Copyright 2009 Slide, Inc.
'''
import unittest
import pyecc
DEFAULT_DATA = 'This message will be signed\n'
DEFAULT_SIG = '$HPI?t(I*1vAYsl$|%21WXND=6Br*[>k(OR9B!GOwHqL0s+3Uq'
DEFAULT_PUBKEY = '8W;>i^H0qi|J&$coR5MFpR*Vn'
DEFAULT_PRIVKEY = 'my private key'
class ECC_Verify_Tests(unittest... |
Make new test use contains assertion | import sys
from nose.tools import ok_
from _utils import _output_eq, IntegrationSpec, _dispatch, trap, expect_exit
class ShellCompletion(IntegrationSpec):
"""
Shell tab-completion behavior
"""
def no_input_means_just_task_names(self):
_output_eq('-c simple_ns_list --complete', "z_toplevel\n... | import sys
from nose.tools import ok_
from _utils import (
_output_eq, IntegrationSpec, _dispatch, trap, expect_exit, assert_contains
)
class ShellCompletion(IntegrationSpec):
"""
Shell tab-completion behavior
"""
def no_input_means_just_task_names(self):
_output_eq('-c simple_ns_list -... |
Fix KeyError in Provide personal data form | from django.core.urlresolvers import reverse
from django.forms import model_to_dict
from django.http.response import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from common.models import Student
from sell.forms import PersonalDataForm
def index(request):
return HttpResponseRedirect(re... | from django.core.urlresolvers import reverse
from django.forms import model_to_dict
from django.http.response import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from common.models import Student
from sell.forms import PersonalDataForm
def index(request):
return HttpResponseRedirect(re... |
Migrate link tests to pytest | from nose.tools import eq_
from mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
'''
Test link's shares retrieving from constructor
'''
mocked_api = MagicMock()
mocked_api.get.return_value = {'shares': 123}
link = Link(api=mocked_api, url='www.google.com')
eq_(link... | from unittest.mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
""" Test link"s shares retrieving from constructor. """
mocked_api = MagicMock()
mocked_api.get.return_value = {"shares": 123}
link = Link(api=mocked_api, url="www.google.com")
assert link["shares"... |
Make collections link go to v2 route | from django.conf import settings
from django.conf.urls import include, url, patterns
from django.conf.urls.static import static
from settings import API_BASE
from website.settings import DEV_MODE
from . import views
base_pattern = '^{}'.format(API_BASE)
urlpatterns = [
### API ###
url(base_pattern,
i... | from django.conf import settings
from django.conf.urls import include, url, patterns
from django.conf.urls.static import static
from settings import API_BASE
from website.settings import DEV_MODE
from . import views
base_pattern = '^{}'.format(API_BASE)
urlpatterns = [
### API ###
url(base_pattern,
i... |
Switch to ruamel_yaml from conda by default | import sys
from setuptools import setup
# See https://stackoverflow.com/questions/19534896/enforcing-python-version-in-setup-py
if sys.version_info < (3,6):
sys.exit("Sorry, Python < 3.6 is not supported by Auspex.")
setup(
name='auspex',
version='0.1',
author='auspex Developers',
package_dir={'':... | import sys
from setuptools import setup
# See https://stackoverflow.com/questions/19534896/enforcing-python-version-in-setup-py
if sys.version_info < (3,6):
sys.exit("Sorry, Python < 3.6 is not supported by Auspex.")
setup(
name='auspex',
version='0.1',
author='auspex Developers',
package_dir={'':... |
Add long description / url | #!/usr/bin/env python
import setuptools
setuptools.setup(
name='bumper',
version='0.1.1',
author='Max Zheng',
author_email='maxzheng.os @t gmail.com',
description=open('README.rst').read(),
entry_points={
'console_scripts': [
'bump = bumper:bump',
],
},
install_requires=open('requir... | #!/usr/bin/env python
import setuptools
setuptools.setup(
name='bumper',
version='0.1.1',
author='Max Zheng',
author_email='maxzheng.os @t gmail.com',
description='Bump (pin/manage) your dependency requirements with ease',
long_description=open('README.rst').read(),
url='https://github.com/maxzheng/... |
Drop Python 2.5 support, add support for Python 3.2 | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-less',
version='0.1',
url='https://github.com/gears/gears-less',
license='ISC',
author='Mike Yumatov',
author_email='mike@yum... | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-less',
version='0.1',
url='https://github.com/gears/gears-less',
license='ISC',
author='Mike Yumatov',
author_email='mike@yum... |
Sort yml items to get same results for regendoc runs | # content of conftest.py
import pytest
def pytest_collect_file(parent, path):
if path.ext == ".yml" and path.basename.startswith("test"):
return YamlFile(path, parent)
class YamlFile(pytest.File):
def collect(self):
import yaml # we need a yaml parser, e.g. PyYAML
raw = yaml.safe_load... | # content of conftest.py
import pytest
def pytest_collect_file(parent, path):
if path.ext == ".yml" and path.basename.startswith("test"):
return YamlFile(path, parent)
class YamlFile(pytest.File):
def collect(self):
import yaml # we need a yaml parser, e.g. PyYAML
raw = yaml.safe_load... |
Make the quantum top-level a namespace package. | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/l... | |
Add option for determining requirement of 'state' parameter. | # coding: utf-8
from django.config import settings
from appconf import AppConf
class DJOAuthConf(AppConf):
class Meta:
prefix = 'djoauth'
ACCESS_TOKEN_LENGTH = 30
ACCESS_TOKEN_LIFETIME = 3600
ACCESS_TOKENS_REFRESHABLE = True
AUTHORIZATION_CODE_LENGTH = 30
AUTHORIZATION_CODE_LIFETIME = 120
CLIENT_K... | # coding: utf-8
from django.config import settings
from appconf import AppConf
class DJOAuthConf(AppConf):
class Meta:
prefix = 'djoauth'
ACCESS_TOKEN_LENGTH = 30
ACCESS_TOKEN_LIFETIME = 3600
ACCESS_TOKENS_REFRESHABLE = True
AUTHORIZATION_CODE_LENGTH = 30
AUTHORIZATION_CODE_LIFETIME = 120
CLIENT_K... |
Revert "Should break travis integration" | """
WSGI config for {{ project_name }} project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... | """
WSGI config for {{ project_name }} project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... |
Fix a bug in load_tags function | import os
import json
from dtags.utils import halt, expand_path
TAGS = os.path.expanduser('~/.dtags')
def load_tags():
"""Load the tags from disk."""
if not os.path.exists(TAGS):
try:
with open(TAGS, "w") as config_file:
json.dump({}, config_file)
except (IOError,... | import os
import json
from dtags.utils import halt, expand_path
TAGS = os.path.expanduser('~/.dtags')
def load_tags():
"""Load the tags from disk."""
if not os.path.exists(TAGS):
try:
with open(TAGS, "w") as config_file:
json.dump({}, config_file)
except (IOError,... |
Use round_fn to specify built-in round function | from mapbox_vector_tile.encoder import on_invalid_geometry_make_valid
from mapbox_vector_tile import encode as mvt_encode
def encode(fp, feature_layers, coord, bounds_merc):
tile = mvt_encode(feature_layers, quantize_bounds=bounds_merc,
on_invalid_geometry=on_invalid_geometry_make_valid)
... | from mapbox_vector_tile.encoder import on_invalid_geometry_make_valid
from mapbox_vector_tile import encode as mvt_encode
def encode(fp, feature_layers, coord, bounds_merc):
tile = mvt_encode(
feature_layers,
quantize_bounds=bounds_merc,
on_invalid_geometry=on_invalid_geometry_make_valid,
... |
Remove ability to recieve messages | from http_client import HttpClient
"""
@breif Facebook messenger bot
"""
class Bot():
def __init__(self, token):
self.api_token = token
self.client = HttpClient()
def send_message(self, message, completion):
def completion(response, error):
if error is None:
... | from http_client import HttpClient
class Bot():
"""
@breif Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient()
def send_message(self, message, completion):
def completion(response, error):
if error is None:
... |
Remove spaces in empty lines | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveG... | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveG... |
Remove the object from selection if it is selected | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Oper... |
Add comment to gender class | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
... | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
... |
Remove unnecessary imports form dummy tests. | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Du... | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_b... |
Add the answer of seventh question of Assignment 3 | """ Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) !... | """
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) ... |
Update log time, remove messages | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%... | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%... |
Add seperate key log handler | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# ... | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# ... |
Add links to Android/iOS apps | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED... |
Fix a packaging bug and make sure we also include templates directory. | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... |
Add missing import statement for whitenoise | """
WSGI config for untitled1 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... | """
WSGI config for untitled1 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Djan... |
Add WorkflowTestCase to integration tests | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from integration.ggrc import TestCase
from integration.ggrc_workflows.generator i... |
Fix watchmedo tests in Windows | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from watchdog import watchmedo
import pytest
import yaml
import os
def test_load_config_valid(tmpdir):
"""Verifies the load of a valid yaml file"""
yaml_file = os.path.join(tmpdir, 'config_file.yaml')
with open(yaml_file, 'w') as f:
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from watchdog import watchmedo
import pytest
from yaml.constructor import ConstructorError
from yaml.scanner import ScannerError
import os
def test_load_config_valid(tmpdir):
"""Verifies the load of a valid yaml file"""
yaml_file = os.path.join... |
Add additional application for gunicorn. | from app.main import bundle_app # noqa
# NOTE: uncomment out while genrating migration
# app = bundle_app({'MIGRATION': True})
| import os
from app.main import bundle_app # noqa
# NOTE: uncomment out while genrating migration
# app = bundle_app({'MIGRATION': True})
application = bundle_app({
'CLI_OR_DEPLOY': True,
'GUNICORN': 'gunicorn' in os.environ.get('SERVER_SOFTWARE', '')}) # noqa
|
Undo removing `import os` statement | # Setting for template directory not found by app_directories.Loader. This
# allows templates to be identified by two paths which enables a template to be
# extended by a template with the same identifier.
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_... | import os
# Setting for template directory not found by app_directories.Loader. This
# allows templates to be identified by two paths which enables a template to be
# extended by a template with the same identifier.
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts'... |
Add 'marker' to the list of tests to be run | # -*- coding: utf-8 -*-
#
__all__ = [
'annotate',
'basic_sin',
'circle_patch',
'dual_axis',
'errorband',
'errorbar',
'fancybox',
'heat',
'image_plot',
'legends2',
'legends',
'loglogplot',
'logplot',
'noise',
'noise2',
'patches',
'scatter',
'subplots',
'subplot4x4',
'text_overlay'... | # -*- coding: utf-8 -*-
#
__all__ = [
'annotate',
'basic_sin',
'circle_patch',
'dual_axis',
'errorband',
'errorbar',
'fancybox',
'heat',
'image_plot',
'legends2',
'legends',
'loglogplot',
'logplot',
'marker',
'noise',
'noise2',
'patches',
'scatter',
'subplots',
'subplot4x4',
't... |
Fix bug when parse version info | #!/usr/bin/env python
import os
from .data_format import dumps
class RemoteRepo(object):
def __init__(self, repo_dir):
self.repo_dir = repo_dir
# initial setup
pool_relative_dir = "pool"
package_relative_path = "index/package"
self.pool_absolute_dir = os.path.join(self.r... | #!/usr/bin/env python
import os
from .data_format import dumps
class RemoteRepo(object):
def __init__(self, repo_dir):
self.repo_dir = repo_dir
# initial setup
pool_relative_dir = "pool"
package_relative_path = "index/package"
self.pool_absolute_dir = os.path.join(self.r... |
Add RestPoseError and CheckPointExpiredError to top-level module symbols | # -*- coding: utf-8 -
#
# This file is part of the restpose python module, released under the MIT
# license. See the COPYING file for more information.
"""Python client for the RestPose search server.
"""
from .client import Server
from .version import dev_release, version_info, __version__
from restkit import Reso... | # -*- coding: utf-8 -
#
# This file is part of the restpose python module, released under the MIT
# license. See the COPYING file for more information.
"""Python client for the RestPose search server.
"""
from .client import Server
from .errors import RestPoseError, CheckPointExpiredError
from .version import dev_re... |
Move api auth url to api_patterns | from django.conf.urls import url, include
from rest_framework.authtoken.views import obtain_auth_token
from . import views
urlpatterns = [
url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf,
name='generate-pdf'),
url(r'^user/$', views.UserAdmin.as_view(), name='user'),
url(r'^user/(?P<pk>[0... | from django.conf.urls import url, include
from rest_framework.authtoken.views import obtain_auth_token
from . import views
api_patterns = [
url(r'^auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^token-auth/', obtain_auth_token, name='api-token-auth'),
url... |
Update for unit tests for PR 37 | """ Unit tests for grid_utils module. """
from datetime import datetime
import numpy as np
from tint import grid_utils
from tint.testing.sample_objects import grid, field
from tint.testing.sample_objects import params, grid_size
def test_parse_grid_datetime():
dt = grid_utils.parse_grid_datetime(grid)
asser... | """ Unit tests for grid_utils module. """
from datetime import datetime
import numpy as np
from tint import grid_utils
from tint.testing.sample_objects import grid, field
from tint.testing.sample_objects import params, grid_size
def test_parse_grid_datetime():
dt = grid_utils.parse_grid_datetime(grid)
asser... |
Add export for models module | # Copyright 2022 The KerasCV Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | # Copyright 2022 The KerasCV Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
Return full osascript output from getCurrentConfig | import configmanager
import osascript
APP_CONFIG_PATH = "../applications/"
applicationConfigs = configmanager.ConfigManager(APP_CONFIG_PATH)
#TODO: Make this user choosable
currentApplication = "radiant"
def getCurrentConfig():
return applicationConfigs[currentApplication]
def _executeCommand(command):
config = g... | import configmanager
import osascript
APP_CONFIG_PATH = "../applications/"
applicationConfigs = configmanager.ConfigManager(APP_CONFIG_PATH)
#TODO: Make this user choosable
currentApplication = "radiant"
def getCurrentConfig():
return applicationConfigs[currentApplication]
def _executeCommand(command):
config = g... |
Add awarding criteria field to configurator | # -*- coding: utf-8 -*-
from openprocurement.tender.openeu.adapters import TenderAboveThresholdEUConfigurator
from openprocurement.tender.esco.models import Tender
class TenderESCOConfigurator(TenderAboveThresholdEUConfigurator):
""" ESCO Tender configuration adapter """
name = "esco Tender configurator"
... | # -*- coding: utf-8 -*-
from openprocurement.tender.openeu.adapters import TenderAboveThresholdEUConfigurator
from openprocurement.tender.esco.models import Tender
class TenderESCOConfigurator(TenderAboveThresholdEUConfigurator):
""" ESCO Tender configuration adapter """
name = "esco Tender configurator"
... |
Make the rate-limiting test more fancy | from seleniumbase import BaseCase
from seleniumbase.common import decorators
class MyTestClass(BaseCase):
@decorators.rate_limited(4) # The arg is max calls per second
def print_item(self, item):
print item
def test_rate_limited_printing(self):
print "\nRunning rate-limited print test:"... | from seleniumbase import BaseCase
from seleniumbase.common import decorators
class MyTestClass(BaseCase):
@decorators.rate_limited(3.5) # The arg is max calls per second
def print_item(self, item):
print item
def test_rate_limited_printing(self):
print "\nRunning rate-limited print test... |
Fix the import all mamba error | from mamba.loader import describe, context
from mamba.hooks import before, after
from mamba.decorators import skip
__all__ = [describe, context, before, after, skip]
| from mamba.loader import describe, context
from mamba.hooks import before, after
from mamba.decorators import skip
__all__ = ['describe', 'context', 'before', 'after', 'skip']
|
Improve management command for exporting pi-xml | import sys
from django.core.management.base import BaseCommand
import pandas as pd
from tslib.readers import PiXmlReader
from tslib.writers import PiXmlWriter
from ddsc_core.models import Timeseries
class Command(BaseCommand):
args = "<pi.xml>"
help = "help"
def handle(self, *args, **options):
... | from optparse import make_option
from django.core.management.base import BaseCommand
import pandas as pd
from tslib.readers import PiXmlReader
from tslib.writers import PiXmlWriter
from ddsc_core.models import Timeseries
class Command(BaseCommand):
args = "<pi.xml>"
help = (
"Create pi.xml from a t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.