<commit_before>from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
import os
import re
import codecs
import platform
from distutils.sysconfig import get_config_var, get_python_inc
from distutils.version import LooseVersion
import sys
import subprocess

# to publish use:
# > python setup.py sdist bdist_wheel upload
# which depends on ~/.pypirc

# This is copied from @robbuckley's fix for Panda's
# For mac, ensure extensions are built for macos 10.9 when compiling on a
# 10.9 system or above, overriding distuitls behavior which is to target
# the version that python was built for. This may be overridden by setting
# MACOSX_DEPLOYMENT_TARGET before calling setup.pcuda-comp-generalizey
if sys.platform == 'darwin':
    if 'MACOSX_DEPLOYMENT_TARGET' not in os.environ:
        current_system = LooseVersion(platform.mac_ver()[0])
        python_target = LooseVersion(get_config_var('MACOSX_DEPLOYMENT_TARGET'))
        if python_target < '10.9' and current_system >= '10.9':
            os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9'

here = os.path.abspath(os.path.dirname(__file__))

def read(*parts):
    with codecs.open(os.path.join(here, *parts), 'r') as fp:
        return fp.read()

def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

# Extend the default build_ext class to bootstrap numpy installation
# that are needed to build C extensions.
# see https://stackoverflow.com/questions/19919905/how-to-bootstrap-numpy-installation-in-setup-py
class build_ext(_build_ext):
    def finalize_options(self):
        _build_ext.finalize_options(self)
        if isinstance(__builtins__, dict):
            __builtins__["__NUMPY_SETUP__"] = False
        else:
            setattr(__builtins__, "__NUMPY_SETUP__", False)
        import numpy
        print("numpy.get_include()", numpy.get_include())
        self.include_dirs.append(numpy.get_include())

def find_in_path(name, path):
    """Find a file in a search path and return its full path."""
    # adapted from:
    # http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
    for dir in path.split(os.pathsep):
        binpath = os.path.join(dir, name)
        if os.path.exists(binpath):
            return os.path.abspath(binpath)
    return None

def get_cuda_path():
    """Return a tuple with (base_cuda_directory, full_path_to_nvcc_compiler)."""
    # Inspired by https://github.com/benfred/implicit/blob/master/cuda_setup.py
    nvcc_bin = "nvcc.exe" if sys.platform == "win32" else "nvcc"

    if "CUDAHOME" in os.environ:
        cuda_home = os.environ["CUDAHOME"]
    elif "CUDA_PATH" in os.environ:
        cuda_home = os.environ["CUDA_PATH"]
    else:
        # otherwise, search the PATH for NVCC
        found_nvcc = find_in_path(nvcc_bin, os.environ["PATH"])
        if found_nvcc is None:
            print(
                "The nvcc binary could not be located in your $PATH. Either " +
                " add it to your path, or set $CUDAHOME to enable CUDA"
            )
            return None
        cuda_home = os.path.dirname(os.path.dirname(found_nvcc))
    if not os.path.exists(os.path.join(cuda_home, "include")):
        print("Failed to find cuda include directory, using /usr/local/cuda")
        cuda_home = "/usr/local/cuda"

    nvcc = os.path.join(cuda_home, "bin", nvcc_bin)
    if not os.path.exists(nvcc):
        print("Failed to find nvcc compiler in %s, trying /usr/local/cuda" %
              nvcc)
        cuda_home = "/usr/local/cuda"
        nvcc = os.path.join(cuda_home, "bin", nvcc_bin)

    return (cuda_home, nvcc)

def compile_cuda_module(host_args):
    libname = '_cext_gpu.lib' if sys.platform == 'win32' else 'lib_cext_gpu.a'
    lib_out = 'build/' + libname
    if not os.path.exists('build/'):
        os.makedirs('build/')

    cuda_home, nvcc = get_cuda_path()

    print("NVCC ==> ", nvcc)
    arch_flags = "-arch=sm_60 " + \
                 "-gencode=arch=compute_70,code=sm_70 " + \
                 "-gencode=arch=compute_75,code=sm_75 " + \
                 "-gencode=arch=compute_75,code=compute_75"
    nvcc_command = "shap/cext/_cext_gpu.cu -lib -o {} -Xcompiler {} -I{} " \
                   "--std c++14 " \
                   "--expt-extended-lambda " \
                   "--expt-relaxed-constexpr {}".format(
                       lib_out,
                       ','.join(host_args),
                       get_python_inc(), arch_flags)
    print("Compiling cuda extension, calling nvcc with arguments:")
    print([nvcc] + nvcc_command.split(' '))
    subprocess.run([nvcc] + nvcc_command.split(' '), check=True)
    return 'build', '_cext_gpu'

def run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True, test_catboost=True,
              test_spark=True, test_pyod=True, with_cuda=True):
    ext_modules = []
    if with_binary:
        compile_args = []
        if sys.platform == 'zos':
            compile_args.append('-qlonglong')
        if sys.platform == 'win32':
            compile_args.append('/MD')

        ext_modules.append(
            Extension('shap._cext', sources=['shap/cext/_cext.cc'],
                      extra_compile_args=compile_args))
    if with_cuda:
        try:
            cuda_home, nvcc = get_cuda_path()
            if sys.platform == 'win32':
                cudart_path = cuda_home + '/lib/x64'
            else:
                cudart_path = cuda_home + '/lib64'
                compile_args.append('-fPIC')

            lib_dir, lib = compile_cuda_module(compile_args)

            ext_modules.append(
                Extension('shap._cext_gpu', sources=['shap/cext/_cext_gpu.cc'],
                          extra_compile_args=compile_args,
                          library_dirs=[lib_dir, cudart_path],
                          libraries=[lib, 'cudart'],
                          depends=['shap/cext/_cext_gpu.cu', 'shap/cext/gpu_treeshap.h','setup.py'])
            )
        except Exception as e:
            raise Exception("Error building cuda module: " + repr(e))

    tests_require = ['pytest', 'pytest-mpl', 'pytest-cov']
    if test_xgboost:
        tests_require += ['xgboost']
    if test_lightgbm:
        tests_require += ['lightgbm']
    if test_catboost:
        tests_require += ['catboost']
    if test_spark:
        tests_require += ['pyspark']
    if test_pyod:
        tests_require += ['pyod']

    extras_require = {
        'plots': [
            'matplotlib',
            'ipython'
        ],
        'others': [
            'lime',
        ],
        'docs': [
            'matplotlib',
            'ipython',
            'numpydoc',
            'sphinx_rtd_theme',
            'sphinx',
            'nbsphinx',
        ]
    }
    extras_require['test'] = tests_require
    extras_require['all'] = list(set(i for val in extras_require.values() for i in val))

    setup(
        name='shap',
        version=find_version("shap", "__init__.py"),
        description='A unified approach to explain the output of any machine learning model.',
        long_description="SHAP (SHapley Additive exPlanations) is a unified approach to explain "
                         "the output of " + \
                         "any machine learning model. SHAP connects game theory with local "
                         "explanations, uniting " + \
                         "several previous methods and representing the only possible consistent "
                         "and locally accurate " + \
                         "additive feature attribution method based on expectations.",
        long_description_content_type="text/markdown",
        url='http://github.com/slundberg/shap',
        author='Scott Lundberg',
        author_email='slund1@cs.washington.edu',
        license='MIT',
        packages=[
            'shap', 'shap.explainers', 'shap.explainers.other', 'shap.explainers._deep',
            'shap.plots', 'shap.plots.colors', 'shap.benchmark', 'shap.maskers', 'shap.utils',
            'shap.actions', 'shap.models'
        ],
        package_data={'shap': ['plots/resources/*', 'cext/tree_shap.h']},
        cmdclass={'build_ext': build_ext},
        setup_requires=['numpy'],
        install_requires=['numpy', 'scipy', 'scikit-learn', 'pandas', 'tqdm>4.25.0',
                          'slicer==0.0.7', 'numba'],
        extras_require=extras_require,
        ext_modules=ext_modules,
        classifiers=[
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.6',
        ],
        zip_safe=False
        # python_requires='>3.0' we will add this at some point
    )

def try_run_setup(**kwargs):
    """ Fails gracefully when various install steps don't work.
    """

    try:
        run_setup(**kwargs)
    except Exception as e:
        print(str(e))
        if "xgboost" in str(e).lower():
            kwargs["test_xgboost"] = False
            print("Couldn't install XGBoost for testing!")
            try_run_setup(**kwargs)
        elif "lightgbm" in str(e).lower():
            kwargs["test_lightgbm"] = False
            print("Couldn't install LightGBM for testing!")
            try_run_setup(**kwargs)
        elif "catboost" in str(e).lower():
            kwargs["test_catboost"] = False
            print("Couldn't install CatBoost for testing!")
            try_run_setup(**kwargs)
        elif "cuda" in str(e).lower():
            kwargs["with_cuda"] = False
            print(
                "WARNING: Could not compile cuda extensions")
            try_run_setup(**kwargs)
        elif kwargs["with_binary"]:
            kwargs["with_binary"] = False
            print(
                "WARNING: The C extension could not be compiled, sklearn tree models not "
                "supported.")
            try_run_setup(**kwargs)
        elif "pyod" in str(e).lower():
            kwargs["test_pyod"] = False
            print("Couldn't install PyOD for testing!")
            try_run_setup(**kwargs)
        else:
            print("ERROR: Failed to build!")

# we seem to need this import guard for appveyor
if __name__ == "__main__":
    try_run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True, test_spark=True,
                  test_pyod=True, with_cuda=True)
<commit_msg>added cloudpickle dependency<commit_after>from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
import os
import re
import codecs
import platform
from distutils.sysconfig import get_config_var, get_python_inc
from distutils.version import LooseVersion
import sys
import subprocess

# to publish use:
# > python setup.py sdist bdist_wheel upload
# which depends on ~/.pypirc

