<commit_before>import os
from setuptools import find_packages, setup

try:
    from functools import singledispatch

    singledispatch_requires = []
except ImportError:
    singledispatch_requires = ['singledispatch==3.4.0.3']

from eventsourcing import __version__

# Read the docs doesn't need to build the Cassandra driver (and can't).
if 'READTHEDOCS' in os.environ:
    os.environ['CASS_DRIVER_NO_CYTHON'] = '1'

install_requires = singledispatch_requires + [
    'python-dateutil<=2.6.99999',
    'six<=1.11.99999',
    'pycryptodome<=3.4.99999',
    'requests<=2.18.99999',
]

sqlalchemy_requires = [
    'sqlalchemy<=1.2.99999,>=0.9',
    'sqlalchemy-utils<=0.32.99999',
]

cassandra_requires = [
    'cassandra-driver<=3.12.99999'
]

django_requires = [  # Note, Django 2 doesn't support Python 2.7
    'django>=1.11,<=2.0.99999' if str != bytes else 'django>=1.11,<=1.11.99999',
]

testing_requires = [
    'mock<=2.0.99999',
    'flask<=0.12.99999',
    'flask_sqlalchemy<=2.3.99',
    'uwsgi<=2.0.99999',
    'redis<=2.10.99999',
    'celery<=4.1.99999',
    'pymysql<=0.8.99999',
] + cassandra_requires + sqlalchemy_requires + django_requires

docs_requires = ['Sphinx', 'sphinx_rtd_theme', 'sphinx-autobuild'] + testing_requires

long_description = """
A library for event sourcing in Python.

`Package documentation is now available <http://eventsourcing.readthedocs.io/>`_.

`Please raise issues on GitHub <https://github.com/johnbywater/eventsourcing/issues>`_.
"""

packages = find_packages(
    exclude=[
        "docs",
        # "eventsourcing.contrib*",
        # "eventsourcing.tests*"
    ]
)

setup(
    name='eventsourcing',
    version=__version__,
    description='Event sourcing in Python',
    author='John Bywater',
    author_email='john.bywater@appropriatesoftware.net',
    url='https://github.com/johnbywater/eventsourcing',
    packages=packages,
    install_requires=install_requires,
    extras_require={
        'cassandra': cassandra_requires,
        'sqlalchemy': sqlalchemy_requires,
        'django': django_requires,
        'test': testing_requires,
        'tests': testing_requires,
        'testing': testing_requires,
        'dev': testing_requires,
        'develop': testing_requires,
        'development': testing_requires,
        'docs': docs_requires,
    },
    zip_safe=False,
    long_description=long_description,
    keywords=['event sourcing', 'event store', 'domain driven design', 'ddd', 'cqrs', 'cqs'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: Education',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Programming Language :: Python :: Implementation :: PyPy3',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)
<commit_msg>Dropped Python 3.4 from classifiers.<commit_after>import os
from setuptools import find_packages, setup

try:
    from functools import singledispatch

    singledispatch_requires = []
except ImportError:
    singledispatch_requires = ['singledispatch==3.4.0.3']

from eventsourcing import __version__

# Read the docs doesn't need to build the Cassandra driver (and can't).
if 'READTHEDOCS' in os.environ:
    os.environ['CASS_DRIVER_NO_CYTHON'] = '1'

install_requires = singledispatch_requires + [
    'python-dateutil<=2.6.99999',
    'six<=1.11.99999',
    'pycryptodome<=3.4.99999',
    'requests<=2.18.99999',
]

sqlalchemy_requires = [
    'sqlalchemy<=1.2.99999,>=0.9',
    'sqlalchemy-utils<=0.32.99999',
]

cassandra_requires = [
    'cassandra-driver<=3.12.99999'
]

django_requires = [  # Note, Django 2 doesn't support Python 2.7
    'django>=1.11,<=2.0.99999' if str != bytes else 'django>=1.11,<=1.11.99999',
]

testing_requires = [
    'mock<=2.0.99999',
    'flask<=0.12.99999',
    'flask_sqlalchemy<=2.3.99',
    'uwsgi<=2.0.99999',
    'redis<=2.10.99999',
    'celery<=4.1.99999',
    'pymysql<=0.8.99999',
] + cassandra_requires + sqlalchemy_requires + django_requires

docs_requires = ['Sphinx', 'sphinx_rtd_theme', 'sphinx-autobuild'] + testing_requires

long_description = """
A library for event sourcing in Python.

`Package documentation is now available <http://eventsourcing.readthedocs.io/>`_.

`Please raise issues on GitHub <https://github.com/johnbywater/eventsourcing/issues>`_.
"""

packages = find_packages(
    exclude=[
        "docs",
        # "eventsourcing.contrib*",
        # "eventsourcing.tests*"
    ]
)

setup(
    name='eventsourcing',
    version=__version__,
    description='Event sourcing in Python',
    author='John Bywater',
    author_email='john.bywater@appropriatesoftware.net',
    url='https://github.com/johnbywater/eventsourcing',
    packages=packages,
    install_requires=install_requires,
    extras_require={
        'cassandra': cassandra_requires,
        'sqlalchemy': sqlalchemy_requires,
        'django': django_requires,
        'test': testing_requires,
        'tests': testing_requires,
        'testing': testing_requires,
        'dev': testing_requires,
        'develop': testing_requires,
        'development': testing_requires,
        'docs': docs_requires,
    },
    zip_safe=False,
    long_description=long_description,
    keywords=['event sourcing', 'event store', 'domain driven design', 'ddd', 'cqrs', 'cqs'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: Education',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Programming Language :: Python :: Implementation :: PyPy3',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)
<|endoftext|>


<commit_before># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import unicode_literals

import io
import os.path
import sys

import setuptools

REQUIREMENT_DIR = "requirements"
ENCODING = "utf8"

with io.open("README.rst", encoding=ENCODING) as f:
    long_description = f.read()

with io.open(
        os.path.join("docs", "pages", "introduction", "summary.txt"),
        encoding=ENCODING) as f:
    summary = f.read()

with open(os.path.join(REQUIREMENT_DIR, "requirements.txt")) as f:
    install_requires = [line.strip() for line in f if line.strip()]

with open(os.path.join(REQUIREMENT_DIR, "test_requirements.txt")) as f:
    tests_requires = [line.strip() for line in f if line.strip()]

with open(os.path.join(REQUIREMENT_DIR, "docs_requirements.txt")) as f:
    docs_requires = [line.strip() for line in f if line.strip()]

MODULE_NAME = "pytablewriter"
setuptools_require = ["setuptools>=20.2.2"]
needs_pytest = set(["pytest", "test", "ptr"]).intersection(sys.argv)
pytest_runner_require = ["pytest-runner"] if needs_pytest else []

setuptools.setup(
    name=MODULE_NAME,
    version="0.27.2",
    url="https://github.com/thombashi/{}".format(MODULE_NAME),

    author="Tsuyoshi Hombashi",
    author_email="tsuyoshi.hombashi@gmail.com",
    description=summary,
    include_package_data=True,
    keywords=[
        "table", "CSV", "Excel", "JavaScript", "JSON", "LTSV",
        "Markdown", "MediaWiki", "HTML", "pandas", "reStructuredText",
        "SQLite", "TSV", "TOML",
    ],
    license="MIT License",
    long_description=long_description,
    packages=setuptools.find_packages(exclude=["test*"]),

    install_requires=setuptools_require + install_requires,
    setup_requires=setuptools_require + pytest_runner_require,
    tests_require=tests_requires,
    extras_require={
        "test": tests_requires,
        "docs": docs_requires,
    },

    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Information Technology",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Topic :: Software Development :: Libraries",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ])
<commit_msg>Fix the PyPI page<commit_after># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import unicode_literals

import io
import os.path
import sys

import setuptools

REQUIREMENT_DIR = "requirements"
ENCODING = "utf8"

with io.open("README.rst", encoding=ENCODING) as f:
    long_description = f.read()

with io.open(
        os.path.join("docs", "pages", "introduction", "summary.txt"),
        encoding=ENCODING) as f:
    summary = f.read().strip()

with open(os.path.join(REQUIREMENT_DIR, "requirements.txt")) as f:
    install_requires = [line.strip() for line in f if line.strip()]

with open(os.path.join(REQUIREMENT_DIR, "test_requirements.txt")) as f:
    tests_requires = [line.strip() for line in f if line.strip()]

with open(os.path.join(REQUIREMENT_DIR, "docs_requirements.txt")) as f:
    docs_requires = [line.strip() for line in f if line.strip()]

MODULE_NAME = "pytablewriter"
setuptools_require = ["setuptools>=20.2.2"]
needs_pytest = set(["pytest", "test", "ptr"]).intersection(sys.argv)
pytest_runner_require = ["pytest-runner"] if needs_pytest else []

setuptools.setup(
    name=MODULE_NAME,
    version="0.27.2",
    url="https://github.com/thombashi/{}".format(MODULE_NAME),

    author="Tsuyoshi Hombashi",
    author_email="tsuyoshi.hombashi@gmail.com",
    description=summary,
    include_package_data=True,
    keywords=[
        "table", "CSV", "Excel", "JavaScript", "JSON", "LTSV",
        "Markdown", "MediaWiki", "HTML", "pandas", "reStructuredText",
        "SQLite", "TSV", "TOML",
    ],
    license="MIT License",
    long_description=long_description,
    packages=setuptools.find_packages(exclude=["test*"]),

    install_requires=setuptools_require + install_requires,
    setup_requires=setuptools_require + pytest_runner_require,
    tests_require=tests_requires,
    extras_require={
        "test": tests_requires,
        "docs": docs_requires,
    },

    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Information Technology",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Topic :: Software Development :: Libraries",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ])
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Standard library
from distutils.core import setup
# Project
import dashgen

with open('README.rst') as file:
    long_description = file.read()

setup(author="Timid Robot Zehta",
      author_email="tim@clockwork.net",
      classifiers=["Environment :: Console",
                   "License :: OSI Approved :: MIT License",],
      description="Interquartile Mean pure-Python module",
      download_url="https://github.com/ClockworkNet/graphite-dashgen/releases",
      license="MIT License",
      long_description=long_description,
      name="python-graphite-dashgen",
      py_modules=["dashgen"],
      url="https://github.com/ClockworkNet/graphite-dashgen",
      version=dashgen.VERSION,
      )
