Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Remove 'bibpy.parsers' from package list
"""bibpy module setup script for distribution.""" from __future__ import with_statement import os import distutils.core def get_version(filename): with open(filename) as fh: for line in fh: if line.startswith('__version__'): return line.split('=')[-1].strip()[1:-1] distutil...
"""bibpy module setup script for distribution.""" from __future__ import with_statement import os import distutils.core def get_version(filename): with open(filename) as fh: for line in fh: if line.startswith('__version__'): return line.split('=')[-1].strip()[1:-1] distutil...
Add handling of which on Windows
# Convenience imports from pexpect from __future__ import absolute_import from pexpect import spawn, which, EOF, TIMEOUT
# Convenience imports from pexpect from __future__ import absolute_import from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT import os try: from pexpect import spawn import pty except ImportError: pty = None def which(filename): '''This takes a given filename; tries to find it ...
Update the PyPI version to 7.0.7.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.6', packages=['todoist', 'todoist.managers'], author='Doist Team'...
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.7', packages=['todoist', 'todoist.managers'], author='Doist Team'...
Fix up description and long_description.
import ez_setup ez_setup.use_setuptools() from setuptools import setup from django_allowdeny import NAME, VERSION setup( name=NAME, version=VERSION, author='Nimrod A. Abing', author_email='nimrod.abing@gmail.com', packages=['django_allowdeny'], package_data={ 'django_allowdeny': ['temp...
import ez_setup ez_setup.use_setuptools() from setuptools import setup from django_allowdeny import NAME, VERSION setup( name=NAME, version=VERSION, author='Nimrod A. Abing', author_email='nimrod.abing@gmail.com', packages=['django_allowdeny'], package_data={ 'django_allowdeny': ['temp...
Add an explicit requirement on PyYAML instead of relying the fact that pyvcloud pulls it in (but won't in future versions, since it doesn't need it)
######### # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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...
######### # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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...
Remove f-string to allow python 3.4 support
from setuptools import setup from setuptools.command.install import install import os import sys VERSION = '0.1.3' class VerifyVersionCommand(install): """Custom command to verify that the git tag matches our version""" description = 'Verify that the git tag matches our version' def run(self): t...
from setuptools import setup from setuptools.command.install import install import os import sys VERSION = '0.1.3' class VerifyVersionCommand(install): """Custom command to verify that the git tag matches our version""" description = 'Verify that the git tag matches our version' def run(self): t...
Update the PyPI version to 7.0.15.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.14', packages=['todoist', 'todoist.managers'], author='Doist Team...
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.15', packages=['todoist', 'todoist.managers'], author='Doist Team...
Increment version after change to get_base_url
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tes...
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tes...
Change the YAML outputter to use block mode and add some docs
''' YAML Outputter ''' # Third Party libs import yaml def __virtual__(): return 'yaml' def output(data): ''' Print out YAML ''' return yaml.dump(data)
''' Output data in YAML, this outputter defaults to printing in YAML block mode for better readability. ''' # Third Party libs import yaml def __virtual__(): return 'yaml' def output(data): ''' Print out YAML using the block mode ''' return yaml.dump(data, default_flow_style=False)
Update readme location following rename.
#!/usr/bin/env python # # coding: utf-8 from setuptools import setup, find_packages long_description = open('README.md').read() setup( name='captainhook', description='A collection of git commit hooks', version='0.8.3', long_description=long_description, author='Alex Couper', author_email='info...
#!/usr/bin/env python # # coding: utf-8 from setuptools import setup, find_packages long_description = open('README.rst').read() setup( name='captainhook', description='A collection of git commit hooks', version='0.8.3', long_description=long_description, author='Alex Couper', author_email='inf...
Revert "Move beautifulsoup4 from requires to install_requires"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from distutils.core import setup import gygax setup( name="gygax", version=gygax.__version__, description="A minimalistic IRC bot", long_description=open("README").read(), author="Tiit Pikma", author_email="1042524+thsnr@u...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from distutils.core import setup import gygax setup( name="gygax", version=gygax.__version__, description="A minimalistic IRC bot", long_description=open("README").read(), author="Tiit Pikma", author_email="1042524+thsnr@u...
Increment version for 0.0.2 release.
from setuptools import setup setup( name='twisted-hl7', version='0.0.2dev', author='John Paulett', author_email = 'john@paulett.org', url = 'http://twisted-hl7.readthedocs.org', license = 'BSD', platforms = ['POSIX', 'Windows'], keywords = ['HL7', 'Health Level 7', 'healthcare', 'health...
from setuptools import setup setup( name='twisted-hl7', version='0.0.2', author='John Paulett', author_email = 'john@paulett.org', url = 'http://twisted-hl7.readthedocs.org', license = 'BSD', platforms = ['POSIX', 'Windows'], keywords = ['HL7', 'Health Level 7', 'healthcare', 'health ca...
Update mock host to match new interface.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import sys import time from PySide import QtGui from segue import discover_processors from segue.backend.host.base import Host from segue.frontend.exporter import ExporterWidget class MockHost(Host): ...
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import sys import time from PySide import QtGui from segue import discover_processors from segue.backend.host.base import Host from segue.frontend.exporter import ExporterWidget class MockHost(Host): ...
Allow two command arguments for in and out files, or none for standard filter operations
#!/usr/bin/env python # mdstrip.py: makes new notebook from old, stripping md out """A tool to copy cell_type=("code") into a new file without grabbing headers/markdown (most importantly the md) NOTE: may want to grab the headers after all, or define new ones?""" import os import IPython.nbformat.current as nbf from...
#!/usr/bin/env python # mdstrip.py: makes new notebook from old, stripping md out """A tool to copy cell_type=("code") into a new file without grabbing headers/markdown (most importantly the md) NOTE: may want to grab the headers after all, or define new ones?""" import os import IPython.nbformat.current as nbf from...
Fix GStreamer packages use of prefix
GstreamerXzPackage (project = 'gstreamer', name = 'gstreamer', version = '1.4.5', configure_flags = [ '--disable-gtk-doc', '--prefix="%{prefix}' ])
GstreamerXzPackage (project = 'gstreamer', name = 'gstreamer', version = '1.4.5', configure_flags = [ '--disable-gtk-doc', '--prefix=%{prefix}' ])
Switch UI tests back to google chrome.
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions import time from webdriver_manager.chrome import ChromeDri...
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions import time from webdriver_manager.chrome import ChromeDri...
Change the intercept and coefficients to be floats, not unicode
from sklearn.linear_model import LinearRegression from bs4 import BeautifulSoup import numpy def from_pmml(self, pmml): """Returns a model with the intercept and coefficients represented in PMML file.""" model = self() # Reads the input PMML file with BeautifulSoup. with open(pmml, "r") as f: ...
from sklearn.linear_model import LinearRegression from bs4 import BeautifulSoup import numpy def from_pmml(self, pmml): """Returns a model with the intercept and coefficients represented in PMML file.""" model = self() # Reads the input PMML file with BeautifulSoup. with open(pmml, "r") as f: ...
Update environment test to have cross platform support
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "USER"} ] BAD_CHECKERS = [ {"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = che...
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "PATH"} ] BAD_CHECKERS = [ {"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = c...
FIX : increase test timer for buildbot in realtime
import threading import time import Queue from mne.realtime import StimServer, StimClient from nose.tools import assert_equal def test_connection(): """Test TCP/IP connection for StimServer <-> StimClient. """ # have to start a thread to simulate the effect of two # different computers since stim_se...
import threading import time import Queue from mne.realtime import StimServer, StimClient from nose.tools import assert_equal def test_connection(): """Test TCP/IP connection for StimServer <-> StimClient. """ # have to start a thread to simulate the effect of two # different computers since stim_se...
Add github3.py to the requirements
from setuptools import setup, find_packages import inbox requirements = [ "click", ] setup( name="inbox", version=inbox.__version__, url='TODO', description=inbox.__doc__, author=inbox.__author__, license=inbox.__license__, long_description="TODO", packages=find_packages(), in...
from setuptools import setup, find_packages import inbox requirements = [ "click", "github3.py", ] setup( name="inbox", version=inbox.__version__, url='TODO', description=inbox.__doc__, author=inbox.__author__, license=inbox.__license__, long_description="TODO", packages=find_...
Modify cappy dependency to work with Python 3.8
############################################################################### # Copyright 2015-2020 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. #######################################...
############################################################################### # Copyright 2015-2020 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. #######################################...
Add cookiecutter to install reqs
from setuptools import setup, find_packages # Work around mbcs bug in distutils. # http://bugs.python.org/issue10945 import codecs try: codecs.lookup('mbcs') except LookupError: ascii = codecs.lookup('ascii') func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs') codecs.register(func) setup( ...
from setuptools import setup, find_packages # Work around mbcs bug in distutils. # http://bugs.python.org/issue10945 import codecs try: codecs.lookup('mbcs') except LookupError: ascii = codecs.lookup('ascii') func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs') codecs.register(func) setup( ...
Change "Development Status" classifier to "5 - Production/Stable"
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pi...
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pi...
Change from planning to in beta
import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests', ] setup(name='googlemaps', version='2...
import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests', ] setup(name='googlemaps', version='2...
Downgrade tastypie to test-only dependency
""" Package configuration """ # pylint:disable=no-name-in-module, import-error from distutils.core import setup from setuptools import find_packages setup( name='IXWSAuth', version='0.1.1', author='Infoxchanhe Australia dev team', author_email='devs@infoxchange.net.au', packages=find_packages(), ...
""" Package configuration """ # pylint:disable=no-name-in-module, import-error from distutils.core import setup from setuptools import find_packages setup( name='IXWSAuth', version='0.1.1', author='Infoxchanhe Australia dev team', author_email='devs@infoxchange.net.au', packages=find_packages(), ...
Add management file to packages so django can find it
from setuptools import setup setup( name='django-simpleimages', version='1.0.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=['simpleimages', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), descriptio...
from setuptools import setup setup( name='django-simpleimages', version='1.0.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=['simpleimages', 'simpleimages.management.commands'], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LI...
Change is_luci default to True.
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from recipe_engine import recipe_api class RuntimeApi(recipe_api.RecipeApi): """This module assists in experimenting with production recipes. ...
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from recipe_engine import recipe_api class RuntimeApi(recipe_api.RecipeApi): """This module assists in experimenting with production recipes. ...
Use production dashboard API endpoint
import click import requests from shub.utils import find_api_key from shub.click_utils import log @click.command(help="Download a project's eggs from the Scrapy Cloud") @click.argument("project_id", required=True) def cli(project_id): auth = (find_api_key(), '') url = "https://staging.scrapinghub.com/api/egg...
import click import requests from shub.utils import find_api_key from shub.click_utils import log @click.command(help="Download a project's eggs from the Scrapy Cloud") @click.argument("project_id", required=True) def cli(project_id): auth = (find_api_key(), '') url = "https://dash.scrapinghub.com/api/eggs/b...
Allow overriding the DATABASE_URL with an environment varible if in development mode
from os import getenv class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL') STRIP_WWW_PREFIX = True API_KEY = getenv('API_KEY') class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABAS...
from os import getenv class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///app.db') STRIP_WWW_PREFIX = True API_KEY = getenv('API_KEY') class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True c...
Fix tests for Django 1.8
import django.template import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.loader.get_template_fr...
import django.template import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.Template("""{% load compile_static %}{{ "source"|com...
Add MCMemoryNetwork as a usable solver
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, '...
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers =...
Manage can now clean up pyc files
# Set the path import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask.ext.script import Manager, Server from maproulette import app manager = Manager(app) # Turn on debugger by default and reloader manager.add_command("runserver", Server( use_debugger = True, ...
# Set the path import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask.ext.script import Manager, Server from maproulette import app manager = Manager(app) # Turn on debugger by default and reloader manager.add_command("runserver", Server( use_debugger = True, ...
Allow processor to handle the fact that the attribute might have no values, or that they are not scoped
from ..attribute_processor import AttributeProcessorError from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another a...
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and ...
Comment all view return a json of all comments
from flask_classy import FlaskView from flask_user import current_user, login_required from ..models import CommentModel, PostModel from ..forms import CommentForm class Comment(FlaskView): def get(self): pass def all(self, post_id): comment = CommentModel() comment.query.add_filter(...
from flask import jsonify from flask_classy import FlaskView from flask_user import current_user, login_required from ..models import CommentModel, PostModel from ..forms import CommentForm class Comment(FlaskView): def get(self): pass def all(self, post_id): comment = CommentModel() ...
Make lil&big merged configuration hostname-aware for SITE_DOMAIN, this fixes the bad hostname in JS bookmarklets.
# -*- coding: utf-8 -*- # Settings for 1flow.net (local development) MAIN_SERVER = '127.0.0.1' from sparks.django.settings import include_snippets include_snippets( ( # Don't forget to deactivate nobother when we'ge got time to # fix other's bugs. Just kidding… '000_nobother', '00...
# -*- coding: utf-8 -*- # Settings for 1flow.net (local development) MAIN_SERVER = '127.0.0.1' import socket from sparks.django.settings import include_snippets include_snippets( ( # Don't forget to deactivate nobother when we'ge got time to # fix other's bugs. Just kidding… '000_nobother...
Prepare for deploy in deploy script.
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage...
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage...
Fix big fuckup from last commit
import logging from urllib.parse import urlsplit, urljoin from requests import get l = logging.getLogger(__name__) #TODO: move this somewhere sensible #TODO: useful error handling (CLI...) class HTTPClient: def __init__(self, base, user=None, password=None): self.base = base self.user = user ...
import logging from urllib.parse import urlsplit, urljoin from requests import get #TODO: move this somewhere sensible #TODO: useful error handling (CLI...) class HTTPClient: def __init__(self, base, user=None, password=None): self.base = base self.user = user self.password = password ...
Fix residual blocks to be on-par with paper.
from keras.layers import Convolution2D, Merge from keras.layers.advanced_activations import PReLU from keras.engine.topology import merge from eva.layers.masked_convolution2d import MaskedConvolution2D def ResidualBlock(model, filters): # 2h -> h block = Convolution2D(filters//2, 1, 1)(model) block = PReL...
from keras.layers import Convolution2D, Merge from keras.layers.advanced_activations import PReLU from eva.layers.masked_convolution2d import MaskedConvolution2D def ResidualBlock(model, filters): # 2h -> h block = PReLU()(model) block = MaskedConvolution2D(filters//2, 1, 1)(block) # h 3x3 -> h b...
Allow people to import ThriftConnection from elasticsearch package itself
from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelec...
from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelec...
Remove the unused import and fix testing library
""" :mod:`zsl.interface.webservice.performers.method` ------------------------------------------------- .. moduleauthor:: Martin Babka """ from __future__ import unicode_literals import logging from importlib import import_module, reload import sys from zsl.router.method import get_method_packages def call_expose...
""" :mod:`zsl.interface.webservice.performers.method` ------------------------------------------------- .. moduleauthor:: Martin Babka """ from __future__ import unicode_literals import logging from importlib import import_module import sys from zsl.router.method import get_method_packages def call_exposers_in_me...
Use new OpenAM token validation endpoint
# -*- coding:utf-8 -*- from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid=' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_function(*args...
# -*- coding:utf-8 -*- from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_functi...
Introduce scope_types in pause server policy
# Copyright 2016 Cloudbase Solutions Srl # 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 r...
# Copyright 2016 Cloudbase Solutions Srl # 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 r...
Allow the 'dataType' field to be overriden
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): clien...
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): clien...
Remove unused forms from context processor
from molo.profiles.forms import RegistrationForm from molo.profiles.forms import EditProfileForm, ProfilePasswordChangeForm def default_forms(request): return { 'registration_form': RegistrationForm(), 'edit_profile_form': EditProfileForm(), 'password_change_form': ProfilePasswordChangeFor...
from molo.profiles.forms import ProfilePasswordChangeForm def default_forms(request): return { 'password_change_form': ProfilePasswordChangeForm() } # TODO: remove this context processor def detect_freebasics(request): return { 'is_via_freebasics': 'Internet.org' in request....
Change update_addon_node() to return the Addon node, whether created or found.
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # 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 ...
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # 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 ...
Update fabric examples to reflect changes.
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just above @task @notify @task(default=True, alias="success") def sweet_task(some_arg, other_arg): """Alw...
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @task(default=True, alias="success") @notify def sweet_task(some_arg, other_arg): """Alw...
Add alias method named "distance"
from .bycython import eval __all__ = ('eval',)
from .bycython import eval def distance(*args, **kwargs): """"An alias to eval""" return eval(*args, **kwargs) __all__ = ('eval', 'distance')
Make Clear Inbox keyword more robust.
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) for fname in os.listdir(maildir): os.remove(os.path.join(maildir, fname)) def inbox_should_contain_num_m...
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) if not os.path.isdir(maildir): return for fname in os.listdir(maildir): os.remove(os.path.join...
Break celeryd restart into distict 'stop' and 'start' commands on deploy
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/api.freemusic.ninja" env.deploy_path = "/home/django/django_project" def deploy(): with cd(env.directory): run("git fetch") run("git reset --hard origin/master") sudo("p...
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/api.freemusic.ninja" env.deploy_path = "/home/django/django_project" def deploy(): with cd(env.directory): run("git fetch") run("git reset --hard origin/master") sudo("p...
Add permissions to organisation consultants endpoint
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer from radar.models import OrganisationConsultant from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView class OrganisationConsultantListView(ListCreateModelView): serializer_class = OrganisationCon...
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer from radar.models import OrganisationConsultant from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView from radar.permissions import AdminPermission class OrganisationConsultantListView(ListCreateMode...
Rename class to sync with new file name.
import subprocess import sys import unittest from django.conf import settings # # Must configure settings before importing base. # db = 'testdjangodb1' schema = 'django1' user = 'django1' passwd = 'django1' settings.configure( DEBUG=True, DATABASE_NAME=db, DATABASE_USER=user, DATABASE_PASSWORD=passw...
import subprocess import sys import unittest from django.conf import settings # # Must configure settings before importing base. # db = 'testdjangodb1' schema = 'django1' user = 'django1' passwd = 'django1' settings.configure( DEBUG=True, DATABASE_NAME=db, DATABASE_USER=user, DATABASE_PASSWORD=passw...
Solve Code Fights array replace problem
#!/usr/local/bin/python # Code Fights Add Border Problem def arrayReplace(inputArray, elemToReplace, substitutionElem): pass def main(): pass if __name__ == '__main__': main()
#!/usr/local/bin/python # Code Fights Add Border Problem def arrayReplace(inputArray, elemToReplace, substitutionElem): return [x if x != elemToReplace else substitutionElem for x in inputArray] def main(): tests = [ [[1, 2, 1], 1, 3, [3, 2, 3]], [[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]], ...
Make a shortcut for debugging with pdb
INFINITY = 1e+31 DIRECTIONS = ((-1,-1),(-1,0),(-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)) EMPTY = 0 BLACK = 1 WHITE = 2 def opposite_colour(col): if col == BLACK: return WHITE if col == WHITE: return BLACK
INFINITY = 1e+31 DIRECTIONS = ((-1,-1),(-1,0),(-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)) EMPTY = 0 BLACK = 1 WHITE = 2 def opposite_colour(col): if col == BLACK: return WHITE if col == WHITE: return BLACK from pdb import set_trace as st
Make sure the filter arg is a string.
# coding: utf-8 from django.template import Library from ..html import TermsHTMLReconstructor register = Library() @register.filter def replace_terms(html): parser = TermsHTMLReconstructor() parser.feed(html) return parser.out
# coding: utf-8 from django.template import Library from django.template.defaultfilters import stringfilter from ..html import TermsHTMLReconstructor register = Library() @register.filter @stringfilter def replace_terms(html): parser = TermsHTMLReconstructor() parser.feed(html) return parser.out
Fix checking of limit parameter
from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): intParam = int(param) if str(intParam) != param: return [False, param] return [(intParam >= 0), param] def checkPermission(self, user,...
from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): try: intParam = int(param) except ValueError: return [False, param] if str(intParam) != param: return [False, param] ...
Change the feature calculation to match the new unified format
# Standard imports import math import logging import numpy as np import emission.core.common as ec import emission.analysis.section_features as sf def calDistance(point1, point2): return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude]) def calHeading(point1, point2): re...
# Standard imports import math import logging import numpy as np import emission.core.common as ec import emission.analysis.section_features as sf def calDistance(point1, point2): return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude]) def calHeading(point1, point2): re...
Remove application flag, not an application
# -*- coding: utf-8 -*- # Copyright 2013-2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) {'name': 'Connector', 'version': '10.0.1.0.0', 'author': 'Camptocamp,Openerp Connector Core Editors,' 'Odoo Community Association (OCA)', 'website': 'http://odoo-connector.com',...
# -*- coding: utf-8 -*- # Copyright 2013-2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) {'name': 'Connector', 'version': '10.0.1.0.0', 'author': 'Camptocamp,Openerp Connector Core Editors,' 'Odoo Community Association (OCA)', 'website': 'http://odoo-connector.com',...
Update the default settings file to include the database threaded option
""" Copyright [2009-2014] 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-2014] 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...
Load DB migrations before testing and use verbose=2 and failfast
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } ...
import os import sys try: sys.path.append('demoproject') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings") from django.conf import settings from django.core.management import call_command settings.DATABASES['default']['NAME'] = ':memory:' settings.INSTALLED_APPS.append('...
Write name and version to output file.
from __future__ import unicode_literals class VisualFormatWriter(object): """ A class responsible for writing observation data in AAVSO `Visual File Format`_. The API here mimics the ``csv`` module in Python standard library. .. _`Visual File Format`: http://www.aavso.org/aavso-visual-file-forma...
from __future__ import unicode_literals import pyaavso class VisualFormatWriter(object): """ A class responsible for writing observation data in AAVSO `Visual File Format`_. The API here mimics the ``csv`` module in Python standard library. .. _`Visual File Format`: http://www.aavso.org/aavso-v...
Add an entry in URLconf
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'example.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'example.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ) # Add an entry in you...
Add URL for signup api endpoint
from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'), ]
from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'), url(r'^signup/$', views.SignupView.as_vie...
Fix for a tamper script (in some cases comments were not inserted)
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import randomRange from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def tamper(payload, **kwargs)...
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import randomRange from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def tamper(payload, **kwargs)...
Fix issue with latest sdk: cannot import name sandbox
# appengine_config.py from google.appengine.ext import vendor # Add any libraries install in the "lib" folder. vendor.add('lib') import os if os.environ.get('SERVER_SOFTWARE', '').startswith('Development'): import imp import os.path import inspect from google.appengine.tools.devappserver2.python impo...
# appengine_config.py from google.appengine.ext import vendor # Add any libraries install in the "lib" folder. vendor.add('lib') import os if os.environ.get('SERVER_SOFTWARE', '').startswith('Development'): import imp import os.path import inspect from google.appengine.tools.devappserver2.python.runt...
Add file with linear algebra numpy operations
''' 2.1 - Numpy Array library ''' #!/usr/bin/env import numpy as np def main(): '''' # 1) Create two vectors 'a' and 'b', and sum them. # Standart n = 3 a = [x**2 for x in range(1, n + 1)] b = [x**3 for x in range(1, n + 1)] v = plainVectorAddition(a, b) # Numpy n = 3 a = np.ara...
''' 2.1 - Numpy Array library - Sum of two vectors - Usage: python smpl4.py n Where 'n' specifies the size of the vector. The program make performance comparisons and print the results. ''' #!/usr/bin/env import numpy as np import sys from datetime import datetime def main(): size = int(sys.argv[1]) s...
Handle errors with JSON messages.
from flask import g from flask.ext.login import current_user from tmi.core import app from tmi.assets import assets # noqa from tmi.views.ui import ui # noqa from tmi.views.auth import login, logout # noqa from tmi.views.admin import admin # noqa from tmi.views.cards_api import blueprint as cards_api @app.before_req...
from flask import g, request from flask.ext.login import current_user from werkzeug.exceptions import HTTPException from tmi.core import app from tmi.forms import Invalid from tmi.util import jsonify from tmi.assets import assets # noqa from tmi.views.ui import ui # noqa from tmi.views.auth import login, logout # noqa...
Add deprecation warning to bitvec function
""" Boolean Vector Logic Expressions This module is deprecated. The functionality has been superceded by the bfarray module. Interface Functions: bitvec """ from pyeda.boolalg import expr from pyeda.boolalg import bfarray def bitvec(name, *dims): """Return a new array of given dimensions, filled with Expres...
""" Boolean Vector Logic Expressions This module is deprecated. The functionality has been superceded by the bfarray module. Interface Functions: bitvec """ from warnings import warn from pyeda.boolalg import expr from pyeda.boolalg import bfarray def bitvec(name, *dims): """Return a new array of given dim...
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): '''@param short_name can be e.g. mx''' model = rdf_helper.init_model( rdf_helper.JURI_RDF_PATH) ...
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 ...
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): ...
# # 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): ...
Use `compile` function for `gradient` function
# Module containing functions to compile and differentiate Theano graphs. import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and re...
# Module containing functions to compile and differentiate Theano graphs. import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and re...
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): """ Gets all cases with a specified owner ID that...
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...
Add simple serializers for books and authors
"""restapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
"""restapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
Fix glibc version detect string
import sys import platform from setuptools import setup, Extension cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5...
import sys import platform from setuptools import setup, Extension cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' if is_glibc: glibc_ver = platform.libc_ver()[1] libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) libc_ok = libc_nu...
Add long description to the package.
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...
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...
Make UUIDField have a fixed max-length
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.with_metaclass(mode...
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.with_metaclass(mode...
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_all', 'load_all_gen'] class OrderedRoundTripLoader(yaml.RoundTripLoader): """ Extends the default round trip YAML ...
""" 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...
Comment out gevent until we need it
# TODO, figure out how to load gevent monkey patch cleanly in production try: from gevent.monkey import patch_all patch_all() except ImportError: print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if os.environ.get('S...
# TODO, figure out how to load gevent monkey patch cleanly in production # try: # from gevent.monkey import patch_all # patch_all() # except ImportError: # print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if os.envi...
Add function for linear interpolation (lerp)
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
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
Check and raise HTTP errors
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None pay...
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None pay...
Move up to release 6 (1.3.0 Beta 3b)
version = '1.3.0' milestone = 'Chami' release_number = '5' projectURL = 'http://syncplay.pl/'
version = '1.3.0' milestone = 'Chami' release_number = '6' projectURL = 'http://syncplay.pl/'
Add timestamp field to Listing
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Listing(Base): __tablename__ = 'listings' id = Column(Integer, primary_key=True) craigslist_id = Column(String, u...
from sqlalchemy import create_engine, Column, DateTime, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import func Base = declarative_base() class Listing(Base): __tablename__ = 'listings' id = Column(Integer, primary_key=...
Use argparse instead of optparse
import binascii import os import time from optparse import OptionParser def gen_random_object_id(): timestamp = '{0:x}'.format(int(time.time())) rest = binascii.b2a_hex(os.urandom(8)).decode('ascii') return timestamp + rest if __name__ == '__main__': parser = OptionParser() parser.add_option('-l...
import binascii import os import time from argparse import ArgumentParser def gen_random_object_id(): timestamp = '{0:x}'.format(int(time.time())) rest = binascii.b2a_hex(os.urandom(8)).decode('ascii') return timestamp + rest if __name__ == '__main__': parser = ArgumentParser(description='Generate a...
Revert "Picture access from admin console"
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'lots_client.views.home', name='home'), url(r'^status/$', 'lots_client.views.status', name='status'), url(r'^appl...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'lots_client.views.home', name='home'), url(r'^status/$', 'lots_client.views.status', name='status'), url(r'^apply/$', 'lots_client.views.apply', ...
Add more profile model tests
from django.contrib.auth import get_user_model from django.test import TestCase from portal.models import Profile class TestProfile(TestCase): """Profile test suite""" users = ["john", "jane"] UserModel = get_user_model() def setUp(self): for user in self.users: self.UserModel....
from django.contrib.auth import get_user_model from django.test import TestCase from portal.models import Profile class TestProfile(TestCase): """Profile test suite""" users = ["john", "jane"] UserModel = get_user_model() def setUp(self): for user in self.users: self.UserModel....
Fix python 2 testing issue
__all__ = [ 'test', ] import unittest import fnmatch import os try: from colour_runner.runner import ColourTextTestRunner as TextTestRunner except ImportError: from unittest import TextTestRunner def test(close=False): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. ...
__all__ = [ 'test', ] import unittest import fnmatch import os try: from colour_runner.runner import ColourTextTestRunner as TextTestRunner except ImportError: from unittest import TextTestRunner def test(close=False): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. ...
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...
Remove the fully qualified module reference 'trombi.client'
# Copyright (c) 2010 Inoi Oy # # 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, including without limitation the rights # to use, copy, modify, merge, publish, distribute,...
# Copyright (c) 2010 Inoi Oy # # 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, including without limitation the rights # to use, copy, modify, merge, publish, distribute,...
Fix dangerous default mutable value
from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict={}): if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total = cart_dict["total"] self...
from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict=None): cart_dict = cart_dict or {} if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total...
Fix running tests on lower Django versions
#!/usr/bin/env python from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") django.setup() module_root = os.path.dirname(os.path.realp...
#!/usr/bin/env python from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") if django.VERSION >= (1,7): django.setup() module_...
Customize the command runner for cleaner output
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from warehouse import script def main(): script.run() if __name__ == "__main__": main()
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import sys from flask.ext.script import InvalidCommand # pylint: disable=E0611,F0401 from warehouse import script def main(): # This is copied over from script.run and modified for Warehouse try:...
Read HTTP server from env variables
from __future__ import unicode_literals import os import pprint import StringIO from flask import Flask from flask import request app = Flask(__name__) @app.route("/") def echo(): stream = StringIO.StringIO() indent = int(os.environ.get('PRINT_INDENT', 1)) pprint.pprint(request.environ, indent=indent, s...
from __future__ import unicode_literals import os import pprint import StringIO from flask import Flask from flask import request app = Flask(__name__) @app.route("/") def echo(): stream = StringIO.StringIO() indent = int(os.environ.get('PRINT_INDENT', 1)) pprint.pprint(request.environ, indent=indent, s...
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 graph. Time complexity for graph G(V, E)...
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...
Update code for changed function.
#!/usr/bin/python import sys if 'darwin' in sys.platform: sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python') sys.path.append('.') import adapter adapter.main.run_tcp_server(multiple=False)
#!/usr/bin/python import sys if 'darwin' in sys.platform: sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python') sys.path.append('.') import adapter adapter.main.run_tcp_server()
Add 2 tests for Utils
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): ...
import os from unittest import TestCase import requests from furikura import utils from furikura.config import Config config_cls = Config() def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/...
Write to temp directories in such a way that files get cleaned up
import tempfile import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty_format_json(fil...
import io import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty_format_json(filename,...
Fix DATrie support under Python 2.
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(key, str): ...
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from six import text_type from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not is...
Update related name for `layout` field.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( ...
Add menu to choose star or planet, print results.
import ephem from datetime import datetime def const(planet_name): # function name and parameters planet_class = getattr(ephem, planet_name) # sets ephem object class date_class = datetime.now() planet = planet_class() # sets planet variable south_bend = ephem.Observer...
import ephem from datetime import datetime def star(star_name): star = ephem.star(star_name) south_bend = ephem.Observer() date_class = datetime.now() south_bend.lat = '41.15' south_bend.lon = '-86.26' south_bend.date = date_class star.compute(south_bend) print date_class print ...
Refactor handling of pretty parameter.
from falcon.util.uri import parse_query_string import json from api.actions import pos_tagging class ApiResource(object): def parse_request_data(self, raw_post_data): try: raw_correct_encoded = str(raw_post_data, 'utf-8') except UnicodeDecodeError: raw_correct_encoded = "" ...
from falcon.util.uri import parse_query_string import json from api.actions import pos_tagging class ApiResource(object): def parse_request_data(self, raw_post_data): encoded_raw_post_data = "" try: encoded_raw_post_data = str(raw_post_data, 'utf-8') except UnicodeDecodeError: ...
Convert binhex regression test to PyUnit. We could use a better test for this.
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Roger E. Masse """ import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open...
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Based on an original test by Roger E. Masse. """ import binhex import os import tempfile import test_support import unittest class BinHexTestCase(unittest.TestCase): def setUp(self): self.f...