# This is copied from @robbuckley's fix for Panda's
# For mac, ensure extensions are built for macos 10.9 when compiling on a
# 10.9 system or above, overriding distuitls behavior which is to target
# the version that python was built for. This may be overridden by setting
# MACOSX_DEPLOYMENT_TARGET before calling setup.pcuda-comp-generalizey
if sys.platform == 'darwin':
    if 'MACOSX_DEPLOYMENT_TARGET' not in os.environ:
        current_system = LooseVersion(platform.mac_ver()[0])
        python_target = LooseVersion(get_config_var('MACOSX_DEPLOYMENT_TARGET'))
        if python_target < '10.9' and current_system >= '10.9':
            os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9'

here = os.path.abspath(os.path.dirname(__file__))

def read(*parts):
    with codecs.open(os.path.join(here, *parts), 'r') as fp:
        return fp.read()

def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

# Extend the default build_ext class to bootstrap numpy installation
# that are needed to build C extensions.
# see https://stackoverflow.com/questions/19919905/how-to-bootstrap-numpy-installation-in-setup-py
class build_ext(_build_ext):
    def finalize_options(self):
        _build_ext.finalize_options(self)
        if isinstance(__builtins__, dict):
            __builtins__["__NUMPY_SETUP__"] = False
        else:
            setattr(__builtins__, "__NUMPY_SETUP__", False)
        import numpy
        print("numpy.get_include()", numpy.get_include())
        self.include_dirs.append(numpy.get_include())

def find_in_path(name, path):
    """Find a file in a search path and return its full path."""
    # adapted from:
    # http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
    for dir in path.split(os.pathsep):
        binpath = os.path.join(dir, name)
        if os.path.exists(binpath):
            return os.path.abspath(binpath)
    return None

def get_cuda_path():
    """Return a tuple with (base_cuda_directory, full_path_to_nvcc_compiler)."""
    # Inspired by https://github.com/benfred/implicit/blob/master/cuda_setup.py
    nvcc_bin = "nvcc.exe" if sys.platform == "win32" else "nvcc"

    if "CUDAHOME" in os.environ:
        cuda_home = os.environ["CUDAHOME"]
    elif "CUDA_PATH" in os.environ:
        cuda_home = os.environ["CUDA_PATH"]
    else:
        # otherwise, search the PATH for NVCC
        found_nvcc = find_in_path(nvcc_bin, os.environ["PATH"])
        if found_nvcc is None:
            print(
                "The nvcc binary could not be located in your $PATH. Either " +
                " add it to your path, or set $CUDAHOME to enable CUDA"
            )
            return None
        cuda_home = os.path.dirname(os.path.dirname(found_nvcc))
    if not os.path.exists(os.path.join(cuda_home, "include")):
        print("Failed to find cuda include directory, using /usr/local/cuda")
        cuda_home = "/usr/local/cuda"

    nvcc = os.path.join(cuda_home, "bin", nvcc_bin)
    if not os.path.exists(nvcc):
        print("Failed to find nvcc compiler in %s, trying /usr/local/cuda" %
              nvcc)
        cuda_home = "/usr/local/cuda"
        nvcc = os.path.join(cuda_home, "bin", nvcc_bin)

    return (cuda_home, nvcc)

def compile_cuda_module(host_args):
    libname = '_cext_gpu.lib' if sys.platform == 'win32' else 'lib_cext_gpu.a'
    lib_out = 'build/' + libname
    if not os.path.exists('build/'):
        os.makedirs('build/')

    cuda_home, nvcc = get_cuda_path()

    print("NVCC ==> ", nvcc)
    arch_flags = "-arch=sm_60 " + \
                 "-gencode=arch=compute_70,code=sm_70 " + \
                 "-gencode=arch=compute_75,code=sm_75 " + \
                 "-gencode=arch=compute_75,code=compute_75"
    nvcc_command = "shap/cext/_cext_gpu.cu -lib -o {} -Xcompiler {} -I{} " \
                   "--std c++14 " \
                   "--expt-extended-lambda " \
                   "--expt-relaxed-constexpr {}".format(
                       lib_out,
                       ','.join(host_args),
                       get_python_inc(), arch_flags)
    print("Compiling cuda extension, calling nvcc with arguments:")
    print([nvcc] + nvcc_command.split(' '))
    subprocess.run([nvcc] + nvcc_command.split(' '), check=True)
    return 'build', '_cext_gpu'

def run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True, test_catboost=True,
              test_spark=True, test_pyod=True, with_cuda=True):
    ext_modules = []
    if with_binary:
        compile_args = []
        if sys.platform == 'zos':
            compile_args.append('-qlonglong')
        if sys.platform == 'win32':
            compile_args.append('/MD')

        ext_modules.append(
            Extension('shap._cext', sources=['shap/cext/_cext.cc'],
                      extra_compile_args=compile_args))
    if with_cuda:
        try:
            cuda_home, nvcc = get_cuda_path()
            if sys.platform == 'win32':
                cudart_path = cuda_home + '/lib/x64'
            else:
                cudart_path = cuda_home + '/lib64'
                compile_args.append('-fPIC')

            lib_dir, lib = compile_cuda_module(compile_args)

            ext_modules.append(
                Extension('shap._cext_gpu', sources=['shap/cext/_cext_gpu.cc'],
                          extra_compile_args=compile_args,
                          library_dirs=[lib_dir, cudart_path],
                          libraries=[lib, 'cudart'],
                          depends=['shap/cext/_cext_gpu.cu', 'shap/cext/gpu_treeshap.h','setup.py'])
            )
        except Exception as e:
            raise Exception("Error building cuda module: " + repr(e))

    tests_require = ['pytest', 'pytest-mpl', 'pytest-cov']
    if test_xgboost:
        tests_require += ['xgboost']
    if test_lightgbm:
        tests_require += ['lightgbm']
    if test_catboost:
        tests_require += ['catboost']
    if test_spark:
        tests_require += ['pyspark']
    if test_pyod:
        tests_require += ['pyod']

    extras_require = {
        'plots': [
            'matplotlib',
            'ipython'
        ],
        'others': [
            'lime',
        ],
        'docs': [
            'matplotlib',
            'ipython',
            'numpydoc',
            'sphinx_rtd_theme',
            'sphinx',
            'nbsphinx',
        ]
    }
    extras_require['test'] = tests_require
    extras_require['all'] = list(set(i for val in extras_require.values() for i in val))

    setup(
        name='shap',
        version=find_version("shap", "__init__.py"),
        description='A unified approach to explain the output of any machine learning model.',
        long_description="SHAP (SHapley Additive exPlanations) is a unified approach to explain "
                         "the output of " + \
                         "any machine learning model. SHAP connects game theory with local "
                         "explanations, uniting " + \
                         "several previous methods and representing the only possible consistent "
                         "and locally accurate " + \
                         "additive feature attribution method based on expectations.",
        long_description_content_type="text/markdown",
        url='http://github.com/slundberg/shap',
        author='Scott Lundberg',
        author_email='slund1@cs.washington.edu',
        license='MIT',
        packages=[
            'shap', 'shap.explainers', 'shap.explainers.other', 'shap.explainers._deep',
            'shap.plots', 'shap.plots.colors', 'shap.benchmark', 'shap.maskers', 'shap.utils',
            'shap.actions', 'shap.models'
        ],
        package_data={'shap': ['plots/resources/*', 'cext/tree_shap.h']},
        cmdclass={'build_ext': build_ext},
        setup_requires=['numpy'],
        install_requires=['numpy', 'scipy', 'scikit-learn', 'pandas', 'tqdm>4.25.0',
                          'slicer==0.0.7', 'numba', 'cloudpickle'],
        extras_require=extras_require,
        ext_modules=ext_modules,
        classifiers=[
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.6',
        ],
        zip_safe=False
        # python_requires='>3.0' we will add this at some point
    )

def try_run_setup(**kwargs):
    """ Fails gracefully when various install steps don't work.
    """

    try:
        run_setup(**kwargs)
    except Exception as e:
        print(str(e))
        if "xgboost" in str(e).lower():
            kwargs["test_xgboost"] = False
            print("Couldn't install XGBoost for testing!")
            try_run_setup(**kwargs)
        elif "lightgbm" in str(e).lower():
            kwargs["test_lightgbm"] = False
            print("Couldn't install LightGBM for testing!")
            try_run_setup(**kwargs)
        elif "catboost" in str(e).lower():
            kwargs["test_catboost"] = False
            print("Couldn't install CatBoost for testing!")
            try_run_setup(**kwargs)
        elif "cuda" in str(e).lower():
            kwargs["with_cuda"] = False
            print(
                "WARNING: Could not compile cuda extensions")
            try_run_setup(**kwargs)
        elif kwargs["with_binary"]:
            kwargs["with_binary"] = False
            print(
                "WARNING: The C extension could not be compiled, sklearn tree models not "
                "supported.")
            try_run_setup(**kwargs)
        elif "pyod" in str(e).lower():
            kwargs["test_pyod"] = False
            print("Couldn't install PyOD for testing!")
            try_run_setup(**kwargs)
        else:
            print("ERROR: Failed to build!")

# we seem to need this import guard for appveyor
if __name__ == "__main__":
    try_run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True, test_spark=True,
                  test_pyod=True, with_cuda=True)
<|endoftext|>


<commit_before>from setuptools import setup, find_packages

__version__ = '0.17.0'

setup(
    name="Flask-REST-JSONAPI",
    version=__version__,
    description='Flask extension to create REST web api according to JSONAPI 1.0 specification with Flask, Marshmallow \
                 and data provider of your choice (SQLAlchemy, MongoDB, ...)',
    url='https://github.com/miLibris/flask-rest-jsonapi',
    author='miLibris API Team',
    author_email='pf@milibris.net',
    license='MIT',
    classifiers=[
        'Framework :: Flask',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'License :: OSI Approved :: MIT License',
    ],
    keywords='web api rest jsonapi flask sqlalchemy marshmallow',
    packages=find_packages(exclude=['tests']),
    zip_safe=False,
    platforms='any',
    install_requires=['six',
                      'Flask>=0.11',
                      'marshmallow==2.13.1',
                      'marshmallow_jsonapi',
                      'sqlalchemy'],
    setup_requires=['pytest-runner'],
    tests_require=['pytest'],
    extras_require={'tests': 'pytest', 'docs': 'sphinx'}
)
<commit_msg>Bump version to 0.17.1<commit_after>from setuptools import setup, find_packages