<commit_msg>corrected description<commit_after>#!/usr/bin/env python
# Standard library
from distutils.core import setup
# Project
import dashgen

with open('README.rst') as file:
    long_description = file.read()

setup(author="Timid Robot Zehta",
      author_email="tim@clockwork.net",
      classifiers=["Environment :: Console",
                   "License :: OSI Approved :: MIT License",],
      description="Graphite-dashgen automates the creation of Graphite "
                  "dashboards",
      download_url="https://github.com/ClockworkNet/graphite-dashgen/releases",
      license="MIT License",
      long_description=long_description,
      name="python-graphite-dashgen",
      py_modules=["dashgen"],
      url="https://github.com/ClockworkNet/graphite-dashgen",
      version=dashgen.VERSION,
      )
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import codecs
import os
import sys

from setuptools import setup, Command

long_description = codecs.open("README.md", "r", "utf-8").read()

CLASSIFIERS = [
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
    'Topic :: System :: Distributed Computing',
    'Topic :: Software Development :: Object Brokering',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Operating System :: OS Independent',
    'Operating System :: POSIX',
    'Operating System :: Microsoft :: Windows',
    'Operating System :: MacOS :: MacOS X',
    'Framework :: Django',
]

NAME = 'jobtastic'

# Distribution Meta stuff because we can't just import jobtastic
# Mostly cribbed fro Celery's setup.py

import re

# Standard ``__foo__ = 'bar'`` pairs.
re_meta = re.compile(r'__(\w+?)__\s*=\s*(.*)')
# VERSION tuple
re_vers = re.compile(r'VERSION\s*=\s*\((.*?)\)')
# Module docstring
re_doc = re.compile(r'^"""(.+?)"""')
# We don't need the quotes
rq = lambda s: s.strip("\"'")

def add_default(m):
    """
    Get standard ``__foo__ = 'bar'`` pairs as a (foo, bar) tuple.
    """
    attr_name, attr_value = m.groups()
    return ((attr_name, rq(attr_value)), )

def add_version(m):
    v = list(map(rq, m.groups()[0].split(', ')))
    return (('VERSION', '.'.join(v[0:3]) + ''.join(v[3:])), )

def add_doc(m):
    """
    Grab the module docstring
    """
    return (('doc', m.groups()[0]), )

pats = {
    re_meta: add_default,
    re_vers: add_version,
    re_doc: add_doc,
}

here = os.path.abspath(os.path.dirname(__file__))
meta_fh = open(os.path.join(here, 'jobtastic/__init__.py'))

# Parse out the package meta information from the __init__ using *shudder*
# regexes
meta = {}
try:
    for line in meta_fh:
        if line.strip() == '# -eof meta-':
            break
        for pattern, handler in pats.items():
            m = pattern.match(line.strip())
            if m:
                meta.update(handler(m))
finally:
    meta_fh.close()

# -*- Installation Requires -*-

def strip_comments(l):
    return l.split('#', 1)[0].strip()

def reqs(*f):
    return list(filter(None, [strip_comments(l) for l in open(
        os.path.join(os.getcwd(), 'requirements', *f)).readlines()]))

install_requires = reqs('default.txt')
tests_require = reqs('tests.txt')

# -*- Test Runners -*-

class RunDjangoTests(Command):
    description = 'Run the django test suite from the tests dir.'
    user_options = []
    extra_env = {}
    extra_args = []

    def run(self):
        for env_name, env_value in self.extra_env.items():
            os.environ[env_name] = str(env_value)

        this_dir = os.getcwd()
        testproj_dir = os.path.join(this_dir, 'test_projects')
        django_testproj_dir = os.path.join(testproj_dir, 'django')
        os.chdir(django_testproj_dir)
        sys.path.append(django_testproj_dir)

        from django.core.management import execute_manager
        os.environ['DJANGO_SETTINGS_MODULE'] = os.environ.get(
            'DJANGO_SETTINGS_MODULE',
            'testproj.settings',
        )
        settings_file = os.environ['DJANGO_SETTINGS_MODULE']
        settings_mod = __import__(settings_file, {}, {}, [''])
        prev_argv = list(sys.argv)
        try:
            sys.argv = [__file__, 'test'] + self.extra_args
            execute_manager(settings_mod, argv=sys.argv)
        finally:
            sys.argv = prev_argv

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

setup(
    name=NAME,
    version=meta['VERSION'],
    description=meta['doc'],
    author=meta['author'],
    author_email=meta['contact'],
    url=meta['homepage'],
    long_description=long_description,
    packages=[NAME],
    license='BSD',
    platforms=['any'],
    classifiers=CLASSIFIERS,
    cmdclass={
        'test': RunDjangoTests,
    },
    install_requires=install_requires,
    tests_require=tests_require,
)
<commit_msg>Django 1.6 compat for setup.py test<commit_after># -*- coding: utf-8 -*-

import codecs
import os
import sys

from setuptools import setup, Command

long_description = codecs.open("README.md", "r", "utf-8").read()

CLASSIFIERS = [
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
    'Topic :: System :: Distributed Computing',
    'Topic :: Software Development :: Object Brokering',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Operating System :: OS Independent',
    'Operating System :: POSIX',
    'Operating System :: Microsoft :: Windows',
    'Operating System :: MacOS :: MacOS X',
    'Framework :: Django',
]

NAME = 'jobtastic'

# Distribution Meta stuff because we can't just import jobtastic
# Mostly cribbed fro Celery's setup.py

import re

# Standard ``__foo__ = 'bar'`` pairs.
re_meta = re.compile(r'__(\w+?)__\s*=\s*(.*)')
# VERSION tuple
re_vers = re.compile(r'VERSION\s*=\s*\((.*?)\)')
# Module docstring
re_doc = re.compile(r'^"""(.+?)"""')
# We don't need the quotes
rq = lambda s: s.strip("\"'")

def add_default(m):
    """
    Get standard ``__foo__ = 'bar'`` pairs as a (foo, bar) tuple.
    """
    attr_name, attr_value = m.groups()
    return ((attr_name, rq(attr_value)), )

def add_version(m):
    v = list(map(rq, m.groups()[0].split(', ')))
    return (('VERSION', '.'.join(v[0:3]) + ''.join(v[3:])), )

def add_doc(m):
    """
    Grab the module docstring
    """
    return (('doc', m.groups()[0]), )

pats = {
    re_meta: add_default,
    re_vers: add_version,
    re_doc: add_doc,
}

here = os.path.abspath(os.path.dirname(__file__))
meta_fh = open(os.path.join(here, 'jobtastic/__init__.py'))

# Parse out the package meta information from the __init__ using *shudder*
# regexes
meta = {}
try:
    for line in meta_fh:
        if line.strip() == '# -eof meta-':
            break
        for pattern, handler in pats.items():
            m = pattern.match(line.strip())
            if m:
                meta.update(handler(m))
finally:
    meta_fh.close()

# -*- Installation Requires -*-

def strip_comments(l):
    return l.split('#', 1)[0].strip()

def reqs(*f):
    return list(filter(None, [strip_comments(l) for l in open(
        os.path.join(os.getcwd(), 'requirements', *f)).readlines()]))

install_requires = reqs('default.txt')
tests_require = reqs('tests.txt')

# -*- Test Runners -*-

class RunDjangoTests(Command):
    description = 'Run the django test suite from the tests dir.'
    user_options = []
    extra_env = {}
    extra_args = []

    def run(self):
        for env_name, env_value in self.extra_env.items():
            os.environ[env_name] = str(env_value)

        this_dir = os.getcwd()
        testproj_dir = os.path.join(this_dir, 'test_projects')
        django_testproj_dir = os.path.join(testproj_dir, 'django')
        os.chdir(django_testproj_dir)
        sys.path.append(django_testproj_dir)

        os.environ['DJANGO_SETTINGS_MODULE'] = os.environ.get(
            'DJANGO_SETTINGS_MODULE',
            'testproj.settings',
        )

        django_1_4 = False
        try:
            from django.core.management import execute_manager as run_command
            django_1_4 = True
        except ImportError:
            # execute_manager was renamed in Django 1.6
            from django.core.management import (
                execute_from_command_line as run_command,
            )

        modified_args = [__file__, 'test'] + self.extra_args
        if django_1_4:
            settings_file = os.environ['DJANGO_SETTINGS_MODULE']
            settings_mod = __import__(settings_file, {}, {}, [''])
            run_command(settings_mod, argv=modified_args)
        else:
            run_command(modified_args)

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

setup(
    name=NAME,
    version=meta['VERSION'],
    description=meta['doc'],
    author=meta['author'],
    author_email=meta['contact'],
    url=meta['homepage'],
    long_description=long_description,
    packages=[NAME],
    license='BSD',
    platforms=['any'],
    classifiers=CLASSIFIERS,
    cmdclass={
        'test': RunDjangoTests,
    },
    install_requires=install_requires,
    tests_require=tests_require,
)
<|endoftext|>


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

import os
import utils as u
from argparse import ArgumentParser
from configparser import ConfigParser
from printer import PrinterFactory
from sys import exit

def main():
    # GENERAL SETTINGS!
    file_dir = os.path.dirname(os.path.realpath(__file__))
    directory = os.path.join(file_dir, "sheets/")
    extention = ".ini"
    description = "Cool Command-line Cheatsheets"
    help_general = "The cheatsheet you want to see"
    help_list = "List all available Cheatsheets"
    help_inline = "One cheat per line, this is default"
    help_breakline = "Break lines"

    # COMMAND-LINE ARGUMENTS!
    argumentparser = ArgumentParser(description=description)
    printertype = argumentparser.add_mutually_exclusive_group()

    argumentparser.add_argument('--list', dest='listcheats', action="store_true", required=False, help=help_list)
    argumentparser.add_argument('cheatsheet', nargs='?', help=help_general)

    printertype.set_defaults(printer='InlinePrinter')
    printertype.add_argument('-l', help=help_inline, action='store_const', dest='printer', const='InlinePrinter')
    printertype.add_argument('-b', help=help_breakline, action='store_const', dest='printer', const='BreaklinePrinter')

    # WHERE THE RUBBER MEETS THE ROAD!
    cmd_arguments = argumentparser.parse_args()

    if cmd_arguments.cheatsheet is None:
        argumentparser.print_help()
        exit(2)

    if cmd_arguments.listcheats:
        u.print_available_sheets(directory)
        exit(0)

    filename = directory + cmd_arguments.cheatsheet + extention
    CheatPrinterConstructor = PrinterFactory.create_printer(cmd_arguments.printer)
    configparser = ConfigParser()
    cheatprinter = CheatPrinterConstructor(configparser)

    try:
        configparser.read(filename)
        cheatprinter.printsheet()
        exitcode = 0
    except Exception as e:
        # I know lazy handling... Sorry.
        # TOOD better exception handling.
        print(filename + " not available or contains errors.")
        print(e)
        exitcode = 1
    finally:
        exit(exitcode)