__version__ = '0.17.1'

setup(
    name="Flask-REST-JSONAPI",
    version=__version__,
    description='Flask extension to create REST web api according to JSONAPI 1.0 specification with Flask, Marshmallow \
                 and data provider of your choice (SQLAlchemy, MongoDB, ...)',
    url='https://github.com/miLibris/flask-rest-jsonapi',
    author='miLibris API Team',
    author_email='pf@milibris.net',
    license='MIT',
    classifiers=[
        'Framework :: Flask',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'License :: OSI Approved :: MIT License',
    ],
    keywords='web api rest jsonapi flask sqlalchemy marshmallow',
    packages=find_packages(exclude=['tests']),
    zip_safe=False,
    platforms='any',
    install_requires=['six',
                      'Flask>=0.11',
                      'marshmallow==2.13.1',
                      'marshmallow_jsonapi',
                      'sqlalchemy'],
    setup_requires=['pytest-runner'],
    tests_require=['pytest'],
    extras_require={'tests': 'pytest', 'docs': 'sphinx'}
)
<|endoftext|>


<commit_before>from setuptools import setup
from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements('requirements.txt', session=False)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    name='atmos',
    packages=['atmos'],
    version='0.2.4',
    description='Atmospheric sciences utility library',
    author='Jeremy McGibbon',
    author_email='mcgibbon@uw.edu',
    install_requires=reqs,
    url='https://github.com/mcgibbon/atmos',
    keywords=['atmos', 'atmospheric', 'equations', 'geoscience', 'science'],
    classifiers=[],
    license='MIT',
)
<commit_msg>updated setup.py version to develop<commit_after>from setuptools import setup
from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements('requirements.txt', session=False)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    name='atmos',
    packages=['atmos'],
    version='0.2.5-develop',
    description='Atmospheric sciences utility library',
    author='Jeremy McGibbon',
    author_email='mcgibbon@uw.edu',
    install_requires=reqs,
    url='https://github.com/mcgibbon/atmos',
    keywords=['atmos', 'atmospheric', 'equations', 'geoscience', 'science'],
    classifiers=[],
    license='MIT',
)
<|endoftext|>


<commit_before>import codecs
import os
import sys
import unittest

from setuptools import setup, find_packages
from setuptools.command.install import install

VERSION = "1.28.13"
AUTHOR = "Free Law Project"
EMAIL = "info@free.law"
HERE = os.path.abspath(os.path.dirname(__file__))

reqs_path = HERE + "/requirements.txt"
with open(reqs_path) as reqs_file:
    reqs = reqs_file.read().splitlines()

def read(*parts):
    """
    Build an absolute path from *parts* and and return the contents of the
    resulting file.  Assume UTF-8 encoding.
    """
    with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
        return f.read()

class TestNetwork(install):
    """Run network test only"""

    description = "run isolated tests that hit the network"

    def run(self):
        loader = unittest.defaultTestLoader
        runner = unittest.TextTestRunner(verbosity=2)
        tests = loader.discover("./tests/network")
        runner.run(tests)

class VerifyVersion(install):
    """Custom command to verify that the git tag matches our version"""

    description = "verify that the git tag matches our version"

    def run(self):
        tag = os.getenv("CIRCLE_TAG")

        if tag is None:
            sys.exit(
                "The 'verify' option is only available in tagged CircleCI container"
            )

        if tag != VERSION:
            message = (
                "Git tag: {0} does not match the version of this app: {1}"
            )
            sys.exit(message.format(tag, VERSION))

setup(
    name="juriscraper",
    description="An API to scrape American court websites for metadata.",
    license="BSD",
    url="https://github.com/freelawproject/juriscraper",
    version=VERSION,
    author=AUTHOR,
    author_email=EMAIL,
    maintainer=AUTHOR,
    maintainer_email=EMAIL,
    keywords=["scraping", "legal", "pacer"],
    long_description=read("README.rst"),
    long_description_content_type="text/markdown",
    packages=find_packages(exclude=["tests*"]),
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Natural Language :: English",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
    install_requires=reqs,
    tests_require=["jsondate3-aware", "mock", "vcrpy"],
    include_package_data=True,
    test_suite="tests.test_local",
    cmdclass={"verify": VerifyVersion, "testnetwork": TestNetwork,},
)
<commit_msg>Version bump<commit_after>import codecs
import os
import sys
import unittest

from setuptools import setup, find_packages
from setuptools.command.install import install

VERSION = "1.28.14"
AUTHOR = "Free Law Project"
EMAIL = "info@free.law"
HERE = os.path.abspath(os.path.dirname(__file__))

reqs_path = HERE + "/requirements.txt"
with open(reqs_path) as reqs_file:
    reqs = reqs_file.read().splitlines()

def read(*parts):
    """
    Build an absolute path from *parts* and and return the contents of the
    resulting file.  Assume UTF-8 encoding.
    """
    with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
        return f.read()

class TestNetwork(install):
    """Run network test only"""

    description = "run isolated tests that hit the network"

    def run(self):
        loader = unittest.defaultTestLoader
        runner = unittest.TextTestRunner(verbosity=2)
        tests = loader.discover("./tests/network")
        runner.run(tests)

class VerifyVersion(install):
    """Custom command to verify that the git tag matches our version"""

    description = "verify that the git tag matches our version"

    def run(self):
        tag = os.getenv("CIRCLE_TAG")

        if tag is None:
            sys.exit(
                "The 'verify' option is only available in tagged CircleCI container"
            )

        if tag != VERSION:
            message = (
                "Git tag: {0} does not match the version of this app: {1}"
            )
            sys.exit(message.format(tag, VERSION))

setup(
    name="juriscraper",
    description="An API to scrape American court websites for metadata.",
    license="BSD",
    url="https://github.com/freelawproject/juriscraper",
    version=VERSION,
    author=AUTHOR,
    author_email=EMAIL,
    maintainer=AUTHOR,
    maintainer_email=EMAIL,
    keywords=["scraping", "legal", "pacer"],
    long_description=read("README.rst"),
    long_description_content_type="text/markdown",
    packages=find_packages(exclude=["tests*"]),
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Natural Language :: English",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
    install_requires=reqs,
    tests_require=["jsondate3-aware", "mock", "vcrpy"],
    include_package_data=True,
    test_suite="tests.test_local",
    cmdclass={"verify": VerifyVersion, "testnetwork": TestNetwork,},
)
<|endoftext|>


<commit_before>"""Distutils file for MPipe."""

from distutils.core import setup, Command
import inspect
import shutil
import os

class Clean2(Command):
    """A more thorough clean command."""
    description = 'clean everything generated by the build command'
    user_options = []
    def initialize_options(self):
        pass
    def finalize_options(self):
        pass
    def run(self):
        to_remove = (
            'build',
            'dist',
            'MANIFEST',
            )
        this_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
        this_dir = os.path.normpath(this_dir)
        for entry in os.listdir(this_dir):
            if entry not in to_remove:
                continue
            entry = os.path.join(this_dir, entry)
            print('erasing', entry)
            if os.path.isfile(entry):
                os.remove(entry)
            elif os.path.isdir(entry):
                shutil.rmtree(entry)

from src.mpipe import __version__ as version

setup(
    name         = 'mpipe',
    version      = version,
    description  = 'A multiprocess pipeline software framework.',
    url          = 'http://vmlaker.github.io/mpipe',
    author       = 'Velimir Mlaker',
    author_email = 'velimir.mlaker@gmail.com',
    license      = 'MIT',
    long_description = open('README.md').read(),
    package_dir  = {'' : 'src'},
    py_modules   = ['mpipe'],
    cmdclass     = { 'clean2' : Clean2 },
    classifiers  = [
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: Freeware',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Libraries :: Python Modules',
        ],
    )
<commit_msg>Add test command.<commit_after>"""Distutils file for MPipe."""

from distutils.core import setup, Command
import subprocess
import inspect
import shutil
import os
import sys

class Clean2(Command):
    """A more thorough clean command."""
    description = 'clean everything generated by the build command'
    user_options = []
    def initialize_options(self): pass  # Must override.
    def finalize_options(self): pass  # Must override.
    def run(self):
        to_remove = ('build','dist','MANIFEST',)
        this_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
        this_dir = os.path.normpath(this_dir)
        for entry in os.listdir(this_dir):
            if entry not in to_remove:
                continue
            entry = os.path.join(this_dir, entry)
            print('erasing %s'%entry)
            if os.path.isfile(entry):
                os.remove(entry)
            elif os.path.isdir(entry):
                shutil.rmtree(entry)

class Test(Command):
    """A custom test command."""
    description = 'run custom test suite'
    user_options = []
    def initialize_options(self): pass  # Must override.
    def finalize_options(self): pass  # Must override.
    def run(self):
        this_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
        this_dir = os.path.normpath(this_dir)
        args = os.path.join(this_dir, 'test', 'test.py')
        command = '%s %s'%(sys.executable, args)
        print(command)
        subprocess.call(command, shell=True)

from src.mpipe import __version__ as version

setup(
    name         = 'mpipe',
    version      = version,
    description  = 'A multiprocess pipeline software framework.',
    url          = 'http://vmlaker.github.io/mpipe',
    author       = 'Velimir Mlaker',
    author_email = 'velimir.mlaker@gmail.com',
    license      = 'MIT',
    long_description = open('README.md').read(),
    package_dir  = {'' : 'src'},
    py_modules   = ['mpipe'],
    cmdclass     = { 'clean2' : Clean2, 'test' : Test, },
    classifiers  = [
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: Freeware',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Libraries :: Python Modules',
        ],
    )
<|endoftext|>


<commit_before>from __future__ import division
import sys
from itertools import groupby
from operator import itemgetter
from collections import defaultdict
import ninemlcatalog
import numpy as np
from nineml import units as un, Property
import pyNN.neuron
import pype9.neuron
import argparse
import logging
from matplotlib import pyplot as plt
argv = sys.argv[1:]  # Save argv before it is clobbered by the NEST init.
import nest  # @IgnorePep8
import pyNN.nest  # @IgnorePep8
import pype9.nest  # @IgnorePep8