if __name__ == "__main__":
    main()
<commit_msg>Fix command line arguments order of checks<commit_after>#!/usr/bin/env python3

import os
import utils as u
from argparse import ArgumentParser
from configparser import ConfigParser
from printer import PrinterFactory
from sys import exit

def main():
    # GENERAL SETTINGS!
    file_dir = os.path.dirname(os.path.realpath(__file__))
    directory = os.path.join(file_dir, "sheets/")
    extention = ".ini"
    description = "Cool Command-line Cheatsheets"
    help_general = "The cheatsheet you want to see"
    help_list = "List all available Cheatsheets"
    help_inline = "One cheat per line, this is default"
    help_breakline = "Break lines"

    # COMMAND-LINE ARGUMENTS!
    argumentparser = ArgumentParser(description=description)
    printertype = argumentparser.add_mutually_exclusive_group()

    argumentparser.add_argument('--list', dest='listcheats', action="store_true", required=False, help=help_list)
    argumentparser.add_argument('cheatsheet', nargs='?', help=help_general)

    printertype.set_defaults(printer='InlinePrinter')
    printertype.add_argument('-l', help=help_inline, action='store_const', dest='printer', const='InlinePrinter')
    printertype.add_argument('-b', help=help_breakline, action='store_const', dest='printer', const='BreaklinePrinter')

    # WHERE THE RUBBER MEETS THE ROAD!
    cmd_arguments = argumentparser.parse_args()

    if cmd_arguments.listcheats:
        u.print_available_sheets(directory)
        exit(0)

    if cmd_arguments.cheatsheet is None:
        argumentparser.print_help()
        exit(2)

    filename = directory + cmd_arguments.cheatsheet + extention
    CheatPrinterConstructor = PrinterFactory.create_printer(cmd_arguments.printer)
    configparser = ConfigParser()
    cheatprinter = CheatPrinterConstructor(configparser)

    try:
        configparser.read(filename)
        cheatprinter.printsheet()
        exitcode = 0
    except Exception as e:
        # I know lazy handling... Sorry.
        # TOOD better exception handling.
        print(filename + " not available or contains errors.")
        print(e)
        exitcode = 1
    finally:
        exit(exitcode)

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before># Copyright (c) 2009 gocept gmbh & co. kg
# See also LICENSE.txt

from setuptools import setup, find_packages

setup(
    name='zeit.content.cp',
    version='0.8dev',
    author='gocept',
    author_email='mail@gocept.com',
    url='https://intra.gocept.com/projects/projects/zeit-cms',
    description="""\
""",
    packages=find_packages('src'),
    package_dir = {'': 'src'},
    include_package_data = True,
    zip_safe=False,
    license='gocept proprietary',
    namespace_packages = ['zeit', 'zeit.content'],
    install_requires=[
        'FeedParser',
        'gocept.cache',
        'gocept.lxml',
        'gocept.mochikit>=1.4.2.2',
        'gocept.runner',
        'lxml',
        'python-cjson',
        'setuptools',
        'stabledict',
        'zc.sourcefactory',
        'zeit.cms>1.21',
        'zeit.content.quiz>=0.4.2',
        'zeit.find >= 0.4',
        'zope.app.pagetemplate',
        'zope.component',
        'zope.container>=3.8.1',
        'zope.event',
        'zope.formlib',
        'zope.i18n',
        'zope.interface',
        'zope.lifecycleevent',
        'zope.viewlet',
    ],
    entry_points = dict(
        console_scripts =
        ['refresh-feeds = zeit.content.cp.feed:refresh_all',])
)
<commit_msg>declared missing dependency<commit_after># Copyright (c) 2009 gocept gmbh & co. kg
# See also LICENSE.txt

from setuptools import setup, find_packages

setup(
    name='zeit.content.cp',
    version='0.8dev',
    author='gocept',
    author_email='mail@gocept.com',
    url='https://intra.gocept.com/projects/projects/zeit-cms',
    description="""\
""",
    packages=find_packages('src'),
    package_dir = {'': 'src'},
    include_package_data = True,
    zip_safe=False,
    license='gocept proprietary',
    namespace_packages = ['zeit', 'zeit.content'],
    install_requires=[
        'FeedParser',
        'gocept.cache',
        'gocept.lxml',
        'gocept.mochikit>=1.4.2.2',
        'gocept.runner',
        'lxml',
        'python-cjson',
        'setuptools',
        'stabledict',
        'zc.sourcefactory',
        'zeit.cms>1.21',
        'zeit.content.quiz>=0.4.2',
        'zeit.find >= 0.4',
        'zope.app.appsetup',
        'zope.app.pagetemplate',
        'zope.component',
        'zope.container>=3.8.1',
        'zope.event',
        'zope.formlib',
        'zope.i18n',
        'zope.interface',
        'zope.lifecycleevent',
        'zope.viewlet',
    ],
    entry_points = dict(
        console_scripts =
        ['refresh-feeds = zeit.content.cp.feed:refresh_all',])
)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# OpenID relying party library
# Copyright Martin v. Löwis, 2009
# Licensed under the Academic Free License, version 3

# This library implements OpenID Authentication 2.0,
# in the role of a relying party
# It has the following assumptions and limitations:
# - service discovery requires YADIS (HTML discovery not implemented)
# - only provider-directed mode (identifier_select) is supported
# - direct requests require https
# - as a signature algorithm, HMAC-SHA1 is requested

import urllib, BeautifulSoup, xml.etree.ElementTree
import cStringIO, base64, hmac, sha, datetime

# Don't use urllib2, since it breaks in 2.5
# for https://login.launchpad.net//+xrds

def parse_response(s):
    '''Parse a key-value form (OpenID section 4.1.1) into a dictionary'''
    res = {}
    for line in s.splitlines():
        k,v = line.split(':', 1)
        res[k] = v
    return res

def discover(url):
    '''Perform service discovery on the OP URL.
    Return list of service types, and the auth/2.0 URL,
    or None if discovery fails.'''
    res = urllib.urlopen(url)

    content_type = res.headers.gettype()

    # Yadis 6.2.5 option 2 and 3: header includes x-xrds-location
    xrds_loc = res.headers.get('x-xrds-location')
    if xrds_loc and content_type != 'application/xrds+xml':
        res.close()
        return discover(xrds_loc)

    if content_type == 'text/html':
        data = res.read()
        res.close()
        soup = BeautifulSoup.BeautifulSoup(data)
        # Yadis 6.2.5 option 1: meta tag
        meta = soup.findAll('meta', {'http-equiv':lambda v:v.lower()=='x-xrds-location'})
        if meta:
            xrds_loc = meta.attrs['content']
            return discover(xrds_loc)
        # OpenID 7.3, item 3: attempt html based discovery
        # TODO
        return None

    if content_type == 'application/xrds+xml':
        # Yadis 6.2.5 option 4
        doc = xml.etree.ElementTree.parse(res)
        res.close()
        for svc in doc.findall(".//{xri://$xrd*($v*2.0)}Service"):
            services = [x.text for x in svc.findall("{xri://$xrd*($v*2.0)}Type")]
            if not 'http://specs.openid.net/auth/2.0/server' in services:
                # We don't support discovery of Claimed Identifiers, only OP Identifiers
                continue
            uri = svc.find("{xri://$xrd*($v*2.0)}URI")
            if uri is None:
                return None # invalid service
            break
        else:
            return None # No OpenID 2.0 service found
    return services, uri.text

def associate(url):
    '''Create an association (OpenID section 8) between RP and OP.
    Return response as a dictionary.'''
    assert url.startswith('https') # we only support no-encryption sessions
    data = {
        'openid.ns':"http://specs.openid.net/auth/2.0",
        'openid.mode':"associate",
        'openid.assoc_type':"HMAC-SHA1",
        'openid.session_type':"no-encryption",
        }
    res = urllib.urlopen(url, urllib.urlencode(data))
    data = parse_response(res.read())
    return data

def request_authentication(services, url, assoc_handle, return_to):
    '''Request authentication (OpenID section 9).
    services is the list of discovered service types,
    url the OP service URL, assoc_handle the established session
    dictionary, and return_to the return URL.

    The return_to URL will also be passed as realm, and the
    OP may perform RP discovery on it; always request these
    data through SREG 1.0 as well.

    If AX or SREG 1.1 are supported, request email address,
    first/last name, or nickname.

    Return the URL that the browser should be redirected to.'''
    data = {
        'openid.ns':"http://specs.openid.net/auth/2.0",
        'openid.mode':"checkid_setup",
        'openid.assoc_handle':assoc_handle,
        'openid.return_to':return_to,
        'openid.claimed_id':"http://specs.openid.net/auth/2.0/identifier_select",
        'openid.identity':"http://specs.openid.net/auth/2.0/identifier_select",
        'openid.realm':return_to,
        'openid.ns.sreg':"http://openid.net/sreg/1.0",
        'openid.sreg.required':'nickname,email',
        }
    if "http://openid.net/srv/ax/1.0" in services:
        data.update({
            'openid.ns.ax':"http://openid.net/srv/ax/1.0",
            'openid.ax.mode':'fetch_request',
            'openid.ax.required':'email,first,last',
            'openid.ax.type.email':'http://axschema.org/contact/email',
            'openid.ax.type.first':"http://axschema.org/namePerson/first",
            'openid.ax.type.last':"http://axschema.org/namePerson/last",
            })
    if "http://openid.net/extensions/sreg/1.1" in services:
        data.update({
            'openid.ns.sreg11':"http://openid.net/extensions/sreg/1.1",
            'openid.sreg11.required':'nickname,email'
            })
    return url+"?"+urllib.urlencode(data)