pyNN_logger = logging.Logger('PyNN')

parser = argparse.ArgumentParser()
parser.add_argument('--cases', type=str, nargs='+',
                    default=['AI', 'SIFast', 'SISlow', 'SR'],
                    help="Which Brunel version(s) to run")
parser.add_argument('--order', type=int, default=10,
                    help="The scale of the network (full network order=1000)")
parser.add_argument('--simtime', type=float, default=100.0,
                    help="The length of the simulation in ms")
parser.add_argument('--timestep', type=float, default=0.001,
                    help="Simulation timestep")
parser.add_argument('--simulators', type=str, nargs='+',
                    default=['neuron', 'nest'],
                    help="Which simulators to simulate the 9ML network")
parser.add_argument('--record_v', action='store_true', default=False,
                    help=("Whether to record and plot the voltages"))
parser.add_argument('--plot_start', type=float, default=0.0,
                    help=("The time to start plotting from"))
parser.add_argument('--build_mode', type=str, default='force',
                    help="The build mode with which to construct the "
                    "network")
parser.add_argument('--option', nargs=2, type=str, action='append',
                    default=[],
                    help="Extra options that are passed to the test")
parser.add_argument('--seed', type=int, default=None,
                    help="Random seed passed to the simulators")
parser.add_argument('--reference', action='store_true', default=False,
                    help="Plot a reference NEST implementation alongside")
args = parser.parse_args(argv)

# Construct reference NEST network
def construct_reference(case, order):
    """
    The model has been adapted from the brunel-alpha-nest.py
    model that is part of NEST.

    Copyright (C) 2004 The NEST Initiative

    NEST is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    NEST is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NEST.  If not, see <http://www.gnu.org/licenses/>.
    This version uses NEST's Connect functions.
    """

    # Parameters used to construct the reference network
    delay = 1.5 * un.ms

    # Initialize the parameters of the integrate and fire neuron
    theta = 20.0
    J = 0.1  # postsynaptic amplitude in mV
    tauSyn = 0.1
    tauMem = 20.0
    CMem = 250.0

    epsilon = 0.1  # connection probability

    brunel_parameters = {
        "SR": {"g": 3.0, "eta": 2.0},
        "AI": {"g": 5.0, "eta": 2.0},
        "SIfast": {"g": 6.0, "eta": 4.0},
        "SIslow": {"g": 4.5, "eta": 0.9}}

    # Parameters for asynchronous irregular firing
    g = brunel_parameters[case]["g"]
    eta = brunel_parameters[case]["eta"]

    NE = 4 * order
    NI = 1 * order

    CE = int(epsilon * NE)  # number of excitatory synapses per neuron
    CI = int(epsilon * NI)  # number of inhibitory synapses per neuron
    if not CE:
        CE = 1

    def compute_normalised_psr(tauMem, CMem, tauSyn):
        """Compute the maximum of postsynaptic potential
           for a synaptic input current of unit amplitude
           (1 pA)
        """

        a = (tauMem / tauSyn)
        b = (1.0 / tauSyn - 1.0 / tauMem)

        # time of maximum
        t_max = 1.0 / b * \
            (-nest.sli_func('LambertWm1', -np.exp(-1.0 / a) / a) - 1.0 / a)

        # maximum of PSP for current of unit amplitude
        return (np.exp(1.0) / (tauSyn * CMem * b) *
                ((np.exp(-t_max / tauMem) -
                  np.exp(-t_max / tauSyn)) / b - t_max *
                 np.exp(-t_max / tauSyn)))

    # normalize synaptic current so that amplitude of a PSP is J
    J_unit = compute_normalised_psr(tauMem, CMem, tauSyn)
    J_ex = J / J_unit
    J_in = -g * J_ex

    # threshold rate, equivalent rate of events needed to
    # have mean input current equal to threshold
    nu_th = ((theta * CMem) /
             (J_ex * CE * np.exp(1) * tauMem * tauSyn))
    nu_ex = eta * nu_th
    p_rate = 1000.0 * nu_ex * CE

    neuron_params = {"C_m": CMem,
                     "tau_m": tauMem,
                     "tau_syn_ex": tauSyn,
                     "tau_syn_in": tauSyn,
                     "t_ref": 2.0,
                     "E_L": 0.0,
                     "V_reset": 0.0,
                     "V_m": 0.0,
                     "V_th": theta}

    nest.SetDefaults("iaf_psc_alpha", neuron_params)
    nodes_exc = nest.Create("iaf_psc_alpha", NE)
    nodes_inh = nest.Create("iaf_psc_alpha", NI)

    nest.SetStatus(nodes_exc + nodes_inh, 'V_m',
                   list(np.random.rand(NE + NI) * 20.0))

    nest.SetDefaults("poisson_generator", {"rate": p_rate})
    noise = nest.Create("poisson_generator")
    nodes_ext = nest.Create('parrot_neuron', NE + NI)
    nest.Connect(noise, nodes_ext)

    all_nodes = {'Exc': nodes_exc, 'Inh': nodes_inh, 'Ext': nodes_ext}

    # Set up connections

    nest.CopyModel(
        "static_synapse", "excitatory", {
            "weight": J_ex, "delay": float(delay.value)})
    nest.CopyModel(
        "static_synapse", "inhibitory", {
            "weight": J_in, "delay": float(delay.value)})

    nest.Connect(nodes_ext, nodes_exc + nodes_inh, 'one_to_one',
                 "excitatory")

    # We now iterate over all neuron IDs, and connect the neuron to the
    # sources from our array. The first loop connects the excitatory
    # neurons and the second loop the inhibitory neurons.
    conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE}
    nest.Connect(
        nodes_exc,
        nodes_exc +
        nodes_inh,
        conn_params_ex,
        "excitatory")

    conn_params_in = {'rule': 'fixed_indegree', 'indegree': CI}
    nest.Connect(
        nodes_inh,
        nodes_exc +
        nodes_inh,
        conn_params_in,
        "inhibitory")
    return all_nodes

pyNN_states = {'nest': pyNN.nest.simulator.state,
               'neuron': pyNN.neuron.simulator.state}
pyNN_setup = {'nest': pyNN.nest.setup, 'neuron': pyNN.neuron.setup}
pype9_network_classes = {'nest': pype9.nest.Network,
                         'neuron': pype9.neuron.Network}
# Set up recorders for 9ML network
rates = {}
psth = {}

# Set the random seed
np.random.seed(args.seed)
seeds = np.asarray(
    np.floor(np.random.random(len(args.simulators) * 1e5)), dtype=int)

# Loop through each Brunel case and scale the model according to the order
models = {}
for case in args.cases:
    model = ninemlcatalog.load(
        'network/Brunel2000/' + case).as_network('Brunel_{}'.format(case))
    # Rescale loaded populations to requested order
    if args.order != 1000:
        for pop in model.populations:
            pop.size = int(np.ceil((pop.size / 1000) * args.order))
        for proj in (model.projection('Excitation'),
                     model.projection('Inhibition')):
            props = proj.connectivity.rule_properties
            number = props.property('number')
            props.set(Property(
                number.name,
                (int(np.ceil((number.value / 1000) * args.order)) *
                 un.unitless)))
    models[case] = model

# Create dictionaries to hold the simulation results
spikes = defaultdict(defaultdict(dict))
if args.record_v:
    vs = defaultdict(defaultdict(dict))
ref_recorders = {}

# Create the network and run the simulations for each simulator
for simulator, seed in zip(args.simulators, seeds):
    # Reset the simulator
    pyNN_setup[simulator](timestep=args.timestep, rng_seeds_seed=seed)
    for case, model in models.iteritems():
        # Construct the network
        network = pype9_network_classes[simulator](model)
        # Record spikes and voltages
        for pop in network.component_arrays:
            pop.record('spikes')
            if args.record_v and pop.name != 'Ext':
                pop.record('v__cell')
        if args.reference and simulator == 'nest':
            ref_recorders[case] = construct_reference(case, args.order)
        # Run the simulation
        pyNN_states[simulator].run(args.simtime)
        # Plot the results of the simulation
        for pop in network.component_arrays:
            block = pop.get_data()
            segment = block.segments[0]
            spikes[case][pop.name][simulator] = segment.spiketrains
            if args.record_v:
                vs[case][pop.name][simulator] = segment.analogsignalarrays

# Plot the results
for case in args.cases:
    for pop_name in network.component_array_names:
        spike_fig = plt.figure()
        plt.xlabel('Times (ms)')
        plt.ylabel('Cell Indices')
        plt.title("{} - {} Spikes".format(case, pop.name))
        if args.record_v:
            v_fig = plt.figure()
            plt.xlabel('Time (ms)')
            plt.ylabel('Membrane Voltage (mV)')
            plt.title("{} - {} Membrane Voltage".format(case, pop.name))
        for simulator in args.simulators:
            spiketrains = spikes[case][pop_name][simulator]
            spike_times = []
            ids = []
            for i, spiketrain in enumerate(spiketrains):
                spike_times.extend(spiketrain)
                ids.extend([i] * len(spiketrain))
            plt.scatter(spike_times, ids)
            if args.record_v and pop_name != 'Ext':
                traces = vs[case][pop_name][simulator]
                legend = []
                for trace in traces:
                    plt.plot(trace.times, trace)
                    legend.append(trace.name)
                plt.legend(legend)
        if args.reference:
            for pop_name in network.component_array_names:
                events = nest.GetStatus(ref_recorders[pop_name]['spikes'],
                                        "events")[0]
                spike_times = np.asarray(events['times'])
                senders = np.asarray(events['senders'])
                inds = np.asarray(spike_times > args.plot_start, dtype=bool)
                spike_times = spike_times[inds]
                senders = senders[inds]
                plt.scatter(spike_times, senders)
                if args.record_v:
                    events, interval = nest.GetStatus(
                        ref_recorders[pop_name]['v'],
                        ["events", 'interval'])[0]
                    sorted_vs = sorted(zip(events['senders'],
                                           events['times'],
                                           events['v']),
                                       key=itemgetter(0))
                    legend = []
                    for sender, group in groupby(sorted_vs,
                                                 key=itemgetter(0)):
                        _, t, v = zip(*group)
                        t = np.asarray(t)
                        v = np.asarray(v)
                        inds = t > args.plot_start
                        plt.plot(t[inds] * interval, v[inds])
                        legend.append(sender)
                    plt.legend(legend)