class NotAuthenticated(Exception):
    pass

def authenticate(session, response):
    '''Process an authentication response.
    session must be the established session (minimally including
    assoc_handle and mac_key), response is the query string as parse
    by cgi.parse_qs.
    If authentication succeeds, return None.
    If the user was not authenticated, NotAuthenticated is raised.
    If the HTTP request is invalid (missing parameters, failure to
    validate signature), different exceptions will be raised, typically
    ValueError.

    Callers must check openid.response_nonce for replay attacks.
    '''

    if response['openid.ns'][0] != 'http://specs.openid.net/auth/2.0':
        raise ValueError('missing openid.ns')
    if session['assoc_handle'] != response['openid.assoc_handle'][0]:
        raise ValueError('incorrect session')
    if response['openid.mode'][0] == 'cancel':
        raise NotAuthenticated('provider did not authenticate user (cancelled)')
    if response['openid.mode'][0] != 'id_res':
        raise ValueError('invalid openid.mode')
    if  'openid.claimed_id' not in response:
        raise ValueError('missing openid.claimed_id')

    # Won't check nonce value - caller must verify this is not a replay

    signed = response['openid.signed'][0].split(',')
    if not (set(['op_endpoint', 'return_to', 'response_nonce',
                 'assoc_handle', 'claimed_id']) < set(signed)):
        raise ValueError("signature failed to sign important fields")
    query = []
    for name in signed:
        value = response['openid.'+name][0]
        query.append('%s:%s\n' % (name, value))
    query = ''.join(query)

    mac_key = base64.decodestring(session['mac_key'])
    transmitted_sig = base64.decodestring(response['openid.sig'][0])
    computed_sig = hmac.new(mac_key, query, sha).digest()

    if transmitted_sig != computed_sig:
        raise ValueError('Invalid signature')

def parse_nonce(nonce):
    '''Split a nonce into a (timestamp, ID) pair'''
    stamp = nonce.split('Z', 1)[0]
    stamp = datetime.datetime.strptime(stamp,"%Y-%m-%dT%H:%M:%S")
    return stamp

def get_namespaces(resp):
    res = {}
    for k, v in resp.items():
        if k.startswith('openid.ns.'):
            k = k.rsplit('.', 1)[1]
            res[v[0]] = k
    return res

def get_ax(resp, ns, validated):
    if "http://openid.net/srv/ax/1.0" not in ns:
        return {}
    ax = ns["http://openid.net/srv/ax/1.0"]+"."
    oax = "openid."+ax
    res = {}
    for k, v in resp.items():
        if k.startswith(oax+"type."):
            k = k.rsplit('.',1)[1]
            value_name = oax+"value."+k
            if ax+"value."+k not in validated:
                continue
            res[v[0]] = resp[value_name][0]
    return res

def get_email(resp):
    "Return the email address embedded response, or None."

    validated = resp['openid.signed'][0]

    # SREG 1.0; doesn't require namespace, as the protocol doesn't
    # specify one
    if 'openid.sreg.email' in resp and \
       'sreg.email' in validated:
        return resp['openid.sreg.email'][0]

    ns = get_namespaces(resp)

    ax = get_ax(resp, ns, validated)
    if "http://axschema.org/contact/email" in ax:
        return ax["http://axschema.org/contact/email"]

    # TODO: SREG 1.1
    return None

def get_username(resp):
    "Return either nickname or (first, last) or None."

    validated = resp['openid.signed'][0]
    if 'openid.sreg.nickname' in resp and \
       'sreg.nickname' in validated:
        return resp['openid.sreg.nickname'][0]

    ns = get_namespaces(resp)

    ax = get_ax(resp, ns, validated)
    if "http://axschema.org/namePerson/first" in ax and \
       "http://axschema.org/namePerson/last" in ax:
        return (ax["http://axschema.org/namePerson/first"],
                ax["http://axschema.org/namePerson/last"])

    # TODO: SREG 1.1
    return

################ Test Server #################################

import BaseHTTPServer, cgi

# supported providers
providers = (
    ('Google', 'http://www.google.com/favicon.ico', 'https://www.google.com/accounts/o8/id'),
    ('Yahoo', 'http://www.yahoo.com/favicon.ico', 'http://yahoo.com/'),
    # Verisigns service URL is not https
    #('Verisign', 'https://pip.verisignlabs.com/favicon.ico', 'https://pip.verisignlabs.com')
    ('myOpenID', 'https://www.myopenid.com/favicon.ico', 'https://www.myopenid.com/'),
    ('Launchpad', 'https://login.launchpad.net/favicon.ico', 'https://login.launchpad.net/')
    )

sessions = []
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):

    def write(self, payload, type):
        self.send_response(200)
        self.send_header("Content-type", type)
        self.send_header("Content-length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_GET(self):
        if self.path == '/':
            return self.root()
        path = self.path
        i = path.rfind('?')
        if i >= 0:
            query = cgi.parse_qs(path[i+1:])
            path = path[:i]
        else:
            query = {}
        if path == '/':
            if 'provider' in query:
                prov = [p for p in providers if p[0]  == query['provider'][0]]
                if len(prov) != 1:
                    return self.not_found()
                prov = prov[0]
                services, url = discover(prov[2])
                session = associate(url)
                print session
                sessions.append(session)
                self.send_response(307) # temporary redirect - do not cache
                self.send_header("Location", request_authentication
                                 (services, url, session['assoc_handle'],
                                  self.base_url+"?returned=1"))
                self.end_headers()
                return
            if 'returned' in query:
                if 'openid.ns' not in query:
                    return self.rp_discovery()
                handle = query['openid.assoc_handle'][0]
                for session in sessions:
                    if session['assoc_handle'] == handle:
                        break
                else:
                    session = None
                if not session:
                    return self.error('Not authenticated (no session)')
                print query
                try:
                    authenticate(session, query)
                except Exception, e:
                    self.error("Authentication failed"+repr(e))
                claimed = query['openid.claimed_id'][0]
                payload = "Hello "+claimed+"\n"
                email = get_email(query)
                if email:
                    payload += 'Your email is '+email+"\n"
                else:
                    payload += 'No email address is known\n'
                username = get_username(query)
                if isinstance(username, tuple):
                    username = " ".join(username)
                if username:
                    payload += 'Your nickname is '+username+'\n'
                else:
                    payload += 'No nickname is known\n'
                return self.write(payload, "text/plain")

        return self.not_found()

    def debug(self, value):
        payload = repr(value)
        self.write(payload, "text/plain")

    def error(self, text):
        self.write(text, "text/plain")

    def root(self):
        payload = "<title>OpenID login</title>"

        for name, icon, provider in providers:
            payload += "

" % (
                self.base_url, name, icon, name)
        payload += ""
        self.write(payload, "text/html")

    def rp_discovery(self):
        payload = '''<xrds:XRDS
                xmlns:xrds="xri://$xrds"
                xmlns="xri://$xrd*($v*2.0)">
                <XRD>
                     <Service priority="1">
                              <Type>http://specs.openid.net/auth/2.0/return_to</Type>
                              <URI>%s</URI>
                     </Service>
                </XRD>
                </xrds:XRDS>
        ''' % (self.base_url+"/?returned=1")
        self.write(payload, 'application/xrds+xml')

    def not_found(self):
        self.send_response(404)
        self.end_headers()

# OpenID providers often attempt relying-party discovery
# This requires the test server to use a globally valid URL
# If Python cannot correctly determine the base URL, you
# can pass it as command line argument
def test_server():
    import socket, sys
    if len(sys.argv) > 1:
        base_url = sys.argv[1]
    else:
        base_url = "http://" + socket.getfqdn() + "/"
    Handler.base_url = base_url
    BaseHTTPServer.HTTPServer.address_family = socket.AF_INET6
    httpd = BaseHTTPServer.HTTPServer(('', 8000), Handler)
    httpd.serve_forever()

if __name__ == '__main__':
    test_server()
<commit_msg>Use content type negotiation in discovery.<commit_after># -*- coding: utf-8 -*-
# OpenID relying party library
# Copyright Martin v. Löwis, 2009
# Licensed under the Academic Free License, version 3

# This library implements OpenID Authentication 2.0,
# in the role of a relying party
# It has the following assumptions and limitations:
# - service discovery requires YADIS (HTML discovery not implemented)
# - only provider-directed mode (identifier_select) is supported
# - direct requests require https
# - as a signature algorithm, HMAC-SHA1 is requested

import urllib, BeautifulSoup, xml.etree.ElementTree
import cStringIO, base64, hmac, sha, datetime

# Don't use urllib2, since it breaks in 2.5
# for https://login.launchpad.net//+xrds

def parse_response(s):
    '''Parse a key-value form (OpenID section 4.1.1) into a dictionary'''
    res = {}
    for line in s.splitlines():
        k,v = line.split(':', 1)
        res[k] = v
    return res

def discover(url):
    '''Perform service discovery on the OP URL.
    Return list of service types, and the auth/2.0 URL,
    or None if discovery fails.'''
    opener = urllib.FancyURLopener()
    opener.addheader('Accept', "text/html; q=0.3, "+
                     "application/xhtml+xml; q=0.5, "+
                     "application/xrds+xml")
    res = opener.open(url)

    content_type = res.headers.gettype()

    # Yadis 6.2.5 option 2 and 3: header includes x-xrds-location
    xrds_loc = res.headers.get('x-xrds-location')
    if xrds_loc and content_type != 'application/xrds+xml':
        res.close()
        return discover(xrds_loc)

    if content_type == 'text/html':
        data = res.read()
        res.close()
        soup = BeautifulSoup.BeautifulSoup(data)
        # Yadis 6.2.5 option 1: meta tag
        meta = soup.findAll('meta', {'http-equiv':lambda v:v.lower()=='x-xrds-location'})
        if meta:
            xrds_loc = meta.attrs['content']
            return discover(xrds_loc)
        # OpenID 7.3, item 3: attempt html based discovery
        # TODO
        return None

    if content_type == 'application/xrds+xml':
        # Yadis 6.2.5 option 4
        doc = xml.etree.ElementTree.parse(res)
        res.close()
        for svc in doc.findall(".//{xri://$xrd*($v*2.0)}Service"):
            services = [x.text for x in svc.findall("{xri://$xrd*($v*2.0)}Type")]
            if not 'http://specs.openid.net/auth/2.0/server' in services:
                # We don't support discovery of Claimed Identifiers, only OP Identifiers
                continue
            uri = svc.find("{xri://$xrd*($v*2.0)}URI")
            if uri is None:
                return None # invalid service
            break
        else:
            return None # No OpenID 2.0 service found
    return services, uri.text

def associate(url):
    '''Create an association (OpenID section 8) between RP and OP.
    Return response as a dictionary.'''
    assert url.startswith('https') # we only support no-encryption sessions
    data = {
        'openid.ns':"http://specs.openid.net/auth/2.0",
        'openid.mode':"associate",
        'openid.assoc_type':"HMAC-SHA1",
        'openid.session_type':"no-encryption",
        }
    res = urllib.urlopen(url, urllib.urlencode(data))
    data = parse_response(res.read())
    return data

def request_authentication(services, url, assoc_handle, return_to):
    '''Request authentication (OpenID section 9).
    services is the list of discovered service types,
    url the OP service URL, assoc_handle the established session
    dictionary, and return_to the return URL.

    The return_to URL will also be passed as realm, and the
    OP may perform RP discovery on it; always request these
    data through SREG 1.0 as well.

    If AX or SREG 1.1 are supported, request email address,
    first/last name, or nickname.

    Return the URL that the browser should be redirected to.'''
    data = {
        'openid.ns':"http://specs.openid.net/auth/2.0",
        'openid.mode':"checkid_setup",
        'openid.assoc_handle':assoc_handle,
        'openid.return_to':return_to,
        'openid.claimed_id':"http://specs.openid.net/auth/2.0/identifier_select",
        'openid.identity':"http://specs.openid.net/auth/2.0/identifier_select",
        'openid.realm':return_to,
        'openid.ns.sreg':"http://openid.net/sreg/1.0",
        'openid.sreg.required':'nickname,email',
        }
    if "http://openid.net/srv/ax/1.0" in services:
        data.update({
            'openid.ns.ax':"http://openid.net/srv/ax/1.0",
            'openid.ax.mode':'fetch_request',
            'openid.ax.required':'email,first,last',
            'openid.ax.type.email':'http://axschema.org/contact/email',
            'openid.ax.type.first':"http://axschema.org/namePerson/first",
            'openid.ax.type.last':"http://axschema.org/namePerson/last",
            })
    if "http://openid.net/extensions/sreg/1.1" in services:
        data.update({
            'openid.ns.sreg11':"http://openid.net/extensions/sreg/1.1",
            'openid.sreg11.required':'nickname,email'
            })
    return url+"?"+urllib.urlencode(data)

class NotAuthenticated(Exception):
    pass

def authenticate(session, response):
    '''Process an authentication response.
    session must be the established session (minimally including
    assoc_handle and mac_key), response is the query string as parse
    by cgi.parse_qs.
    If authentication succeeds, return None.
    If the user was not authenticated, NotAuthenticated is raised.
    If the HTTP request is invalid (missing parameters, failure to
    validate signature), different exceptions will be raised, typically
    ValueError.

    Callers must check openid.response_nonce for replay attacks.
    '''

    if response['openid.ns'][0] != 'http://specs.openid.net/auth/2.0':
        raise ValueError('missing openid.ns')
    if session['assoc_handle'] != response['openid.assoc_handle'][0]:
        raise ValueError('incorrect session')
    if response['openid.mode'][0] == 'cancel':
        raise NotAuthenticated('provider did not authenticate user (cancelled)')
    if response['openid.mode'][0] != 'id_res':
        raise ValueError('invalid openid.mode')
    if  'openid.claimed_id' not in response:
        raise ValueError('missing openid.claimed_id')

    # Won't check nonce value - caller must verify this is not a replay

    signed = response['openid.signed'][0].split(',')
    if not (set(['op_endpoint', 'return_to', 'response_nonce',
                 'assoc_handle', 'claimed_id']) < set(signed)):
        raise ValueError("signature failed to sign important fields")
    query = []
    for name in signed:
        value = response['openid.'+name][0]
        query.append('%s:%s\n' % (name, value))
    query = ''.join(query)

    mac_key = base64.decodestring(session['mac_key'])
    transmitted_sig = base64.decodestring(response['openid.sig'][0])
    computed_sig = hmac.new(mac_key, query, sha).digest()

    if transmitted_sig != computed_sig:
        raise ValueError('Invalid signature')

def parse_nonce(nonce):
    '''Split a nonce into a (timestamp, ID) pair'''
    stamp = nonce.split('Z', 1)[0]
    stamp = datetime.datetime.strptime(stamp,"%Y-%m-%dT%H:%M:%S")
    return stamp

def get_namespaces(resp):
    res = {}
    for k, v in resp.items():
        if k.startswith('openid.ns.'):
            k = k.rsplit('.', 1)[1]
            res[v[0]] = k
    return res

def get_ax(resp, ns, validated):
    if "http://openid.net/srv/ax/1.0" not in ns:
        return {}
    ax = ns["http://openid.net/srv/ax/1.0"]+"."
    oax = "openid."+ax
    res = {}
    for k, v in resp.items():
        if k.startswith(oax+"type."):
            k = k.rsplit('.',1)[1]
            value_name = oax+"value."+k
            if ax+"value."+k not in validated:
                continue
            res[v[0]] = resp[value_name][0]
    return res

def get_email(resp):
    "Return the email address embedded response, or None."

    validated = resp['openid.signed'][0]

    # SREG 1.0; doesn't require namespace, as the protocol doesn't
    # specify one
    if 'openid.sreg.email' in resp and \
       'sreg.email' in validated:
        return resp['openid.sreg.email'][0]

    ns = get_namespaces(resp)

    ax = get_ax(resp, ns, validated)
    if "http://axschema.org/contact/email" in ax:
        return ax["http://axschema.org/contact/email"]

    # TODO: SREG 1.1
    return None

def get_username(resp):
    "Return either nickname or (first, last) or None."

    validated = resp['openid.signed'][0]
    if 'openid.sreg.nickname' in resp and \
       'sreg.nickname' in validated:
        return resp['openid.sreg.nickname'][0]

    ns = get_namespaces(resp)

    ax = get_ax(resp, ns, validated)
    if "http://axschema.org/namePerson/first" in ax and \
       "http://axschema.org/namePerson/last" in ax:
        return (ax["http://axschema.org/namePerson/first"],
                ax["http://axschema.org/namePerson/last"])

    # TODO: SREG 1.1
    return

################ Test Server #################################

import BaseHTTPServer, cgi

# supported providers
providers = (
    ('Google', 'http://www.google.com/favicon.ico', 'https://www.google.com/accounts/o8/id'),
    ('Yahoo', 'http://www.yahoo.com/favicon.ico', 'http://yahoo.com/'),
    # Verisigns service URL is not https
    #('Verisign', 'https://pip.verisignlabs.com/favicon.ico', 'https://pip.verisignlabs.com')
    ('myOpenID', 'https://www.myopenid.com/favicon.ico', 'https://www.myopenid.com/'),
    ('Launchpad', 'https://login.launchpad.net/favicon.ico', 'https://login.launchpad.net/')
    )

sessions = []
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):

    def write(self, payload, type):
        self.send_response(200)
        self.send_header("Content-type", type)
        self.send_header("Content-length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_GET(self):
        if self.path == '/':
            return self.root()
        path = self.path
        i = path.rfind('?')
        if i >= 0:
            query = cgi.parse_qs(path[i+1:])
            path = path[:i]
        else:
            query = {}
        if path == '/':
            if 'provider' in query:
                prov = [p for p in providers if p[0]  == query['provider'][0]]
                if len(prov) != 1:
                    return self.not_found()
                prov = prov[0]
                services, url = discover(prov[2])
                session = associate(url)
                print session
                sessions.append(session)
                self.send_response(307) # temporary redirect - do not cache
                self.send_header("Location", request_authentication
                                 (services, url, session['assoc_handle'],
                                  self.base_url+"?returned=1"))
                self.end_headers()
                return
            if 'returned' in query:
                if 'openid.ns' not in query:
                    return self.rp_discovery()
                handle = query['openid.assoc_handle'][0]
                for session in sessions:
                    if session['assoc_handle'] == handle:
                        break
                else:
                    session = None
                if not session:
                    return self.error('Not authenticated (no session)')
                print query
                try:
                    authenticate(session, query)
                except Exception, e:
                    self.error("Authentication failed"+repr(e))
                claimed = query['openid.claimed_id'][0]
                payload = "Hello "+claimed+"\n"
                email = get_email(query)
                if email:
                    payload += 'Your email is '+email+"\n"
                else:
                    payload += 'No email address is known\n'
                username = get_username(query)
                if isinstance(username, tuple):
                    username = " ".join(username)
                if username:
                    payload += 'Your nickname is '+username+'\n'
                else:
                    payload += 'No nickname is known\n'
                return self.write(payload, "text/plain")

        return self.not_found()

    def debug(self, value):
        payload = repr(value)
        self.write(payload, "text/plain")

    def error(self, text):
        self.write(text, "text/plain")

    def root(self):
        payload = "<title>OpenID login</title>"

        for name, icon, provider in providers:
            payload += "

" % (
                self.base_url, name, icon, name)
        payload += ""
        self.write(payload, "text/html")

    def rp_discovery(self):
        payload = '''<xrds:XRDS
                xmlns:xrds="xri://$xrds"
                xmlns="xri://$xrd*($v*2.0)">
                <XRD>
                     <Service priority="1">
                              <Type>http://specs.openid.net/auth/2.0/return_to</Type>
                              <URI>%s</URI>
                     </Service>
                </XRD>
                </xrds:XRDS>
        ''' % (self.base_url+"/?returned=1")
        self.write(payload, 'application/xrds+xml')

    def not_found(self):
        self.send_response(404)
        self.end_headers()