<commit_msg>getting brunel model to work<commit_after>from __future__ import division
import sys
from itertools import groupby
from operator import itemgetter
from collections import defaultdict
import ninemlcatalog
import numpy as np
from nineml import units as un, Property
import pyNN.neuron
import pype9.neuron
import argparse
import logging
from matplotlib import pyplot as plt
argv = sys.argv[1:]  # Save argv before it is clobbered by the NEST init.
import nest  # @IgnorePep8
import pyNN.nest  # @IgnorePep8
import pype9.nest  # @IgnorePep8

pyNN_logger = logging.Logger('PyNN')

parser = argparse.ArgumentParser()
parser.add_argument('--cases', type=str, nargs='+',
                    default=['AI', 'SIFast', 'SISlow', 'SR'],
                    help="Which Brunel version(s) to run")
parser.add_argument('--order', type=int, default=10,
                    help="The scale of the network (full network order=1000)")
parser.add_argument('--simtime', type=float, default=100.0,
                    help="The length of the simulation in ms")
parser.add_argument('--timestep', type=float, default=0.001,
                    help="Simulation timestep")
parser.add_argument('--simulators', type=str, nargs='+',
                    default=['neuron', 'nest'],
                    help="Which simulators to simulate the 9ML network")
parser.add_argument('--record_v', action='store_true', default=False,
                    help=("Whether to record and plot the voltages"))
parser.add_argument('--plot_start', type=float, default=0.0,
                    help=("The time to start plotting from"))
parser.add_argument('--build_mode', type=str, default='force',
                    help="The build mode with which to construct the "
                    "network")
parser.add_argument('--option', nargs=2, type=str, action='append',
                    default=[],
                    help="Extra options that are passed to the test")
parser.add_argument('--seed', type=int, default=None,
                    help="Random seed passed to the simulators")
parser.add_argument('--reference', action='store_true', default=False,
                    help="Plot a reference NEST implementation alongside")
args = parser.parse_args(argv)

# Construct reference NEST network
def construct_reference(case, order):
    """
    The model has been adapted from the brunel-alpha-nest.py
    model that is part of NEST.

    Copyright (C) 2004 The NEST Initiative

    NEST is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    NEST is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NEST.  If not, see <http://www.gnu.org/licenses/>.
    This version uses NEST's Connect functions.
    """

    # Parameters used to construct the reference network
    delay = 1.5 * un.ms

    # Initialize the parameters of the integrate and fire neuron
    theta = 20.0
    J = 0.1  # postsynaptic amplitude in mV
    tauSyn = 0.1
    tauMem = 20.0
    CMem = 250.0

    epsilon = 0.1  # connection probability

    brunel_parameters = {
        "SR": {"g": 3.0, "eta": 2.0},
        "AI": {"g": 5.0, "eta": 2.0},
        "SIfast": {"g": 6.0, "eta": 4.0},
        "SIslow": {"g": 4.5, "eta": 0.9}}

    # Parameters for asynchronous irregular firing
    g = brunel_parameters[case]["g"]
    eta = brunel_parameters[case]["eta"]

    NE = 4 * order
    NI = 1 * order

    CE = int(epsilon * NE)  # number of excitatory synapses per neuron
    CI = int(epsilon * NI)  # number of inhibitory synapses per neuron
    if not CE:
        CE = 1

    def compute_normalised_psr(tauMem, CMem, tauSyn):
        """Compute the maximum of postsynaptic potential
           for a synaptic input current of unit amplitude
           (1 pA)
        """

        a = (tauMem / tauSyn)
        b = (1.0 / tauSyn - 1.0 / tauMem)

        # time of maximum
        t_max = 1.0 / b * \
            (-nest.sli_func('LambertWm1', -np.exp(-1.0 / a) / a) - 1.0 / a)

        # maximum of PSP for current of unit amplitude
        return (np.exp(1.0) / (tauSyn * CMem * b) *
                ((np.exp(-t_max / tauMem) -
                  np.exp(-t_max / tauSyn)) / b - t_max *
                 np.exp(-t_max / tauSyn)))

    # normalize synaptic current so that amplitude of a PSP is J
    J_unit = compute_normalised_psr(tauMem, CMem, tauSyn)
    J_ex = J / J_unit
    J_in = -g * J_ex

    # threshold rate, equivalent rate of events needed to
    # have mean input current equal to threshold
    nu_th = ((theta * CMem) /
             (J_ex * CE * np.exp(1) * tauMem * tauSyn))
    nu_ex = eta * nu_th
    p_rate = 1000.0 * nu_ex * CE

    neuron_params = {"C_m": CMem,
                     "tau_m": tauMem,
                     "tau_syn_ex": tauSyn,
                     "tau_syn_in": tauSyn,
                     "t_ref": 2.0,
                     "E_L": 0.0,
                     "V_reset": 0.0,
                     "V_m": 0.0,
                     "V_th": theta}

    nest.SetDefaults("iaf_psc_alpha", neuron_params)
    nodes_exc = nest.Create("iaf_psc_alpha", NE)
    nodes_inh = nest.Create("iaf_psc_alpha", NI)

    nest.SetStatus(nodes_exc + nodes_inh, 'V_m',
                   list(np.random.rand(NE + NI) * 20.0))

    nest.SetDefaults("poisson_generator", {"rate": p_rate})
    noise = nest.Create("poisson_generator")
    nodes_ext = nest.Create('parrot_neuron', NE + NI)
    nest.Connect(noise, nodes_ext)

    all_nodes = {'Exc': nodes_exc, 'Inh': nodes_inh, 'Ext': nodes_ext}

    # Set up connections

    nest.CopyModel(
        "static_synapse", "excitatory", {
            "weight": J_ex, "delay": float(delay.value)})
    nest.CopyModel(
        "static_synapse", "inhibitory", {
            "weight": J_in, "delay": float(delay.value)})

    nest.Connect(nodes_ext, nodes_exc + nodes_inh, 'one_to_one',
                 "excitatory")

    # We now iterate over all neuron IDs, and connect the neuron to the
    # sources from our array. The first loop connects the excitatory
    # neurons and the second loop the inhibitory neurons.
    conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE}
    nest.Connect(
        nodes_exc,
        nodes_exc +
        nodes_inh,
        conn_params_ex,
        "excitatory")

    conn_params_in = {'rule': 'fixed_indegree', 'indegree': CI}
    nest.Connect(
        nodes_inh,
        nodes_exc +
        nodes_inh,
        conn_params_in,
        "inhibitory")

    for pop_name in record_pops:
        pop = np.asarray(pops[model_ver][pop_name], dtype=int)
        record_inds = np.asarray(np.unique(np.floor(
            np.arange(start=0, stop=len(pop),
                         step=len(pop) / record_size))), dtype=int)
        spikes[model_ver][pop_name] = nest.Create("spike_detector")
        nest.SetStatus(spikes[model_ver][pop_name],
                       [{"label": "brunel-py-" + pop_name,
                         "withtime": True, "withgid": True}])
        nest.Connect(list(pop[record_inds]),
                     spikes[model_ver][pop_name],
                     syn_spec="excitatory")
        if record_states:
            # Set up voltage traces recorders for reference network
            if self.record_params[pop_name][model_ver]:
                multi[model_ver][pop_name] = nest.Create(
                    'multimeter',
                    params={'record_from':
                            self.record_params[pop_name][model_ver]})
                nest.Connect(multi[model_ver][pop_name],
                             list(pop[record_inds]))

    return all_nodes

pyNN_states = {'nest': pyNN.nest.simulator.state,
               'neuron': pyNN.neuron.simulator.state}
pyNN_setup = {'nest': pyNN.nest.setup, 'neuron': pyNN.neuron.setup}
pype9_network_classes = {'nest': pype9.nest.Network,
                         'neuron': pype9.neuron.Network}
# Set up recorders for 9ML network
rates = {}
psth = {}

# Set the random seed
np.random.seed(args.seed)
seeds = np.asarray(
    np.floor(np.random.random(len(args.simulators) * 1e5)), dtype=int)

# Loop through each Brunel case and scale the model according to the order
models = {}
for case in args.cases:
    model = ninemlcatalog.load(
        'network/Brunel2000/' + case).as_network('Brunel_{}'.format(case))
    # Rescale loaded populations to requested order
    if args.order != 1000:
        for pop in model.populations:
            pop.size = int(np.ceil((pop.size / 1000) * args.order))
        for proj in (model.projection('Excitation'),
                     model.projection('Inhibition')):
            props = proj.connectivity.rule_properties
            number = props.property('number')
            props.set(Property(
                number.name,
                (int(np.ceil((number.value / 1000) * args.order)) *
                 un.unitless)))
    models[case] = model

# Create dictionaries to hold the simulation results
spikes = defaultdict(lambda: defaultdict(dict))
if args.record_v:
    vs = defaultdict(lambda: defaultdict(dict))
ref_recorders = {}

# Create the network and run the simulations for each simulator
for simulator, seed in zip(args.simulators, seeds):
    # Reset the simulator
    pyNN_setup[simulator](timestep=args.timestep, rng_seeds_seed=seed)
    for case, model in models.iteritems():
        # Construct the network
        network = pype9_network_classes[simulator](model)
        # Record spikes and voltages
        for pop in network.component_arrays:
            pop.record('spikes')
            if args.record_v and pop.name != 'Ext':
                pop.record('v__cell')
        if args.reference and simulator == 'nest':
            ref_recorders[case] = construct_reference(case, args.order)
        # Run the simulation
        pyNN_states[simulator].run(args.simtime)
        # Plot the results of the simulation
        for pop in network.component_arrays:
            block = pop.get_data()
            segment = block.segments[0]
            spikes[case][pop.name][simulator] = segment.spiketrains
            if args.record_v:
                vs[case][pop.name][simulator] = segment.analogsignalarrays