# OpenID providers often attempt relying-party discovery
# This requires the test server to use a globally valid URL
# If Python cannot correctly determine the base URL, you
# can pass it as command line argument
def test_server():
    import socket, sys
    if len(sys.argv) > 1:
        base_url = sys.argv[1]
    else:
        base_url = "http://" + socket.getfqdn() + "/"
    Handler.base_url = base_url
    BaseHTTPServer.HTTPServer.address_family = socket.AF_INET6
    httpd = BaseHTTPServer.HTTPServer(('', 8000), Handler)
    httpd.serve_forever()

if __name__ == '__main__':
    test_server()
<|endoftext|>


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

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from setuptools import find_packages

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

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

requirements = [
    'jsonschema',
    'requests',
    'isodate'
]

test_requirements = [
    'bumpversion',
    'wheel',
    'flake8',
    'tox',
    'coverage',
    'cryptography',
    'PyYAML',
]

setup(
    name='sd-python-wrapper',
    version='0.1.34',
    description="A python wrapper for the Server Density Api",
    long_description=readme + '\n\n', # + history,
    author="Jonathan Sundqvist",
    author_email='hello@serverdensity.com',
    url='https://github.com/serverdensity/sd-python-wrapper',
    packages=find_packages(),
    include_package_data=True,
    install_requires=requirements,
    license="MIT",
    zip_safe=False,
    keywords='monitoring,serverdensity',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        '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='tests',
    tests_require=test_requirements
)
<commit_msg>Version bump<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from setuptools import find_packages

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

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

requirements = [
    'jsonschema',
    'requests',
    'isodate'
]

test_requirements = [
    'bumpversion',
    'wheel',
    'flake8',
    'tox',
    'coverage',
    'cryptography',
    'PyYAML',
]

setup(
    name='sd-python-wrapper',
    version='0.1.35',
    description="A python wrapper for the Server Density Api",
    long_description=readme + '\n\n', # + history,
    author="Jonathan Sundqvist",
    author_email='hello@serverdensity.com',
    url='https://github.com/serverdensity/sd-python-wrapper',
    packages=find_packages(),
    include_package_data=True,
    install_requires=requirements,
    license="MIT",
    zip_safe=False,
    keywords='monitoring,serverdensity',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        '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='tests',
    tests_require=test_requirements
)
<|endoftext|>


<commit_before># coding: utf-8
import setuptools

setuptools.setup(
    name = 'DeWorld',
    version = '0.1.0',
    author = 'Aleksey Yeletsky',
    author_email = 'a.eletsky@gmail.com',
    packages = setuptools.find_packages(),
    url = 'https://github.com/Tiendil/deworld',
    license = 'LICENSE',
    description = "DEveloping WORLD - python world generator",
    long_description = open('README').read(),
    include_package_data = True # setuptools-git MUST be installed
)
<commit_msg>installaton script<commit_after># coding: utf-8
import setuptools

setuptools.setup(
    name = 'DeWorld',
    version = '0.1.0',
    author = 'Aleksey Yeletsky',
    author_email = 'a.eletsky@gmail.com',
    packages = setuptools.find_packages(),
    url = 'https://github.com/Tiendil/deworld',
    license = 'LICENSE',
    description = "DEveloping WORLD - python world generator",
    long_description = open('README.md').read(),
    include_package_data = True # setuptools-git MUST be installed
)
<|endoftext|>


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

# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from setuptools import setup

setup(name='litedesk-lib-active_directory',
    version='0.0.1',
    description='Active Directory library for LiteDesk',
    author='Łukasz Biernot',
    author_email='lukasz.biernot@lgmail.com',
    url='http://laboratories.telekom.com',
    packages=[
        'litedesk.lib.active_directory',
        'litedesk.lib.active_directory.classes',
    ],
    package_dir={
        'litedesk.lib.active_directory': 'src/litedesk/lib/active_directory',
        'litedesk.lib.active_directory.classes': 'src/litedesk/lib/active_directory/classes',
    },
    namespace_packages=['litedesk', 'litedesk.lib'],
    install_requires=['python-ldap', ],
    zip_safe=False,
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache License 2.0',
        'Operating System :: Linux',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Programming Language :: Python',
    ],
    keywords='litedesk active_directory',
)
<commit_msg>Try to fix setup TelekomLabs-DCO-1.1-Signed-off-by: Łukasz Biernot <lukasz.biernot@gmail.com> (github: ElmoVanKielmo)<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from setuptools import setup, find_packages

setup(name='litedesk-lib-active_directory',
    version='0.0.1',
    description='Active Directory library for LiteDesk',
    author='Łukasz Biernot',
    author_email='lukasz.biernot@lgmail.com',
    url='http://laboratories.telekom.com',
    packages=find_packages(),
    package_dir={
        'litedesk.lib.active_directory': 'src/litedesk/lib/active_directory',
        'litedesk.lib.active_directory.classes': 'src/litedesk/lib/active_directory/classes',
    },
    namespace_packages=['litedesk', 'litedesk.lib'],
    install_requires=['python-ldap', ],
    zip_safe=False,
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache License 2.0',
        'Operating System :: Linux',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Programming Language :: Python',
    ],
    keywords='litedesk active_directory',
)
<|endoftext|>


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

from distutils.core import setup
from os.path import abspath, dirname, join
import re

NAME = 'dbbot'
CLASSIFIERS = """
Development Status :: 4 - Beta
License :: OSI Approved :: Apache Software License
Operating System :: OS Independent
Programming Language :: Python
Topic :: Software Development :: Testing
""".strip().splitlines()
CURDIR = dirname(abspath(__file__))
with open(join(CURDIR, NAME, '__init__.py')) as f:
    VERSION = re.search("\n__version__ = '(.*)'\n", f.read()).group(1)
with open(join(CURDIR, 'README.rst')) as f:
    README = f.read()

setup(
    name             = NAME,
    version          = VERSION,
    author           = 'Robot Framework Developers',
    author_email     = 'robotframework@gmail.com',
    url              = 'TODO',
    download_url     = 'TODO',
    license          = 'Apache License 2.0',
    description      = 'A tool for serializing Robot Framework test run '
                       'results into an sqlite3 database.',
    long_description = README,
    keywords         = 'robotframework testing testautomation atdd',
    platforms        = 'any',
    classifiers      = CLASSIFIERS,
    packages         = ['dbbot', 'dbbot.reader'],
    install_requires = ['robotframework']
)
<commit_msg>added URLs to setup.py<commit_after>#!/usr/bin/env python

from distutils.core import setup
from os.path import abspath, dirname, join
import re

NAME = 'dbbot'
CLASSIFIERS = """
Development Status :: 4 - Beta
License :: OSI Approved :: Apache Software License
Operating System :: OS Independent
Programming Language :: Python
Topic :: Software Development :: Testing
""".strip().splitlines()
CURDIR = dirname(abspath(__file__))
with open(join(CURDIR, NAME, '__init__.py')) as f:
    VERSION = re.search("\n__version__ = '(.*)'\n", f.read()).group(1)
with open(join(CURDIR, 'README.rst')) as f:
    README = f.read()

setup(
    name             = NAME,
    version          = VERSION,
    author           = 'Robot Framework Developers',
    author_email     = 'robotframework@gmail.com',
    url              = 'https://github.com/robotframework/DbBot',
    download_url     = 'https://pypi.python.org/pypi/dbbot',
    license          = 'Apache License 2.0',
    description      = 'A tool for serializing Robot Framework test run '
                       'results into an sqlite3 database.',
    long_description = README,
    keywords         = 'robotframework testing testautomation atdd',
    platforms        = 'any',
    classifiers      = CLASSIFIERS,
    packages         = ['dbbot', 'dbbot.reader'],
    install_requires = ['robotframework']
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function

import io
import re
from distutils.command.build import build
from glob import glob
from itertools import chain
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext

from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.easy_install import easy_install
from setuptools.command.install_lib import install_lib

def read(*names, **kwargs):
    with io.open(
        join(dirname(__file__), *names),
        encoding=kwargs.get('encoding', 'utf8')
    ) as fh:
        return fh.read()

class BuildWithPTH(build):
    def run(self, *args, **kwargs):
        build.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.build_lib, basename(path))
        self.copy_file(path, dest)

class EasyInstallWithPTH(easy_install):
    def run(self, *args, **kwargs):
        easy_install.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.install_dir, basename(path))
        self.copy_file(path, dest)

class InstallLibWithPTH(install_lib):
    def run(self, *args, **kwargs):
        install_lib.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.install_dir, basename(path))
        self.copy_file(path, dest)
        self.outputs = [dest]

    def get_outputs(self):
        return chain(install_lib.get_outputs(self), self.outputs)

class DevelopWithPTH(develop):
    def run(self, *args, **kwargs):
        develop.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.install_dir, basename(path))
        self.copy_file(path, dest)

class GeneratePTH(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        with open(join(dirname(__file__), 'src', 'pytest-cov.pth'), 'w') as fh:
            with open(join(dirname(__file__), 'src', 'pytest-cov.embed')) as sh:
                fh.write(
                    'import os, sys;'
                    'exec(%r)' % sh.read().replace('    ', ' ')
                )

setup(
    name='pytest-cov',
    version='2.12.1',
    license='MIT',
    description='Pytest plugin for measuring coverage.',
    long_description='%s\n%s' % (read('README.rst'), re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst'))),
    author='Marc Schlaich',
    author_email='marc.schlaich@gmail.com',
    url='https://github.com/pytest-dev/pytest-cov',
    packages=find_packages('src'),
    package_dir={'': 'src'},
    py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],
    include_package_data=True,
    zip_safe=False,
    classifiers=[
        # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 5 - Production/Stable',
        'Framework :: Pytest',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Testing',
        'Topic :: Utilities',
    ],
    keywords=[
        'cover', 'coverage', 'pytest', 'py.test', 'distributed', 'parallel',
    ],
    install_requires=[
        'pytest>=4.6',
        'coverage[toml]>=5.2.1'
    ],
    python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',
    extras_require={
        'testing': [
            'fields',
            'hunter',
            'process-tests',
            'six',
            'pytest-xdist',
            'virtualenv',
        ]
    },
    entry_points={
        'pytest11': [
            'pytest_cov = pytest_cov.plugin',
        ],
    },
    cmdclass={
        'build': BuildWithPTH,
        'easy_install': EasyInstallWithPTH,
        'install_lib': InstallLibWithPTH,
        'develop': DevelopWithPTH,
        'genpth': GeneratePTH,
    },
)
<commit_msg>Add Python 3.9 to trove classifiers (#481)<commit_after>#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function

import io
import re
from distutils.command.build import build
from glob import glob
from itertools import chain
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext

from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.easy_install import easy_install
from setuptools.command.install_lib import install_lib

def read(*names, **kwargs):
    with io.open(
        join(dirname(__file__), *names),
        encoding=kwargs.get('encoding', 'utf8')
    ) as fh:
        return fh.read()

class BuildWithPTH(build):
    def run(self, *args, **kwargs):
        build.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.build_lib, basename(path))
        self.copy_file(path, dest)

class EasyInstallWithPTH(easy_install):
    def run(self, *args, **kwargs):
        easy_install.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.install_dir, basename(path))
        self.copy_file(path, dest)

class InstallLibWithPTH(install_lib):
    def run(self, *args, **kwargs):
        install_lib.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.install_dir, basename(path))
        self.copy_file(path, dest)
        self.outputs = [dest]

    def get_outputs(self):
        return chain(install_lib.get_outputs(self), self.outputs)

class DevelopWithPTH(develop):
    def run(self, *args, **kwargs):
        develop.run(self, *args, **kwargs)
        path = join(dirname(__file__), 'src', 'pytest-cov.pth')
        dest = join(self.install_dir, basename(path))
        self.copy_file(path, dest)

class GeneratePTH(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        with open(join(dirname(__file__), 'src', 'pytest-cov.pth'), 'w') as fh:
            with open(join(dirname(__file__), 'src', 'pytest-cov.embed')) as sh:
                fh.write(
                    'import os, sys;'
                    'exec(%r)' % sh.read().replace('    ', ' ')
                )

setup(
    name='pytest-cov',
    version='2.12.1',
    license='MIT',
    description='Pytest plugin for measuring coverage.',
    long_description='%s\n%s' % (read('README.rst'), re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst'))),
    author='Marc Schlaich',
    author_email='marc.schlaich@gmail.com',
    url='https://github.com/pytest-dev/pytest-cov',
    packages=find_packages('src'),
    package_dir={'': 'src'},
    py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],
    include_package_data=True,
    zip_safe=False,
    classifiers=[
        # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 5 - Production/Stable',
        'Framework :: Pytest',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Testing',
        'Topic :: Utilities',
    ],
    keywords=[
        'cover', 'coverage', 'pytest', 'py.test', 'distributed', 'parallel',
    ],
    install_requires=[
        'pytest>=4.6',
        'coverage[toml]>=5.2.1'
    ],
    python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',
    extras_require={
        'testing': [
            'fields',
            'hunter',
            'process-tests',
            'six',
            'pytest-xdist',
            'virtualenv',
        ]
    },
    entry_points={
        'pytest11': [
            'pytest_cov = pytest_cov.plugin',
        ],
    },
    cmdclass={
        'build': BuildWithPTH,
        'easy_install': EasyInstallWithPTH,
        'install_lib': InstallLibWithPTH,
        'develop': DevelopWithPTH,
        'genpth': GeneratePTH,
    },
)
<|endoftext|>


<commit_before>from re import sub

from setuptools import setup
import os

def get_long_description():
    # Fix display issues on PyPI caused by RST markup
    readme = open('README.rst').read()

    version_lines = []
    with open('docs/versions.rst') as infile:
        next(infile)
        for line in infile:
            line = line.rstrip().replace('.. automodule:: more_itertools', '')
            version_lines.append(line)
    version_history = '\n'.join(version_lines)
    version_history = sub(r':func:`([a-zA-Z0-9._]+)`', r'\1', version_history)

    ret = readme + '\n\n' + version_history
    return ret

def find_incl_stub_files():
    result = []
    for root, dirs, files in os.walk('more_itertools'):
        for file in files:
            if file.endswith('.pyi') or file.endswith('.py'):
                if os.path.sep in root:
                    sub_root = root.split(os.path.sep, 1)[-1]
                    file = os.path.join(sub_root, file)
                result.append(file)
    return result

setup(
    name='more-itertools',
    version='7.2.0',
    description='More routines for operating on iterables, beyond itertools',
    long_description=get_long_description(),
    author='Erik Rose',
    author_email='erikrose@grinchcentral.com',
    license='MIT',
    packages=['more_itertools'],
    python_requires='>=3.5',
    test_suite='tests',
    url='https://github.com/erikrose/more-itertools',
    include_package_data=True,
    package_data={'more_itertools': find_incl_stub_files()},
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Libraries'],
    keywords=['itertools', 'iterator', 'iteration', 'filter', 'peek',
              'peekable', 'collate', 'chunk', 'chunked'],
)
<commit_msg>Use static list of typing files<commit_after>from re import sub

from setuptools import setup

def get_long_description():
    # Fix display issues on PyPI caused by RST markup
    readme = open('README.rst').read()

    version_lines = []
    with open('docs/versions.rst') as infile:
        next(infile)
        for line in infile:
            line = line.rstrip().replace('.. automodule:: more_itertools', '')
            version_lines.append(line)
    version_history = '\n'.join(version_lines)
    version_history = sub(r':func:`([a-zA-Z0-9._]+)`', r'\1', version_history)

    ret = readme + '\n\n' + version_history
    return ret

setup(
    name='more-itertools',
    version='7.2.0',
    description='More routines for operating on iterables, beyond itertools',
    long_description=get_long_description(),
    author='Erik Rose',
    author_email='erikrose@grinchcentral.com',
    license='MIT',
    packages=['more_itertools'],
    package_data={'more_itertools': ['py.typed', 'recipes.pyi', 'more.pyi']},
    python_requires='>=3.5',
    test_suite='tests',
    url='https://github.com/erikrose/more-itertools',
    include_package_data=True,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Libraries'],
    keywords=['itertools', 'iterator', 'iteration', 'filter', 'peek',
              'peekable', 'collate', 'chunk', 'chunked'],
)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from os import path, chdir, pardir
from setuptools import setup, find_packages

README = open(path.join(path.dirname(__file__), 'README.rst')).read()

# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))

setup(
    name="django-onfido",
    version="0.4.1",
    packages=find_packages(),
    install_requires=[
        'django>=1.8',
        'requests>=2',
        'python-dateutil'
    ],
    include_package_data=True,
    description='Django app for integration with Onfido.',
    long_description=README,
    url='https://github.com/yunojuno/django-onfido',
    author='Hugo Rodger-Brown',
    author_email='code@yunojuno.com',
    maintainer='Hugo Rodger-Brown',
    maintainer_email='hugo@yunojuno.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)
<commit_msg>Bump version to v0.4.2<commit_after># -*- coding: utf-8 -*-
from os import path, chdir, pardir
from setuptools import setup, find_packages

README = open(path.join(path.dirname(__file__), 'README.rst')).read()

# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))

setup(
    name="django-onfido",
    version="0.4.2",
    packages=find_packages(),
    install_requires=[
        'django>=1.8',
        'requests>=2',
        'python-dateutil'
    ],
    include_package_data=True,
    description='Django app for integration with Onfido.',
    long_description=README,
    url='https://github.com/yunojuno/django-onfido',
    author='Hugo Rodger-Brown',
    author_email='code@yunojuno.com',
    maintainer='Hugo Rodger-Brown',
    maintainer_email='hugo@yunojuno.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
from setuptools.command.install import install as _install
from setuptools.command.bdist_egg import bdist_egg as _bdist_egg
from setuptools import setup, find_packages, Command
import os
import zipfile
import urllib.request
import sys
import shutil

CURRENT_VERSION = '9.50.0'

# NOTE: Why we don’t use the the PyPi package:
# <https://code.google.com/p/apsw/source/detail?r=358a9623d051>
class install_apsw(Command):
    description = "Install APSW 3.8.7.3-r1 with the appropriate version of SQLite"
    user_options = []

    def initialize_options(self):
        pass
    def finalize_options(self):
        pass

    def run(self):
        # In Windows APSW should be installed manually
        if os.name == 'nt':
            print('To complete the installation you have to install APSW: https://github.com/rogerbinns/apsw/releases');
            return

        try:
            import apsw
            return
        except:
            pass

        print("downloading apsw.")
        urllib.request.urlretrieve('https://github.com/rogerbinns/apsw/archive/3.8.7.3-r1.zip', 'apsw-3.8.7.3-r1.zip')

        print("extracting.")
        with zipfile.ZipFile('apsw-3.8.7.3-r1.zip', 'r') as zip_file:
            zip_file.extractall()

        executable = sys.executable
        if executable is None:
            executable = "python"

        print("install apsw.")
        install_command = ('cd apsw-3.8.7.3-r1 && {executable} '
          'setup.py fetch --version=3.8.7.3 --all build '
          '--enable-all-extensions install'.format(executable=executable)
        )
        os.system(install_command)

        print("clean files.")
        shutil.rmtree('apsw-3.8.7.3-r1')
        os.remove('apsw-3.8.7.3-r1.zip')

class install_serpent(Command):
    description = "Install Ethereum Serpent"
    user_options = []

    def initialize_options(self):
        pass
    def finalize_options(self):
        pass

    def run(self):
        # In Windows Serpent should be installed manually
        if os.name == 'nt':
            print('To complete the installation you have to install Serpent: https://github.com/ethereum/serpent');
            return

        print("downloading serpent.")
        urllib.request.urlretrieve('https://github.com/ethereum/serpent/archive/master.zip', 'serpent.zip')

        print("extracting.")
        with zipfile.ZipFile('serpent.zip', 'r') as zip_file:
            zip_file.extractall()

        print("making serpent.")
        os.system('cd serpent-master && make')
        print("install serpent using sudo.")
        print("hence it might request a password.")
        os.system('cd serpent-master && sudo make install')

        print("clean files.")
        shutil.rmtree('serpent-master')
        os.remove('serpent.zip')

class move_old_db(Command):
    description = "Move database from old to new default data directory"
    user_options = []

    def initialize_options(self):
        pass
    def finalize_options(self):
        pass

    def run(self):
        import appdirs
        from counterpartylib.lib import config

        old_data_dir = appdirs.user_config_dir(appauthor='Counterparty', appname='counterpartyd', roaming=True)
        old_database = os.path.join(old_data_dir, 'counterpartyd.9.db')
        old_database_testnet = os.path.join(old_data_dir, 'counterpartyd.9.testnet.db')

        new_data_dir = appdirs.user_data_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)
        new_database = os.path.join(new_data_dir, '{}.db'.format(config.APP_NAME))
        new_database_testnet = os.path.join(new_data_dir, '{}.testnet.db'.format(config.APP_NAME))

        # User have an old version of `counterpartyd`
        if os.path.exists(old_data_dir):
            # Move database
            if not os.path.exists(new_data_dir):
                os.makedirs(new_data_dir)
                files_to_copy = {
                    old_database: new_database,
                    old_database_testnet: new_database_testnet
                }
                for src_file in files_to_copy:
                    if os.path.exists(src_file):
                        dest_file = files_to_copy[src_file]
                        print('Copy {} to {}'.format(src_file, dest_file))
                        shutil.copy(src_file, dest_file)

def post_install(cmd, install_serpent=False):
    cmd.run_command('install_apsw')
    if install_serpent:
        cmd.run_command('install_serpent')
    cmd.run_command('move_old_db')

class install(_install):
    user_options = _install.user_options + [
        ("with-serpent", None, "Install Ethereum Serpent"),
    ]
    boolean_options = _install.boolean_options + ['with-serpent']

    def initialize_options(self):
        self.with_serpent = False
        _install.initialize_options(self)

    def run(self):
        caller = sys._getframe(2)
        caller_module = caller.f_globals.get('__name__','')
        caller_name = caller.f_code.co_name
        if caller_module == 'distutils.dist' or caller_name == 'run_commands':
            _install.run(self)
        else:
            self.do_egg_install()
        post_install(self, self.with_serpent)

class bdist_egg(_bdist_egg):
    def run(self):
        _bdist_egg.run(self)
        post_install(self, False)

required_packages = [
    'appdirs',
    'python-dateutil',
    'Flask-HTTPAuth',
    'Flask',
    'json-rpc',
    'pytest',
    'pytest-cov',
    'pycoin',
    'requests',
    'tornado',
    'pycrypto',
    'tendo',
    'pysha3',
    'colorlog',
    'python-bitcoinlib',
    'xmltodict'
]

setup_options = {
    'name': 'counterparty-lib',
    'version': CURRENT_VERSION,
    'author': 'Counterparty Foundation',
    'author_email': 'support@counterparty.io',
    'maintainer': 'Adam Krellenstein',
    'maintainer_email': 'adamk@counterparty.io',
    'url': 'http://counterparty.io',
    'license': 'MIT',
    'description': 'Counterparty Protocol Reference Implementation',
    'keywords': 'counterparty, bitcoin',
    'classifiers': [
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Intended Audience :: Financial and Insurance Industry",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 3 :: Only ",
        "Topic :: Office/Business :: Financial",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: System :: Distributed Computing"
    ],
    'download_url': 'https://github.com/CounterpartyXCP/counterpartyd/releases/tag/v' + CURRENT_VERSION,
    'provides': ['counterpartylib'],
    'packages': find_packages(),
    'zip_safe': False,
    'setup_requires': ['appdirs'],
    'install_requires': required_packages,
    'include_package_data': True,
    'cmdclass': {
        'install': install,
        'move_old_db': move_old_db,
        'install_apsw': install_apsw,
        'install_serpent': install_serpent
    }
}

if sys.argv[1] == 'sdist':
    setup_options['long_description_markdown_filename'] = 'README.md'
    setup_options['setup_requires'].append('setuptools-markdown')

setup(**setup_options)
<commit_msg>Combine Duplicate Version Strings<commit_after>#!/usr/bin/env python
from setuptools.command.install import install as _install
from setuptools.command.bdist_egg import bdist_egg as _bdist_egg
from setuptools import setup, find_packages, Command
import os
import zipfile
import urllib.request
import sys
import shutil

from counterpartylib.lib import config

CURRENT_VERSION = config.VERSION_STRING

# NOTE: Why we don’t use the the PyPi package:
# <https://code.google.com/p/apsw/source/detail?r=358a9623d051>
class install_apsw(Command):
    description = "Install APSW 3.8.7.3-r1 with the appropriate version of SQLite"
    user_options = []

    def initialize_options(self):
        pass
    def finalize_options(self):
        pass

    def run(self):
        # In Windows APSW should be installed manually
        if os.name == 'nt':
            print('To complete the installation you have to install APSW: https://github.com/rogerbinns/apsw/releases');
            return

        try:
            import apsw
            return
        except:
            pass

        print("downloading apsw.")
        urllib.request.urlretrieve('https://github.com/rogerbinns/apsw/archive/3.8.7.3-r1.zip', 'apsw-3.8.7.3-r1.zip')

        print("extracting.")
        with zipfile.ZipFile('apsw-3.8.7.3-r1.zip', 'r') as zip_file:
            zip_file.extractall()

        executable = sys.executable
        if executable is None:
            executable = "python"

        print("install apsw.")
        install_command = ('cd apsw-3.8.7.3-r1 && {executable} '
          'setup.py fetch --version=3.8.7.3 --all build '
          '--enable-all-extensions install'.format(executable=executable)
        )
        os.system(install_command)

        print("clean files.")
        shutil.rmtree('apsw-3.8.7.3-r1')
        os.remove('apsw-3.8.7.3-r1.zip')

class install_serpent(Command):
    description = "Install Ethereum Serpent"
    user_options = []

    def initialize_options(self):
        pass
    def finalize_options(self):
        pass

    def run(self):
        # In Windows Serpent should be installed manually
        if os.name == 'nt':
            print('To complete the installation you have to install Serpent: https://github.com/ethereum/serpent');
            return

        print("downloading serpent.")
        urllib.request.urlretrieve('https://github.com/ethereum/serpent/archive/master.zip', 'serpent.zip')

        print("extracting.")
        with zipfile.ZipFile('serpent.zip', 'r') as zip_file:
            zip_file.extractall()

        print("making serpent.")
        os.system('cd serpent-master && make')
        print("install serpent using sudo.")
        print("hence it might request a password.")
        os.system('cd serpent-master && sudo make install')

        print("clean files.")
        shutil.rmtree('serpent-master')
        os.remove('serpent.zip')

class move_old_db(Command):
    description = "Move database from old to new default data directory"
    user_options = []

    def initialize_options(self):
        pass
    def finalize_options(self):
        pass

    def run(self):
        import appdirs

        old_data_dir = appdirs.user_config_dir(appauthor='Counterparty', appname='counterpartyd', roaming=True)
        old_database = os.path.join(old_data_dir, 'counterpartyd.9.db')
        old_database_testnet = os.path.join(old_data_dir, 'counterpartyd.9.testnet.db')

        new_data_dir = appdirs.user_data_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)
        new_database = os.path.join(new_data_dir, '{}.db'.format(config.APP_NAME))
        new_database_testnet = os.path.join(new_data_dir, '{}.testnet.db'.format(config.APP_NAME))

        # User have an old version of `counterpartyd`
        if os.path.exists(old_data_dir):
            # Move database
            if not os.path.exists(new_data_dir):
                os.makedirs(new_data_dir)
                files_to_copy = {
                    old_database: new_database,
                    old_database_testnet: new_database_testnet
                }
                for src_file in files_to_copy:
                    if os.path.exists(src_file):
                        dest_file = files_to_copy[src_file]
                        print('Copy {} to {}'.format(src_file, dest_file))
                        shutil.copy(src_file, dest_file)

def post_install(cmd, install_serpent=False):
    cmd.run_command('install_apsw')
    if install_serpent:
        cmd.run_command('install_serpent')
    cmd.run_command('move_old_db')

class install(_install):
    user_options = _install.user_options + [
        ("with-serpent", None, "Install Ethereum Serpent"),
    ]
    boolean_options = _install.boolean_options + ['with-serpent']

    def initialize_options(self):
        self.with_serpent = False
        _install.initialize_options(self)

    def run(self):
        caller = sys._getframe(2)
        caller_module = caller.f_globals.get('__name__','')
        caller_name = caller.f_code.co_name
        if caller_module == 'distutils.dist' or caller_name == 'run_commands':
            _install.run(self)
        else:
            self.do_egg_install()
        post_install(self, self.with_serpent)

class bdist_egg(_bdist_egg):
    def run(self):
        _bdist_egg.run(self)
        post_install(self, False)

required_packages = [
    'appdirs',
    'python-dateutil',
    'Flask-HTTPAuth',
    'Flask',
    'json-rpc',
    'pytest',
    'pytest-cov',
    'pycoin',
    'requests',
    'tornado',
    'pycrypto',
    'tendo',
    'pysha3',
    'colorlog',
    'python-bitcoinlib',
    'xmltodict'
]

setup_options = {
    'name': 'counterparty-lib',
    'version': CURRENT_VERSION,
    'author': 'Counterparty Foundation',
    'author_email': 'support@counterparty.io',
    'maintainer': 'Adam Krellenstein',
    'maintainer_email': 'adamk@counterparty.io',
    'url': 'http://counterparty.io',
    'license': 'MIT',
    'description': 'Counterparty Protocol Reference Implementation',
    'keywords': 'counterparty, bitcoin',
    'classifiers': [
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Intended Audience :: Financial and Insurance Industry",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 3 :: Only ",
        "Topic :: Office/Business :: Financial",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: System :: Distributed Computing"
    ],
    'download_url': 'https://github.com/CounterpartyXCP/counterpartyd/releases/tag/v' + CURRENT_VERSION,
    'provides': ['counterpartylib'],
    'packages': find_packages(),
    'zip_safe': False,
    'setup_requires': ['appdirs'],
    'install_requires': required_packages,
    'include_package_data': True,
    'cmdclass': {
        'install': install,
        'move_old_db': move_old_db,
        'install_apsw': install_apsw,
        'install_serpent': install_serpent
    }
}

if sys.argv[1] == 'sdist':
    setup_options['long_description_markdown_filename'] = 'README.md'
    setup_options['setup_requires'].append('setuptools-markdown')

setup(**setup_options)
<|endoftext|>