num_subplots = len(args.simulators) + int(args.reference)
num_rows = 2 if num_subplots > 1 else 1
num_cols = 2 if num_subplots > 2 else 1

# Plot the results
for case in args.cases:
    for pop_name in network.component_array_names:
        spike_fig = plt.figure()
        if args.record_v:
            v_fig = plt.figure()
        for sim_index, simulator in enumerate(args.simulators):
            spiketrains = spikes[case][pop_name][simulator]
            spike_times = []
            ids = []
            for i, spiketrain in enumerate(spiketrains):
                spike_times.extend(spiketrain)
                ids.extend([i] * len(spiketrain))
            spike_fig.add_subplot(num_rows, num_cols, sim_index)
            plt.scatter(spike_times, ids)
            plt.xlabel('Times (ms)')
            plt.ylabel('Cell Indices')
            plt.title("{} - PyPe9 {} - {} Spikes".format(
                case, simulator.upper(), pop.name))
            if args.record_v and pop_name != 'Ext':
                traces = vs[case][pop_name][simulator]
                legend = []
                v_fig.add_subplot(num_rows, num_cols, sim_index)
                for trace in traces:
                    plt.plot(trace.times, trace)
                    legend.append(trace.name)
                plt.xlabel('Time (ms)')
                plt.ylabel('Membrane Voltage (mV)')
                plt.title("{} - {} - {} Membrane Voltage".format(
                    case, simulator, pop.name))
                plt.legend(legend)
        if args.reference:
            for pop_name in network.component_array_names:
                events = nest.GetStatus(ref_recorders[pop_name]['spikes'],
                                        "events")[0]
                spike_times = np.asarray(events['times'])
                senders = np.asarray(events['senders'])
                inds = np.asarray(spike_times > args.plot_start, dtype=bool)
                spike_times = spike_times[inds]
                senders = senders[inds]
                spike_fig.add_subplot(num_rows, num_cols,
                                      len(args.simulators) + 1)
                plt.scatter(spike_times, senders)
                plt.xlabel('Times (ms)')
                plt.ylabel('Cell Indices')
                plt.title("{} - Reference NEST - {} Spikes".format(case,
                                                                   pop.name))
                if args.record_v:
                    events, interval = nest.GetStatus(
                        ref_recorders[pop_name]['v'],
                        ["events", 'interval'])[0]
                    sorted_vs = sorted(zip(events['senders'],
                                           events['times'],
                                           events['v']),
                                       key=itemgetter(0))
                    legend = []
                    for sender, group in groupby(sorted_vs,
                                                 key=itemgetter(0)):
                        _, t, v = zip(*group)
                        t = np.asarray(t)
                        v = np.asarray(v)
                        inds = t > args.plot_start
                        v_fig.add_subplot(num_rows, num_cols,
                                          len(args.simulators) + 1)
                        plt.plot(t[inds] * interval, v[inds])
                        legend.append(sender)
                    plt.xlabel('Time (ms)')
                    plt.ylabel('Membrane Voltage (mV)')
                    plt.title("{} - Reference NEST - {} Membrane Voltage"
                              .format(case, simulator, pop.name))
                    plt.legend(legend)
<|endoftext|>


<commit_before>#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.2',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0'])
<commit_msg>add shapely dependency<commit_after>#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.2',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely'])
<|endoftext|>


<commit_before>#!/usr/bin/env python
import os
import gnupg
from time import gmtime, strftime
import random
import requests
import json

def makeToken(gpghome, keyid):
    gpg = gnupg.GPG(gnupghome=gpghome)
    timestamp = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
    nonce = str(random.randint(10000, 18446744073709551616)) + \
            str(random.randint(10000, 18446744073709551616))
    sig = gpg.sign(timestamp + ";" + nonce + "\n",
        keyid=keyid,
        detach=True, clearsign=True)
    token = timestamp + ";" + nonce + ";"
    linectr=0
    for line in iter(str(sig).splitlines()):
        linectr+=1
        if linectr < 4 or line.startswith('-') or not line:
            continue
        token += line
    return token

if __name__ == '__main__':
    token = makeToken("/home/ulfr/.gnupg",
        "E60892BB9BD89A69F759A1A0A3D652173B763E8F")
    r = requests.get("http://localhost:12345/api/v1/dashboard",
        headers={'X-PGPAUTHORIZATION': token})
    print r.text

<commit_msg>[minor] update python example client to token v1<commit_after>#!/usr/bin/env python
import os
import gnupg
from time import gmtime, strftime
import random
import requests
import json

def makeToken(gpghome, keyid):
    gpg = gnupg.GPG(gnupghome=gpghome)
    version = "1"
    timestamp = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
    nonce = str(random.randint(10000, 18446744073709551616))
    token = version + ";" + timestamp + ";" + nonce
    sig = gpg.sign(token + "\n",
        keyid=keyid,
        detach=True, clearsign=True)
    token += ";"
    linectr=0
    for line in iter(str(sig).splitlines()):
        linectr+=1
        if linectr < 4 or line.startswith('-') or not line:
            continue
        token += line
    return token

if __name__ == '__main__':
    token = makeToken("/home/ulfr/.gnupg",
        "E60892BB9BD89A69F759A1A0A3D652173B763E8F")
    r = requests.get("http://localhost:12345/api/v1/dashboard",
        headers={'X-PGPAUTHORIZATION': token})
    print token
    print r.text

<|endoftext|>


<commit_before>from setuptools import setup, find_packages

version = '0.0'

setup(
    name='ckanext-glasgow',
    version=version,
    description="CKAN extension for the Glasgow Open Data Portal",
    long_description='''
    ''',
    classifiers=[],
    keywords='',
    author='',
    author_email='',
    url='http://data.glasgow.gov.uk',
    license='AGPL',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    namespace_packages=['ckanext', 'ckanext.glasgow'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        # -*- Extra requirements: -*-
    ],
    entry_points='''
        [ckan.plugins]
        # Add plugins here, e.g.
        glasgow_schema=ckanext.glasgow.plugins:GlasgowSchemaPlugin
	ec_intial_harvester=ckanext.glasgow.harvesters.ec_harvester:EcInitialHarvester
    ''',
)
<commit_msg>fix typo<commit_after>from setuptools import setup, find_packages

version = '0.0'

setup(
    name='ckanext-glasgow',
    version=version,
    description="CKAN extension for the Glasgow Open Data Portal",
    long_description='''
    ''',
    classifiers=[],
    keywords='',
    author='',
    author_email='',
    url='http://data.glasgow.gov.uk',
    license='AGPL',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    namespace_packages=['ckanext', 'ckanext.glasgow'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        # -*- Extra requirements: -*-
    ],
    entry_points='''
        [ckan.plugins]
        # Add plugins here, e.g.
        glasgow_schema=ckanext.glasgow.plugins:GlasgowSchemaPlugin
	ec_initial_harvester=ckanext.glasgow.harvesters.ec_harvester:EcInitialHarvester
    ''',
)
<|endoftext|>


<commit_before># Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
Generate a Flocker package that can be deployed onto cluster nodes.
"""

if __name__ == '__main__':
    from setup import main
    raise SystemExit(main())

from collections import namedtuple
import os
from setuptools import setup, find_packages
from distutils.core import Command
from unittest import TestCase
import versioneer
versioneer.vcs = "git"
versioneer.versionfile_source = "flocker/_version.py"
versioneer.versionfile_build = "flocker/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = "flocker-"

rpm_version = namedtuple('rpm_version', 'version release')

class MakeRpmVersionTests(TestCase):
    """
    Tests for ``make_rpm_version``.
    """
    def test_good(self):
        """
        ``make_rpm_version`` gives the expected ``rpm_version`` instances when
        supplied with valid ``flocker_version_number``s.
        """
        expected = {
            '0.1.0': rpm_version('0.1.0', '1'),
            '0.1.0-99-abc': rpm_version('0.1.0', '1.99.abc'),
            '0.1.1pre1': rpm_version('0.1.1', '0.1.pre'),
            '0.1.1': rpm_version('0.1.1', '1'),
            '0.2.0dev1': rpm_version('0.2.0', '0.1.dev'),
            '0.2.0dev2-99-xyz': rpm_version('0.2.0', '0.2.dev.99.xyz'),
            '0.2.0dev3-100-abc-dirty': rpm_version('0.2.0', '0.3.dev.100.abc.dirty'),
        }
        unexpected_results = []
        for supplied_version, expected_rpm_version in expected.items():
            actual_rpm_version = make_rpm_version(supplied_version)
            if actual_rpm_version != expected_rpm_version:
                unexpected_results.append((
                    supplied_version,
                    actual_rpm_version,
                    expected_rpm_version
                ))

        if unexpected_results:
            self.fail(unexpected_results)

    def test_non_integer_suffix(self):
        """
        ``make_rpm_version`` raises ``Exception`` when supplied with a version
        with a non-integer pre or dev suffix number.
        """
        with self.assertRaises(Exception) as exception:
            make_rpm_version('0.1.2preX')

        self.assertEqual(
            u'Non-integer value "X" for "pre". Supplied version 0.1.2preX',
            unicode(exception.exception)
        )

def make_rpm_version(flocker_version):
    """
    Parse the Flocker version generated by versioneer into an RPM compatible
    version and a release version.
    See: http://fedoraproject.org/wiki/Packaging:NamingGuidelines#Pre-Release_packages

    :param flocker_version: The versioneer style Flocker version string.
    :return: An ``rpm_version`` tuple containing a ``version`` and a
        ``release`` attribute.
    """
    # E.g. 0.1.2-69-gd2ff20c-dirty
    # tag+distance+shortid+dirty
    parts = flocker_version.split('-')
    tag, remainder = parts[0], parts[1:]
    for suffix in ('pre', 'dev'):
        parts = tag.rsplit(suffix, 1)
        if len(parts) == 2:
            # A pre or dev suffix was present. ``version`` is the part before
            # the pre and ``suffix_number`` is the part after the pre, but
            # before the first dash.
            version = parts.pop(0)
            suffix_number = parts[0]
            if suffix_number.isdigit():
                # Given pre or dev number X create a 0 prefixed, `.` separated
                # string of version labels. E.g.
                # 0.1.2pre2  becomes
                # 0.1.2-0.2.pre
                release = ['0', suffix_number, suffix]
            else:
                # Non-integer pre or dev number found.
                raise Exception(
                    'Non-integer value "{}" for "{}". '
                    'Supplied version {}'.format(
                        suffix_number, suffix, flocker_version))
            break
    else:
        # Neither of the expected suffixes was found, the tag can be used as
        # the RPM version
        version = tag
        release = ['1']

    if remainder:
        # The version may also contain a distance, shortid which
        # means that there have been changes since the last
        # tag. Additionally there may be a ``dirty`` suffix which
        # indicates that there are uncommitted changes in the
        # working directory.  We probably don't want to release
        # untagged RPM versions, and this branch should probably
        # trigger and error or a warning. But for now we'll add
        # that extra information to the end of release number.
        release.extend(remainder)

    return rpm_version(version, '.'.join(release))

class cmd_generate_spec(Command):
    description = "Generate python-flocker.spec with current version."
    user_options = []
    boolean_options = []
    def initialize_options(self):
        pass
    def finalize_options(self):
        pass
    def run(self):
        with open('python-flocker.spec.in', 'r') as source:
            spec = source.read()

        flocker_version = versioneer.get_version()
        version, release = make_rpm_version(flocker_version)
        with open('python-flocker.spec', 'w') as destination:
            destination.write(
                "%%global flocker_version %s\n" % (flocker_version,))
            destination.write(
                "%%global version %s\n" % (version,))
            destination.write(
                "%%global release %s\n" % (release,))
            destination.write(spec)

def main():
    cmdclass = {'generate_spec': cmd_generate_spec}
    # Let versioneer hook into the various distutils commands so it can rewrite
    # certain data at appropriate times.
    cmdclass.update(versioneer.get_cmdclass())

    # Hard linking doesn't work inside VirtualBox shared folders. This means that
    # you can't use tox in a directory that is being shared with Vagrant,
    # since tox relies on `python setup.py sdist` which uses hard links. As a
    # workaround, disable hard-linking if setup.py is a descendant of /vagrant.
    # See
    # https://stackoverflow.com/questions/7719380/python-setup-py-sdist-error-operation-not-permitted
    # for more details.
    if os.path.abspath(__file__).split(os.path.sep)[1] == 'vagrant':
        del os.link

    with open("README.rst") as readme:
        description = readme.read()

    setup(
        # This is the human-targetted name of the software being packaged.
        name="Flocker",
        # This is a string giving the version of the software being packaged.  For
        # simplicity it should be something boring like X.Y.Z.
        version=versioneer.get_version(),
        # This identifies the creators of this software.  This is left symbolic for
        # ease of maintenance.
        author="ClusterHQ Team",
        # This is contact information for the authors.
        author_email="support@clusterhq.com",
        # Here is a website where more information about the software is available.
        url="https://clusterhq.com/",

        # A short identifier for the license under which the project is released.
        license="Apache License, Version 2.0",

        # Some details about what Flocker is.  Synchronized with the README.rst to
        # keep it up to date more easily.
        long_description=description,

        # This setuptools helper will find everything that looks like a *Python*
        # package (in other words, things that can be imported) which are part of
        # the Flocker package.
        packages=find_packages(),

        package_data={
            'flocker.node.functional': ['sendbytes-docker/*', 'env-docker/*'],
        },

        entry_points = {
            # Command-line programs we want setuptools to install:
            'console_scripts': [
                'flocker-volume = flocker.volume.script:flocker_volume_main',
                'flocker-deploy = flocker.cli.script:flocker_deploy_main',
                'flocker-changestate = flocker.node.script:flocker_changestate_main',
                'flocker-reportstate = flocker.node.script:flocker_reportstate_main',
            ],
        },

        install_requires=[
            "eliot == 0.4.0",
            "zope.interface == 4.0.5",
            "pytz",
            "characteristic == 0.1.0",
            "Twisted == 14.0.0",

            "PyYAML == 3.10",

            "treq == 0.2.1",

            "netifaces >= 0.8",
            "ipaddr == 2.1.10",
            ],

        extras_require={
            # This extra allows you to build and check the documentation for
            # Flocker.
            "doc": [
                "Sphinx==1.2.2",
                "sphinx-rtd-theme==0.1.6",
                "pyenchant==1.6.6",
                "sphinxcontrib-spelling==2.1.1",
                ],
            # This extra is for developers who need to work on Flocker itself.
            "dev": [
                # flake8 is pretty critical to have around to help point out
                # obvious mistakes. It depends on PEP8, pyflakes and mccabe.
                "pyflakes==0.8.1",
                "pep8==1.5.7",
                "mccabe==0.2.1",
                "flake8==2.2.0",

                # Run the test suite:
                "tox==1.7.1",

                # versioneer is necessary in order to update (but *not* merely to
                # use) the automatic versioning tools.
                "versioneer==0.10",

                # Some of the tests use Conch:
                "PyCrypto==2.6.1",
                "pyasn1==0.1.7",

                # The test suite uses network namespaces
                "nomenclature >= 0.1.0",
                ],

            # This extra is for Flocker release engineers to set up their release
            # environment.
            "release": [
                "gsutil",
                "wheel",
                ],
            },

        cmdclass=cmdclass,

        # Some "trove classifiers" which are relevant.
        classifiers=[
            "License :: OSI Approved :: Apache Software License",
            ],
        )
<commit_msg>Move rpm version code to a _release module<commit_after># Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
Generate a Flocker package that can be deployed onto cluster nodes.
"""

import os
from setuptools import setup, find_packages

import versioneer
versioneer.vcs = "git"
versioneer.versionfile_source = "flocker/_version.py"
versioneer.versionfile_build = "flocker/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = "flocker-"

from distutils.core import Command

from flocker._release import make_rpm_version

class cmd_generate_spec(Command):
    description = "Generate python-flocker.spec with current version."
    user_options = []
    boolean_options = []
    def initialize_options(self):
        pass
    def finalize_options(self):
        pass
    def run(self):
        with open('python-flocker.spec.in', 'r') as source:
            spec = source.read()

        flocker_version = versioneer.get_version()
        version, release = make_rpm_version(flocker_version)
        with open('python-flocker.spec', 'w') as destination:
            destination.write(
                "%%global flocker_version %s\n" % (flocker_version,))
            destination.write(
                "%%global version %s\n" % (version,))
            destination.write(
                "%%global release %s\n" % (release,))
            destination.write(spec)

cmdclass = {'generate_spec': cmd_generate_spec}
# Let versioneer hook into the various distutils commands so it can rewrite
# certain data at appropriate times.
cmdclass.update(versioneer.get_cmdclass())

# Hard linking doesn't work inside VirtualBox shared folders. This means that
# you can't use tox in a directory that is being shared with Vagrant,
# since tox relies on `python setup.py sdist` which uses hard links. As a
# workaround, disable hard-linking if setup.py is a descendant of /vagrant.
# See
# https://stackoverflow.com/questions/7719380/python-setup-py-sdist-error-operation-not-permitted
# for more details.
if os.path.abspath(__file__).split(os.path.sep)[1] == 'vagrant':
    del os.link

with open("README.rst") as readme:
    description = readme.read()

setup(
    # This is the human-targetted name of the software being packaged.
    name="Flocker",
    # This is a string giving the version of the software being packaged.  For
    # simplicity it should be something boring like X.Y.Z.
    version=versioneer.get_version(),
    # This identifies the creators of this software.  This is left symbolic for
    # ease of maintenance.
    author="ClusterHQ Team",
    # This is contact information for the authors.
    author_email="support@clusterhq.com",
    # Here is a website where more information about the software is available.
    url="https://clusterhq.com/",

    # A short identifier for the license under which the project is released.
    license="Apache License, Version 2.0",

    # Some details about what Flocker is.  Synchronized with the README.rst to
    # keep it up to date more easily.
    long_description=description,

    # This setuptools helper will find everything that looks like a *Python*
    # package (in other words, things that can be imported) which are part of
    # the Flocker package.
    packages=find_packages(),

    package_data={
        'flocker.node.functional': ['sendbytes-docker/*', 'env-docker/*'],
    },

    entry_points = {
        # Command-line programs we want setuptools to install:
        'console_scripts': [
            'flocker-volume = flocker.volume.script:flocker_volume_main',
            'flocker-deploy = flocker.cli.script:flocker_deploy_main',
            'flocker-changestate = flocker.node.script:flocker_changestate_main',
            'flocker-reportstate = flocker.node.script:flocker_reportstate_main',
        ],
    },

    install_requires=[
        "setuptools >= 1.4",

        "eliot == 0.4.0",
        "zope.interface >= 4.0.5",
        "pytz",
        "characteristic == 0.1.0",
        "Twisted == 14.0.0",

        "PyYAML == 3.10",

        "treq == 0.2.1",

        "netifaces >= 0.8",
        "ipaddr == 2.1.10",

        "docker-py == 0.4.0"
        ],

    extras_require={
        # This extra allows you to build and check the documentation for
        # Flocker.
        "doc": [
            "Sphinx==1.2.2",
            "sphinx-rtd-theme==0.1.6",
            "pyenchant==1.6.6",
            "sphinxcontrib-spelling==2.1.1",
            ],
        # This extra is for developers who need to work on Flocker itself.
        "dev": [
            # flake8 is pretty critical to have around to help point out
            # obvious mistakes. It depends on PEP8, pyflakes and mccabe.
            "pyflakes==0.8.1",
            "pep8==1.5.7",
            "mccabe==0.2.1",
            "flake8==2.2.0",

            # Run the test suite:
            "tox==1.7.1",

            # versioneer is necessary in order to update (but *not* merely to
            # use) the automatic versioning tools.
            "versioneer==0.10",

            # Some of the tests use Conch:
            "PyCrypto==2.6.1",
            "pyasn1==0.1.7",

            # The test suite uses network namespaces
            "nomenclature >= 0.1.0",
            ],

        # This extra is for Flocker release engineers to set up their release
        # environment.
        "release": [
            "gsutil",
            "wheel",
            ],
        },

    cmdclass=cmdclass,

    # Some "trove classifiers" which are relevant.
    classifiers=[
        "License :: OSI Approved :: Apache Software License",
        ],
    )
<|endoftext|>


<commit_before>from distutils.core import setup
setup(name='q', version='2.3', py_modules=['q'],
      description='Quick-and-dirty debugging output for tired programmers',
      author='Ka-Ping Yee', author_email='ping@zesty.ca',
      license='Apache License 2.0',
      url='http://github.com/zestyping/q', classifiers=[
          'Programming Language :: Python',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: Apache Software License'
      ])
<commit_msg>Advance PyPI version to 2.4.<commit_after>from distutils.core import setup
setup(name='q', version='2.4', py_modules=['q'],
      description='Quick-and-dirty debugging output for tired programmers',
      author='Ka-Ping Yee', author_email='ping@zesty.ca',
      license='Apache License 2.0',
      url='http://github.com/zestyping/q', classifiers=[
          'Programming Language :: Python',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: Apache Software License'
      ])
<|endoftext|>


<commit_before># Copyright (c) 2012, Calxeda Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Calxeda Inc. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.

from setuptools import setup

setup(
    name='cxmanage',
    version='0.8.0',
    packages=['cxmanage', 'cxmanage.commands', 'cxmanage_api'],
    scripts=['scripts/cxmanage', 'scripts/sol_tabs'],
    description='Calxeda Management Utility',
    # NOTE: As of right now, the pyipmi version requirement needs to be updated
    # at the top of scripts/cxmanage as well.
    install_requires=[
                        'tftpy',
                        'pexpect',
                        'pyipmi>=0.7.1',
                        'argparse',
                        'sphinx',
                        'cloud_sptheme'
    ],
    classifiers=[
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7']
)
<commit_msg>setup.py: Move sphinx, cloud_sptheme to optional dependencies<commit_after># Copyright (c) 2012, Calxeda Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Calxeda Inc. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.

from setuptools import setup

setup(
    name='cxmanage',
    version='0.8.0',
    packages=['cxmanage', 'cxmanage.commands', 'cxmanage_api'],
    scripts=['scripts/cxmanage', 'scripts/sol_tabs'],
    description='Calxeda Management Utility',
    # NOTE: As of right now, the pyipmi version requirement needs to be updated
    # at the top of scripts/cxmanage as well.
    install_requires=[
                        'tftpy',
                        'pexpect',
                        'pyipmi>=0.7.1',
                        'argparse',
    ],
    extras_require={
        'docs': ['sphinx', 'cloud_sptheme'],
    },
    classifiers=[
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7']
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

version = __import__('wagtail_feeds').__version__

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    "Django>=1.8,<1.11",
    "Wagtail>=1.4",
    "html5lib==0.999999",
]

test_requirements = [
    "Django>=1.8,<1.11",
    "Wagtail>=1.4",
    "html5lib==0.999999",
]

setup(
    name='django-wagtail-feeds',
    version=version,
    description="Support RSS Feeds, Facebook Instant Articles and Apple News",
    long_description=readme + '\n\n' + history,
    author="Christopher Clarke",
    author_email='cclarke@chrisdev.com',
    url='https://github.com/chrisdev/django-wagtail-feeds',
    packages=[
        'wagtail_feeds',
    ],
    package_dir={'wagtail_feeds':
                 'wagtail_feeds'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='wagtail_feeds',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='runtests.runtests',
    tests_require=test_requirements
)
<commit_msg>Latest release<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

version = __import__('wagtail_feeds').__version__

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    "Django>=1.8",
    "Wagtail>=1.4",
]

test_requirements = [
    "Django>=1.8",
    "Wagtail>=1.4",
]

setup(
    name='django-wagtail-feeds',
    version=version,
    description="Support RSS Feeds, Facebook Instant Articles and Apple News",
    long_description=readme + '\n\n' + history,
    author="Christopher Clarke",
    author_email='cclarke@chrisdev.com',
    url='https://github.com/chrisdev/django-wagtail-feeds',
    packages=[
        'wagtail_feeds',
    ],
    package_dir={'wagtail_feeds':
                 'wagtail_feeds'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='wagtail_feeds',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='runtests.runtests',
    tests_require=test_requirements
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py

Created by Stephan Hügel on 2011-03-04
"""
import sys
from setuptools import setup, find_packages
version = '1.0.1'

setup(
    name='Pyzotero',
    version=version,
    description='Python wrapper for the Zotero API',
    author='Stephan Hügel',
    author_email='urschrei@gmail.com',
    license='GNU GPL Version 3',
    url='https://github.com/urschrei/pyzotero',
    include_package_data=True,
    download_url='https://github.com/urschrei/pyzotero/tarball/v%s' % version,
    keywords=['zotero'],
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Operating System :: OS Independent',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    packages=find_packages(),
    install_requires=['feedparser >= 5.1.0', 'pytz', 'requests', 'six'],
    extras_require={
        'ordereddict': ['ordereddict==1.1']
    },
    long_description="""\
A Python wrapper for the Zotero Server v3 API
---------------------------------------------

Provides methods for accessing Zotero Server API v3.
For full documentation see http://pyzotero.readthedocs.org/en/latest/

This version requires Python 2.7.x / 3.4.x"""
)
<commit_msg>Attempting to use pkg_resources to grab version<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py

Created by Stephan Hügel on 2011-03-04
"""
import sys
from setuptools import setup, find_packages
from pkg_resources import get_distribution
version = get_distribution('pyzotero').version

setup(
    name='Pyzotero',
    version=version,
    description='Python wrapper for the Zotero API',
    author='Stephan Hügel',
    author_email='urschrei@gmail.com',
    license='GNU GPL Version 3',
    url='https://github.com/urschrei/pyzotero',
    include_package_data=True,
    download_url='https://github.com/urschrei/pyzotero/tarball/v%s' % version,
    keywords=['zotero'],
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Operating System :: OS Independent',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    packages=find_packages(),
    install_requires=['feedparser >= 5.1.0', 'pytz', 'requests', 'six'],
    extras_require={
        'ordereddict': ['ordereddict==1.1']
    },
    long_description="""\
A Python wrapper for the Zotero Server v3 API
---------------------------------------------

Provides methods for accessing Zotero Server API v3.
For full documentation see http://pyzotero.readthedocs.org/en/latest/

This version requires Python 2.7.x / 3.4.x"""
)
<|endoftext|>


<commit_before>from setuptools import setup

from rohrpost import __version__

setup(
    name = 'rohrpost',
    version = __version__,

    description = 'rohrpost WebSocket protocol for ASGI',

    url = 'https://github.com/axsemantics/rohrpost',

    author = 'Tobias Kunze',
    author_email = 'tobias.kunze@ax-semantics.com',

    license = 'MIT',

    classifiers = [
        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ],

    packages = ['rohrpost'],
)
<commit_msg>Format setup.py with black<commit_after>from setuptools import setup

from rohrpost import __version__

setup(
    name="rohrpost",
    version=__version__,
    description="rohrpost WebSocket protocol for ASGI",
    url="https://github.com/axsemantics/rohrpost",
    author="Tobias Kunze",
    author_email="tobias.kunze@ax-semantics.com",
    license="MIT",
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
    ],
    packages=["rohrpost"],
)
<|endoftext|>


<commit_before>#!/usr/bin/python

from setuptools import setup, find_packages
import os

CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Environment :: Console',
    'Intended Audience :: Customer Service',
    'Intended Audience :: Developers',
    'Intended Audience :: Education',
    'Intended Audience :: Science/Research',
    'Intended Audience :: Telecommunications Industry',
    'Natural Language :: English',
    'Operating System :: POSIX',
    'Topic :: Software Development :: Libraries :: Python Modules',
    'Topic :: Multimedia :: Sound/Audio',
    'Topic :: Utilities',
    "Programming Language :: Python",
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 2.7",
]

setup(
    name='pyfoscam',
    version='1.2',
    description='Foscam Python Library for H.264 IP Cameras (FI9821W/P/HD816W/P)',
    long_description=open('README.rst', 'r').read(),
    author='Cherish Chen',
    author_email='sinchb128@gmail.com',
    url='https://github.com/quatanium/foscam-python-lib',
    include_package_data=True,
    license='MIT',
    packages=find_packages(exclude=['tests']),
    zip_safe=False,
    keywords=['foscam', 'Camera', 'IPC'],
)
<commit_msg>Version bump to 1.2.1 to prepare pypi release<commit_after>#!/usr/bin/python

from setuptools import setup, find_packages
import os

CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Environment :: Console',
    'Intended Audience :: Customer Service',
    'Intended Audience :: Developers',
    'Intended Audience :: Education',
    'Intended Audience :: Science/Research',
    'Intended Audience :: Telecommunications Industry',
    'Natural Language :: English',
    'Operating System :: POSIX',
    'Topic :: Software Development :: Libraries :: Python Modules',
    'Topic :: Multimedia :: Sound/Audio',
    'Topic :: Utilities',
    "Programming Language :: Python",
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 2.7",
]

setup(
    name='pyfoscam',
    version='1.2.1',
    description='Foscam Python Library for H.264 IP Cameras (FI9821W/P/HD816W/P)',
    long_description=open('README.rst', 'r').read(),
    author='Cherish Chen',
    author_email='sinchb128@gmail.com',
    url='https://github.com/quatanium/foscam-python-lib',
    include_package_data=True,
    license='MIT',
    packages=find_packages(exclude=['tests']),
    zip_safe=False,
    keywords=['foscam', 'Camera', 'IPC'],
)
<|endoftext|>