#!/usr/bin/env python

"""Setup script for PythonTemplateDemo."""

import setuptools

from demo import __project__, __version__

try:
    README = open("README.rst").read()
    CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
    LONG_DESCRIPTION = "<placeholder>"
else:
    LONG_DESCRIPTION = README + '\n' + CHANGELOG

setuptools.setup(
    name=__project__,
    version=__version__,

    description="A sample project templated from jacebrowning/template-python.",
    url='https://github.com/jacebrowning/template-python-demo',
    author='Jace Browning',
    author_email='jacebrowning@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=LONG_DESCRIPTION,
    license='MIT',
    classifiers=[
        # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    install_requires=open("requirements.txt").readlines(),
)

Deploy Travis CI build 720 to GitHub

Deploy Travis CI build 720 to GitHub

Response:
<REPLACE_OLD> "<file not found>"
else:
 <REPLACE_NEW> "<placeholder>"
else:
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

"""Setup script for PythonTemplateDemo."""

import setuptools

from demo import __project__, __version__

try:
    README = open("README.rst").read()
    CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
    LONG_DESCRIPTION = "<placeholder>"
else:
    LONG_DESCRIPTION = README + '\n' + CHANGELOG

setuptools.setup(
    name=__project__,
    version=__version__,

    description="A sample project templated from jacebrowning/template-python.",
    url='https://github.com/jacebrowning/template-python-demo',
    author='Jace Browning',
    author_email='jacebrowning@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=LONG_DESCRIPTION,
    license='MIT',
    classifiers=[
        # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    install_requires=open("requirements.txt").readlines(),
)

Prompt:
Deploy Travis CI build 720 to GitHub

#!/usr/bin/env python

"""Setup script for PythonTemplateDemo."""

import setuptools

from demo import __project__, __version__

try:
    README = open("README.rst").read()
    CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
    LONG_DESCRIPTION = "<file not found>"
else:
    LONG_DESCRIPTION = README + '\n' + CHANGELOG

setuptools.setup(
    name=__project__,
    version=__version__,

    description="A sample project templated from jacebrowning/template-python.",
    url='https://github.com/jacebrowning/template-python-demo',
    author='Jace Browning',
    author_email='jacebrowning@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=LONG_DESCRIPTION,
    license='MIT',
    classifiers=[
        # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    install_requires=open("requirements.txt").readlines(),
)


# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
import json

class HathiItems:

    def __init__ (self):
        pass

    def __len__ (self):
        return 0

def get_counts_from_item_list (items, htid):
    a = len([x for x in items if x["htid"] == htid])
    b = len(items) - a

    return a, b

def get_oclc_counts_from_json (json_data, htid = ""):
    try:
        data = json.loads(json_data)
        return get_counts_from_item_list(data["items"], htid)

    except:
        return 0, 0

def get_hathi_data_from_json ():
    return HathiItems()

Response:
<REPLACE_OLD> json

def <REPLACE_NEW> json

class HathiItems:

    def __init__ (self):
        pass

    def __len__ (self):
        return 0

def <REPLACE_END> <REPLACE_OLD> ()
 <REPLACE_NEW> HathiItems()
 <REPLACE_END> <|endoftext|> # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
import json

class HathiItems:

    def __init__ (self):
        pass

    def __len__ (self):
        return 0

def get_counts_from_item_list (items, htid):
    a = len([x for x in items if x["htid"] == htid])
    b = len(items) - a

    return a, b

def get_oclc_counts_from_json (json_data, htid = ""):
    try:
        data = json.loads(json_data)
        return get_counts_from_item_list(data["items"], htid)

    except:
        return 0, 0

def get_hathi_data_from_json ():
    return HathiItems()

Prompt:
Refactor empty tuple into empty object with len()

# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
import json

def get_counts_from_item_list (items, htid):
    a = len([x for x in items if x["htid"] == htid])
    b = len(items) - a

    return a, b

def get_oclc_counts_from_json (json_data, htid = ""):
    try:
        data = json.loads(json_data)
        return get_counts_from_item_list(data["items"], htid)

    except:
        return 0, 0

def get_hathi_data_from_json ():
    return ()


#!/usr/bin/env python2.7
from werkzeug.wrappers import Request, Response

from get_html import get_html, choose_lang

@Request.application
def run(request):
	lang = request.args.get("lang") if request.args.get("lang") else choose_lang(request)
	if request.url.startswith("https://") or request.args.get("forcenossl") == "true":
		html = get_html("launch", lang)
	else:
		html = get_html("nossl", lang)
	return Response(html, mimetype="text/html")

if __name__ == "__main__":
	import CGI
	CGI.app = run
	CGI.run()

Response:
<INSERT> request.args.get("lang") if request.args.get("lang") else <INSERT_END> <|endoftext|> #!/usr/bin/env python2.7
from werkzeug.wrappers import Request, Response

from get_html import get_html, choose_lang

@Request.application
def run(request):
	lang = request.args.get("lang") if request.args.get("lang") else choose_lang(request)
	if request.url.startswith("https://") or request.args.get("forcenossl") == "true":
		html = get_html("launch", lang)
	else:
		html = get_html("nossl", lang)
	return Response(html, mimetype="text/html")

if __name__ == "__main__":
	import CGI
	CGI.app = run
	CGI.run()

Prompt:
Make the language changeable via a GET parameter.

#!/usr/bin/env python2.7
from werkzeug.wrappers import Request, Response

from get_html import get_html, choose_lang

@Request.application
def run(request):
	lang = choose_lang(request)
	if request.url.startswith("https://") or request.args.get("forcenossl") == "true":
		html = get_html("launch", lang)
	else:
		html = get_html("nossl", lang)
	return Response(html, mimetype="text/html")

if __name__ == "__main__":
	import CGI
	CGI.app = run
	CGI.run()


from modularodm import Q

from website.app import init_app
from website.models import User, Node, Institution

def get_institutions():
    institutions = Institution.find(Q('_id', 'ne', None))
    return institutions

def get_user_count_by_institutions():
    institutions = get_institutions()
    user_counts = []
    for institution in institutions:
        query = Q('_affiliated_institutions', 'eq', institution.node)
        user_counts.append({institution.name: User.find(query).count()})
    return user_counts

def get_node_count_by_institutions():
    institutions = get_institutions()
    node_counts = []
    for institution in institutions:
        query = (
            Q('is_deleted', 'ne', True) &
            Q('is_folder', 'ne', True) &
            Q('parent_node', 'eq', None)
        )
        node_counts.append({institution.name: Node.find_by_institutions(institution, query).count()})
    return node_counts

def main():
    users_by_institutions = get_user_count_by_institutions()
    nodes_by_institutions = get_node_count_by_institutions()
    print(users_by_institutions)
    print(nodes_by_institutions)

if __name__ == '__main__':
    init_app()
    main()

Add basic script without the ability to send the data anywhere

Response:
<REPLACE_OLD>  <REPLACE_NEW> from modularodm import Q

from website.app import init_app
from website.models import User, Node, Institution

def get_institutions():
    institutions = Institution.find(Q('_id', 'ne', None))
    return institutions

def get_user_count_by_institutions():
    institutions = get_institutions()
    user_counts = []
    for institution in institutions:
        query = Q('_affiliated_institutions', 'eq', institution.node)
        user_counts.append({institution.name: User.find(query).count()})
    return user_counts

def get_node_count_by_institutions():
    institutions = get_institutions()
    node_counts = []
    for institution in institutions:
        query = (
            Q('is_deleted', 'ne', True) &
            Q('is_folder', 'ne', True) &
            Q('parent_node', 'eq', None)
        )
        node_counts.append({institution.name: Node.find_by_institutions(institution, query).count()})
    return node_counts

def main():
    users_by_institutions = get_user_count_by_institutions()
    nodes_by_institutions = get_node_count_by_institutions()
    print(users_by_institutions)
    print(nodes_by_institutions)

if __name__ == '__main__':
    init_app()
    main()
 <REPLACE_END> <|endoftext|> from modularodm import Q

from website.app import init_app
from website.models import User, Node, Institution

def get_institutions():
    institutions = Institution.find(Q('_id', 'ne', None))
    return institutions

def get_user_count_by_institutions():
    institutions = get_institutions()
    user_counts = []
    for institution in institutions:
        query = Q('_affiliated_institutions', 'eq', institution.node)
        user_counts.append({institution.name: User.find(query).count()})
    return user_counts

def get_node_count_by_institutions():
    institutions = get_institutions()
    node_counts = []
    for institution in institutions:
        query = (
            Q('is_deleted', 'ne', True) &
            Q('is_folder', 'ne', True) &
            Q('parent_node', 'eq', None)
        )
        node_counts.append({institution.name: Node.find_by_institutions(institution, query).count()})
    return node_counts

def main():
    users_by_institutions = get_user_count_by_institutions()
    nodes_by_institutions = get_node_count_by_institutions()
    print(users_by_institutions)
    print(nodes_by_institutions)

if __name__ == '__main__':
    init_app()
    main()

Prompt: Add basic script without the ability to send the data anywhere


import os
import SimpleHTTPServer

class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """
    Overrides the default request handler to handle GitHub custom 404 pages.
    (Pretty much a 404.html page in your root.)

    See https://help.github.com/articles/custom-404-pages

    This currently only works for erroneous pages in the root directory, but
    that's enough to test what the 404 page looks like.

    """
    def do_GET(self):
        path = self.translate_path(self.path)

        # If the path doesn't exist, fake it to be the 404 page.
        if not os.path.exists(path):
            self.path = '404.html'

        # Call the superclass methods to actually serve the page.
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

SimpleHTTPServer.test(GitHubHandler)

Response:
<REPLACE_OLD> self.translate_path(self.path)
        print(self.path)
        print(path)
 <REPLACE_NEW> self.translate_path(self.path)

 <REPLACE_END> <REPLACE_OLD> SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

        print(self.path)
        print(self.translate_path(self.path))

SimpleHTTPServer.test(GitHubHandler)
 <REPLACE_NEW> SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

SimpleHTTPServer.test(GitHubHandler)
 <REPLACE_END> <|endoftext|> import os
import SimpleHTTPServer

class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """
    Overrides the default request handler to handle GitHub custom 404 pages.
    (Pretty much a 404.html page in your root.)

    See https://help.github.com/articles/custom-404-pages

    This currently only works for erroneous pages in the root directory, but
    that's enough to test what the 404 page looks like.

    """
    def do_GET(self):
        path = self.translate_path(self.path)

        # If the path doesn't exist, fake it to be the 404 page.
        if not os.path.exists(path):
            self.path = '404.html'

        # Call the superclass methods to actually serve the page.
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

SimpleHTTPServer.test(GitHubHandler)

Prompt:
Remove some print lines from the fake server.

import os
import SimpleHTTPServer

class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """
    Overrides the default request handler to handle GitHub custom 404 pages.
    (Pretty much a 404.html page in your root.)

    See https://help.github.com/articles/custom-404-pages

    This currently only works for erroneous pages in the root directory, but
    that's enough to test what the 404 page looks like.

    """
    def do_GET(self):
        path = self.translate_path(self.path)
        print(self.path)
        print(path)
        # If the path doesn't exist, fake it to be the 404 page.
        if not os.path.exists(path):
            self.path = '404.html'

        # Call the superclass methods to actually serve the page.
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

        print(self.path)
        print(self.translate_path(self.path))

SimpleHTTPServer.test(GitHubHandler)


from sharepa.search import ShareSearch, basic_search  # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes  # noqa

def source_counts():
    return bucket_to_dataframe(
        'total_source_counts',
        basic_search.execute().aggregations.sourceAgg.buckets
    )

Response:
<REPLACE_OLD> noqa
 <REPLACE_NEW> noqa

def source_counts():
    return bucket_to_dataframe(
        'total_source_counts',
        basic_search.execute().aggregations.sourceAgg.buckets
    )
 <REPLACE_END> <|endoftext|> from sharepa.search import ShareSearch, basic_search  # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes  # noqa

def source_counts():
    return bucket_to_dataframe(
        'total_source_counts',
        basic_search.execute().aggregations.sourceAgg.buckets
    )

Prompt:
Make it so that source_counts is only executed on purpose

from sharepa.search import ShareSearch, basic_search  # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes  # noqa


# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Hugo Santos
#    Copyright 2015 FactorLibre
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name': 'Sale Order Add Variants',
    'summary': 'Add variants from template into sale order',
    'version': '0.1',
    'author': 'FactorLibre,Odoo Community Association (OCA)',
    'category': 'Sale',
    'license': 'AGPL-3',
    'website': 'http://factorlibre.com',
    'depends': [
        'sale'
    ],
    'demo': [],
    'data': [
        'security/sale_order_add_variants_security.xml',
        'view/sale_add_variants_view.xml',
        'view/sale_view.xml',
        'view/res_config_view.xml'
    ],
    'installable': True
}

Fix typo in author FactorLibre

Fix typo in author FactorLibre

Response:
<REPLACE_OLD> 'Factorlibre,Odoo <REPLACE_NEW> 'FactorLibre,Odoo <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Hugo Santos
#    Copyright 2015 FactorLibre
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name': 'Sale Order Add Variants',
    'summary': 'Add variants from template into sale order',
    'version': '0.1',
    'author': 'FactorLibre,Odoo Community Association (OCA)',
    'category': 'Sale',
    'license': 'AGPL-3',
    'website': 'http://factorlibre.com',
    'depends': [
        'sale'
    ],
    'demo': [],
    'data': [
        'security/sale_order_add_variants_security.xml',
        'view/sale_add_variants_view.xml',
        'view/sale_view.xml',
        'view/res_config_view.xml'
    ],
    'installable': True
}

Prompt:
Fix typo in author FactorLibre

# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Hugo Santos
#    Copyright 2015 FactorLibre
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name': 'Sale Order Add Variants',
    'summary': 'Add variants from template into sale order',
    'version': '0.1',
    'author': 'Factorlibre,Odoo Community Association (OCA)',
    'category': 'Sale',
    'license': 'AGPL-3',
    'website': 'http://factorlibre.com',
    'depends': [
        'sale'
    ],
    'demo': [],
    'data': [
        'security/sale_order_add_variants_security.xml',
        'view/sale_add_variants_view.xml',
        'view/sale_view.xml',
        'view/res_config_view.xml'
    ],
    'installable': True
}


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

from setuptools import setup

setup(
    name='yg.emanate',
    use_scm_version=True,
    description="Lightweight event system for Python",
    author="YouGov, plc",
    author_email='dev@yougov.com',
    url='https://github.com/yougov/yg.emanate',
    packages=[
        'yg.emanate',
    ],
    namespace_packages=['yg'],
    include_package_data=True,
    setup_requires=['setuptools_scm>=1.15'],
    keywords='emanate',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
    ],
    test_suite='tests',
    python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
)

Response:
<DELETE>    zip_safe=False,
 <DELETE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

setup(
    name='yg.emanate',
    use_scm_version=True,
    description="Lightweight event system for Python",
    author="YouGov, plc",
    author_email='dev@yougov.com',
    url='https://github.com/yougov/yg.emanate',
    packages=[
        'yg.emanate',
    ],
    namespace_packages=['yg'],
    include_package_data=True,
    setup_requires=['setuptools_scm>=1.15'],
    keywords='emanate',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
    ],
    test_suite='tests',
    python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
)

Prompt:
Remove deprecated 'zip_safe' flag. It's probably safe anyhow.

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

from setuptools import setup

setup(
    name='yg.emanate',
    use_scm_version=True,
    description="Lightweight event system for Python",
    author="YouGov, plc",
    author_email='dev@yougov.com',
    url='https://github.com/yougov/yg.emanate',
    packages=[
        'yg.emanate',
    ],
    namespace_packages=['yg'],
    include_package_data=True,
    setup_requires=['setuptools_scm>=1.15'],
    zip_safe=False,
    keywords='emanate',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
    ],
    test_suite='tests',
    python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
)


import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'pyramid',
    'pyramid_zodbconn',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'ZODB3',
    'waitress',
    'repoze.folder',
    'zope.interface',
    'requests',
    ]

setup(name='push-hub',
      version='0.2',
      description='push-hub',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pylons pyramid',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires = requires,
      tests_require= requires,
      test_suite="pushhub",
      entry_points = """\
      [paste.app_factory]
      main = pushhub:main
      """,
      )

Response:
<REPLACE_OLD> 'requests==0.14.0',
 <REPLACE_NEW> 'requests',
 <REPLACE_END> <|endoftext|> import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'pyramid',
    'pyramid_zodbconn',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'ZODB3',
    'waitress',
    'repoze.folder',
    'zope.interface',
    'requests',
    ]

setup(name='push-hub',
      version='0.2',
      description='push-hub',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pylons pyramid',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires = requires,
      tests_require= requires,
      test_suite="pushhub",
      entry_points = """\
      [paste.app_factory]
      main = pushhub:main
      """,
      )

Prompt:
Move requests pin to versions.cfg in buildout

import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'pyramid',
    'pyramid_zodbconn',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'ZODB3',
    'waitress',
    'repoze.folder',
    'zope.interface',
    'requests==0.14.0',
    ]

setup(name='push-hub',
      version='0.2',
      description='push-hub',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pylons pyramid',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires = requires,
      tests_require= requires,
      test_suite="pushhub",
      entry_points = """\
      [paste.app_factory]
      main = pushhub:main
      """,
      )


#!/usr/bin/env python

import os, sys, glob, subprocess
from setuptools import setup, find_packages

try:
    version = subprocess.check_output(["git", "describe", "--tags", "--match", "v*.*.*"]).strip("v\n")
except:
    version = "0.0.0"

setup(
    name='aegea',
    version=version,
    url='https://github.com/kislyuk/aegea',
    license=open('LICENSE.md').readline().strip(),
    author='Andrey Kislyuk',
    author_email='kislyuk@gmail.com',
    description='Amazon Web Services Operator Interface',
    long_description=open('README.rst').read(),
    install_requires=[
        'setuptools',
        'boto3 >= 1.3.0',
        'argcomplete >= 1.1.0',
        'paramiko >= 1.16.0',
        'requests >= 2.9.1',
        'tweak >= 0.3.2',
        'keymaker >= 0.1.7',
        'pyyaml >= 3.11',
        'python-dateutil >= 2.1'
    ],
    extras_require={
        ':python_version == "2.7"': [
            'enum34 >= 1.0.4',
            'ipaddress >= 1.0.16',
            'backports.statistics >= 0.1.0'
        ]
    },
    packages=find_packages(exclude=['test']),
    scripts=glob.glob('scripts/*'),
    platforms=['MacOS X', 'Posix'],
    test_suite='test',
    include_package_data=True
)

Use git describe output for version

Use git describe output for version

Response:
<REPLACE_OLD> glob
from <REPLACE_NEW> glob, subprocess
from <REPLACE_END> <REPLACE_OLD> find_packages

setup(
 <REPLACE_NEW> find_packages

try:
    version = subprocess.check_output(["git", "describe", "--tags", "--match", "v*.*.*"]).strip("v\n")
except:
    version = "0.0.0"

setup(
 <REPLACE_END> <REPLACE_OLD> version='0.6.0',
 <REPLACE_NEW> version=version,
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os, sys, glob, subprocess
from setuptools import setup, find_packages

try:
    version = subprocess.check_output(["git", "describe", "--tags", "--match", "v*.*.*"]).strip("v\n")
except:
    version = "0.0.0"

setup(
    name='aegea',
    version=version,
    url='https://github.com/kislyuk/aegea',
    license=open('LICENSE.md').readline().strip(),
    author='Andrey Kislyuk',
    author_email='kislyuk@gmail.com',
    description='Amazon Web Services Operator Interface',
    long_description=open('README.rst').read(),
    install_requires=[
        'setuptools',
        'boto3 >= 1.3.0',
        'argcomplete >= 1.1.0',
        'paramiko >= 1.16.0',
        'requests >= 2.9.1',
        'tweak >= 0.3.2',
        'keymaker >= 0.1.7',
        'pyyaml >= 3.11',
        'python-dateutil >= 2.1'
    ],
    extras_require={
        ':python_version == "2.7"': [
            'enum34 >= 1.0.4',
            'ipaddress >= 1.0.16',
            'backports.statistics >= 0.1.0'
        ]
    },
    packages=find_packages(exclude=['test']),
    scripts=glob.glob('scripts/*'),
    platforms=['MacOS X', 'Posix'],
    test_suite='test',
    include_package_data=True
)

Prompt:
Use git describe output for version

#!/usr/bin/env python

import os, sys, glob
from setuptools import setup, find_packages

setup(
    name='aegea',
    version='0.6.0',
    url='https://github.com/kislyuk/aegea',
    license=open('LICENSE.md').readline().strip(),
    author='Andrey Kislyuk',
    author_email='kislyuk@gmail.com',
    description='Amazon Web Services Operator Interface',
    long_description=open('README.rst').read(),
    install_requires=[
        'setuptools',
        'boto3 >= 1.3.0',
        'argcomplete >= 1.1.0',
        'paramiko >= 1.16.0',
        'requests >= 2.9.1',
        'tweak >= 0.3.2',
        'keymaker >= 0.1.7',
        'pyyaml >= 3.11',
        'python-dateutil >= 2.1'
    ],
    extras_require={
        ':python_version == "2.7"': [
            'enum34 >= 1.0.4',
            'ipaddress >= 1.0.16',
            'backports.statistics >= 0.1.0'
        ]
    },
    packages=find_packages(exclude=['test']),
    scripts=glob.glob('scripts/*'),
    platforms=['MacOS X', 'Posix'],
    test_suite='test',
    include_package_data=True
)


#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.

"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
    import bson
except ImportError:
    raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")

# also update in setup.py
version = "1.3"
version_info = (1, 3)

ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = '{ $meta: "textScore" }'
"""TEXT Index sort order."""

from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
                    DataError, IntegrityError, ProgrammingError, NotSupportedError)

from client import Client

Support Sort Order For TEXT Index

Support Sort Order For TEXT Index

Response:
<REPLACE_OLD> index`"""

from <REPLACE_NEW> index`"""
TEXT = '{ $meta: "textScore" }'
"""TEXT Index sort order."""

from <REPLACE_END> <|endoftext|> #!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.

"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
    import bson
except ImportError:
    raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")

# also update in setup.py
version = "1.3"
version_info = (1, 3)

ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = '{ $meta: "textScore" }'
"""TEXT Index sort order."""

from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
                    DataError, IntegrityError, ProgrammingError, NotSupportedError)

from client import Client

Prompt:
Support Sort Order For TEXT Index

#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.

"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
    import bson
except ImportError:
    raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")

# also update in setup.py
version = "1.3"
version_info = (1, 3)

ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""

from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
                    DataError, IntegrityError, ProgrammingError, NotSupportedError)

from client import Client


Response:
<REPLACE_OLD> app.cmdloop()

 <REPLACE_NEW> app.cmdloop()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2

class UnicodeApp(cmd2.Cmd):
    """Example cmd2 application with unicode command names."""

    def __init__(self):
        super().__init__()
        self.intro = 'Welcome the Unicode example app. Note the full Unicode support:  😇 💩'

    def do_𝛑print(self, _):
        """This command prints 𝛑 to 5 decimal places."""
        self.poutput("𝛑 = {0:.6}".format(math.pi))

    def do_你好(self, arg):
        """This command says hello in Chinese (Mandarin)."""
        self.poutput("你好 " + arg)

if __name__ == '__main__':
    app = UnicodeApp()
    app.cmdloop()

Prompt:
Fix flake8 error due to extra blank line in example

#!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2

class UnicodeApp(cmd2.Cmd):
    """Example cmd2 application with unicode command names."""

    def __init__(self):
        super().__init__()
        self.intro = 'Welcome the Unicode example app. Note the full Unicode support:  😇 💩'

    def do_𝛑print(self, _):
        """This command prints 𝛑 to 5 decimal places."""
        self.poutput("𝛑 = {0:.6}".format(math.pi))

    def do_你好(self, arg):
        """This command says hello in Chinese (Mandarin)."""
        self.poutput("你好 " + arg)

if __name__ == '__main__':
    app = UnicodeApp()
    app.cmdloop()


"""
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""

from setuptools import setup, find_packages  # noqa

setup(
    name='tensorpy',
    version='1.0.1',
    url='http://tensorpy.com',
    author='Michael Mintz',
    author_email='@mintzworld',
    maintainer='Michael Mintz',
    description='The fast & easy way to get started with Tensorflow',
    license='The MIT License',
    install_requires=[
        'requests==2.11.1',
        'six==1.10.0',
        'Pillow==3.4.1',
        'BeautifulSoup==3.2.1',
        ],
    packages=['tensorpy'],
    )

Response:
<REPLACE_OLD> 'six>=1.10.0',
 <REPLACE_NEW> 'six==1.10.0',
 <REPLACE_END> <|endoftext|> """
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""

from setuptools import setup, find_packages  # noqa

setup(
    name='tensorpy',
    version='1.0.1',
    url='http://tensorpy.com',
    author='Michael Mintz',
    author_email='@mintzworld',
    maintainer='Michael Mintz',
    description='The fast & easy way to get started with Tensorflow',
    license='The MIT License',
    install_requires=[
        'requests==2.11.1',
        'six==1.10.0',
        'Pillow==3.4.1',
        'BeautifulSoup==3.2.1',
        ],
    packages=['tensorpy'],
    )

Prompt:
Update the "six" to force version 1.10.0

"""
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""

from setuptools import setup, find_packages  # noqa

setup(
    name='tensorpy',
    version='1.0.1',
    url='http://tensorpy.com',
    author='Michael Mintz',
    author_email='@mintzworld',
    maintainer='Michael Mintz',
    description='The fast & easy way to get started with Tensorflow',
    license='The MIT License',
    install_requires=[
        'requests==2.11.1',
        'six>=1.10.0',
        'Pillow==3.4.1',
        'BeautifulSoup==3.2.1',
        ],
    packages=['tensorpy'],
    )


from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin

class CustomAction(db.Model, BaseMixin, SerializerMixin):
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(400))
    entity_type = db.Column(db.String(40), default="all")

Add entity type column to actions

Add entity type column to actions

Response:
<INSERT>    entity_type = db.Column(db.String(40), default="all")
 <INSERT_END> <|endoftext|> from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin

class CustomAction(db.Model, BaseMixin, SerializerMixin):
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(400))
    entity_type = db.Column(db.String(40), default="all")

Prompt:
Add entity type column to actions

from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin

class CustomAction(db.Model, BaseMixin, SerializerMixin):
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(400))


def verifyUnique(string):
    if len(string) > 128:
        return False
    characterHash = [0] * 128
    for character in string:
        hashKey = ord(character)%128
        if(characterHash[hashKey] > 0):
            return False
        else:
            characterHash[hashKey] = characterHash[hashKey]+1
    return True

print verifyUnique('test') # False ,O(n)
print verifyUnique('aquickboASDFwnfxjmps><verthlzydg')  # True ,O(n)

Verify the given string has unique characters

Response:
<INSERT> def verifyUnique(string):
 <INSERT_END> <INSERT>   if len(string) > 128:
        return False
    characterHash = [0] * 128
    for character in string:
        hashKey = ord(character)%128
        if(characterHash[hashKey] > 0):
            return False
        else:
            characterHash[hashKey] = characterHash[hashKey]+1
    return True

print verifyUnique('test') # False ,O(n)
print verifyUnique('aquickboASDFwnfxjmps><verthlzydg')  # True ,O(n)
 <INSERT_END> <|endoftext|> def verifyUnique(string):
    if len(string) > 128:
        return False
    characterHash = [0] * 128
    for character in string:
        hashKey = ord(character)%128
        if(characterHash[hashKey] > 0):
            return False
        else:
            characterHash[hashKey] = characterHash[hashKey]+1
    return True

print verifyUnique('test') # False ,O(n)
print verifyUnique('aquickboASDFwnfxjmps><verthlzydg')  # True ,O(n)

Prompt: Verify the given string has unique characters


#!/usr/bin/env python
from setuptools import setup

setup(name = 'i2py',
    version = '0.3',
    description = 'Tools to work with i2p.',
    author = 'See contributors.txt',
    author_email = 'Anonymous',
    classifiers = [
    'Development Status :: 3 - Alpha',
    #'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: MIT License',
    'Intended Audience :: Developers',
    'Topic :: Utilities',
    ],
    install_requires = [      # If you plan on adding something, make it known why.
                              # Let's try to keep the dependencies minimal, okay?
    'bunch',                  # Needed by i2py.control.pyjsonrpc.
    'python-geoip',           # Needed by i2py.netdb.
    'python-geoip-geolite2',  # Needed by i2py.netdb.
    ],
    tests_require=['pytest'],
    url = 'https://github.com/chris-barry/i2py',
    packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'],
)

Response:
<REPLACE_OLD> '0.2',
 <REPLACE_NEW> '0.3',
 <REPLACE_END> <REPLACE_OLD> 'contributors.txt',
 <REPLACE_NEW> 'See contributors.txt',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from setuptools import setup

setup(name = 'i2py',
    version = '0.3',
    description = 'Tools to work with i2p.',
    author = 'See contributors.txt',
    author_email = 'Anonymous',
    classifiers = [
    'Development Status :: 3 - Alpha',
    #'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: MIT License',
    'Intended Audience :: Developers',
    'Topic :: Utilities',
    ],
    install_requires = [      # If you plan on adding something, make it known why.
                              # Let's try to keep the dependencies minimal, okay?
    'bunch',                  # Needed by i2py.control.pyjsonrpc.
    'python-geoip',           # Needed by i2py.netdb.
    'python-geoip-geolite2',  # Needed by i2py.netdb.
    ],
    tests_require=['pytest'],
    url = 'https://github.com/chris-barry/i2py',
    packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'],
)

Prompt:
Change version to 0.3 due to functions changing name.

#!/usr/bin/env python
from setuptools import setup

setup(name = 'i2py',
    version = '0.2',
    description = 'Tools to work with i2p.',
    author = 'contributors.txt',
    author_email = 'Anonymous',
    classifiers = [
    'Development Status :: 3 - Alpha',
    #'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: MIT License',
    'Intended Audience :: Developers',
    'Topic :: Utilities',
    ],
    install_requires = [      # If you plan on adding something, make it known why.
                              # Let's try to keep the dependencies minimal, okay?
    'bunch',                  # Needed by i2py.control.pyjsonrpc.
    'python-geoip',           # Needed by i2py.netdb.
    'python-geoip-geolite2',  # Needed by i2py.netdb.
    ],
    tests_require=['pytest'],
    url = 'https://github.com/chris-barry/i2py',
    packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'],
)


#!/usr/bin/env py.test
# -*- coding: utf-8 -*-
# Created on Fri Apr 25 02:33:04 2014
# License is MIT, see COPYING.txt for more details.
# @author: Danilo de Jesus da Silva Bellini

import os, re, pytest
from fractal import generate_fractal, call_kw, cli_parse_args
from io import BytesIO
from pylab import imread, imsave

def show_parameters(fname):
  """ String with CLI args to show the fractal with the given ``fname`` """
  re_complex = re.compile("(?:([+-]?\s*[0-9.]+))?\s*"
                          "(?:([+-]\s*[0-9.]+)\s*)?(.*)")
  def part_generator():
    for part in fname.rsplit(".", 1)[0].split("_"):
      if "=" in part:
        yield "--" + part
      else:
        yield " ".join(filter(lambda x: x, re_complex.match(part).groups()))
    yield "--show"
  return " ".join(part_generator())

def to_dict_params(fname):
  """ Get full kwargs from file name """
  return cli_parse_args(show_parameters(fname).split())

@pytest.mark.parametrize("fname", os.listdir("images"))
def test_file_image(fname):
  ext = os.path.splitext(fname)[-1][len(os.path.extsep):]
  kwargs = to_dict_params(fname)

  # Creates the image in memory
  mem = BytesIO()
  fractal_data = call_kw(generate_fractal, kwargs)
  imsave(mem, fractal_data, cmap=kwargs["cmap"], format=ext)
  mem.seek(0) # Return stream psition back for reading

  # Comparison pixel-by-pixel
  img_file = imread("images/" + fname)
  img_mem = imread(mem, format=ext)
  assert img_file.tolist() == img_mem.tolist()

Test with each example image in the repository

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env py.test
# -*- coding: utf-8 -*-
# Created on Fri Apr 25 02:33:04 2014
# License is MIT, see COPYING.txt for more details.
# @author: Danilo de Jesus da Silva Bellini

import os, re, pytest
from fractal import generate_fractal, call_kw, cli_parse_args
from io import BytesIO
from pylab import imread, imsave

def show_parameters(fname):
  """ String with CLI args to show the fractal with the given ``fname`` """
  re_complex = re.compile("(?:([+-]?\s*[0-9.]+))?\s*"
                          "(?:([+-]\s*[0-9.]+)\s*)?(.*)")
  def part_generator():
    for part in fname.rsplit(".", 1)[0].split("_"):
      if "=" in part:
        yield "--" + part
      else:
        yield " ".join(filter(lambda x: x, re_complex.match(part).groups()))
    yield "--show"
  return " ".join(part_generator())

def to_dict_params(fname):
  """ Get full kwargs from file name """
  return cli_parse_args(show_parameters(fname).split())

@pytest.mark.parametrize("fname", os.listdir("images"))
def test_file_image(fname):
  ext = os.path.splitext(fname)[-1][len(os.path.extsep):]
  kwargs = to_dict_params(fname)

  # Creates the image in memory
  mem = BytesIO()
  fractal_data = call_kw(generate_fractal, kwargs)
  imsave(mem, fractal_data, cmap=kwargs["cmap"], format=ext)
  mem.seek(0) # Return stream psition back for reading

  # Comparison pixel-by-pixel
  img_file = imread("images/" + fname)
  img_mem = imread(mem, format=ext)
  assert img_file.tolist() == img_mem.tolist()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env py.test
# -*- coding: utf-8 -*-
# Created on Fri Apr 25 02:33:04 2014
# License is MIT, see COPYING.txt for more details.
# @author: Danilo de Jesus da Silva Bellini

import os, re, pytest
from fractal import generate_fractal, call_kw, cli_parse_args
from io import BytesIO
from pylab import imread, imsave

def show_parameters(fname):
  """ String with CLI args to show the fractal with the given ``fname`` """
  re_complex = re.compile("(?:([+-]?\s*[0-9.]+))?\s*"
                          "(?:([+-]\s*[0-9.]+)\s*)?(.*)")
  def part_generator():
    for part in fname.rsplit(".", 1)[0].split("_"):
      if "=" in part:
        yield "--" + part
      else:
        yield " ".join(filter(lambda x: x, re_complex.match(part).groups()))
    yield "--show"
  return " ".join(part_generator())

def to_dict_params(fname):
  """ Get full kwargs from file name """
  return cli_parse_args(show_parameters(fname).split())

@pytest.mark.parametrize("fname", os.listdir("images"))
def test_file_image(fname):
  ext = os.path.splitext(fname)[-1][len(os.path.extsep):]
  kwargs = to_dict_params(fname)

  # Creates the image in memory
  mem = BytesIO()
  fractal_data = call_kw(generate_fractal, kwargs)
  imsave(mem, fractal_data, cmap=kwargs["cmap"], format=ext)
  mem.seek(0) # Return stream psition back for reading

  # Comparison pixel-by-pixel
  img_file = imread("images/" + fname)
  img_mem = imread(mem, format=ext)
  assert img_file.tolist() == img_mem.tolist()

Prompt: Test with each example image in the repository


import unittest
import os
import sys
from gitdata import GitData
import simplejson as json

class TestGitData(unittest.TestCase):
    def test_fetch(self):
        gd = GitData(repo="./treenexus")

        study_id = 438
        study_nexson = gd.fetch_study(study_id)
        valid = 1
        try:
            json.loads(study_nexson)
        except:
            valid = 0
        self.assertTrue( valid, "fetch_study(%s) returned valid JSON" % study_id)

    def test_write(self):
        gd = GitData(repo="./treenexus")
        author   = "John Doe <john@doe.com>"
        content  = '{"foo":"bar"}'
        study_id = 9999
        branch   = "johndoe_study_%s" % study_id
        new_sha  = gd.write_study(study_id,content,branch,author)
        self.assertTrue( new_sha != "", "new_sha is non-empty")

    def test_branch_exists(self):
        gd = GitData(repo="./treenexus")
        exists = gd.branch_exists("nothisdoesnotexist")
        self.assertTrue( exists == 0, "branch does not exist")

        exists = gd.branch_exists("master")
        self.assertTrue( exists, "master branch exists")

def suite():
    loader = unittest.TestLoader()
    testsuite = loader.loadTestsFromTestCase(TestGitData)
    return testsuite

def test_main():
    testsuite = suite()
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    result = runner.run(testsuite)

if __name__ == "__main__":
    test_main()

Response:
<DELETE> from nose       <DELETE_END> <REPLACE_OLD> with_setup
from nose.tools import *
import <REPLACE_NEW> unittest
import <REPLACE_END> <REPLACE_OLD> json

def test_fetch():
 <REPLACE_NEW> json

class TestGitData(unittest.TestCase):
    def test_fetch(self):
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> assert <REPLACE_NEW>     self.assertTrue( <REPLACE_END> <REPLACE_OLD> study_id

def test_write():
 <REPLACE_NEW> study_id)

    def test_write(self):
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> 999
 <REPLACE_NEW> 9999
     <REPLACE_END> <INSERT>     <INSERT_END> <REPLACE_OLD> assert <REPLACE_NEW>     self.assertTrue( <REPLACE_END> <REPLACE_OLD> non-empty"

def test_branch_exists():
 <REPLACE_NEW> non-empty")

    def test_branch_exists(self):
     <REPLACE_END> <INSERT>     <INSERT_END> <REPLACE_OLD> assert <REPLACE_NEW>     self.assertTrue( <REPLACE_END> <REPLACE_OLD> exist"

 <REPLACE_NEW> exist")

     <REPLACE_END> <REPLACE_OLD> assert <REPLACE_NEW>     self.assertTrue( <REPLACE_END> <REPLACE_OLD> exists"

test_branch_exists()
test_fetch()
test_write()
 <REPLACE_NEW> exists")

def suite():
    loader = unittest.TestLoader()
    testsuite = loader.loadTestsFromTestCase(TestGitData)
    return testsuite

def test_main():
    testsuite = suite()
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    result = runner.run(testsuite)

if __name__ == "__main__":
    test_main()
 <REPLACE_END> <|endoftext|> import unittest
import os
import sys
from gitdata import GitData
import simplejson as json

class TestGitData(unittest.TestCase):
    def test_fetch(self):
        gd = GitData(repo="./treenexus")

        study_id = 438
        study_nexson = gd.fetch_study(study_id)
        valid = 1
        try:
            json.loads(study_nexson)
        except:
            valid = 0
        self.assertTrue( valid, "fetch_study(%s) returned valid JSON" % study_id)

    def test_write(self):
        gd = GitData(repo="./treenexus")
        author   = "John Doe <john@doe.com>"
        content  = '{"foo":"bar"}'
        study_id = 9999
        branch   = "johndoe_study_%s" % study_id
        new_sha  = gd.write_study(study_id,content,branch,author)
        self.assertTrue( new_sha != "", "new_sha is non-empty")

    def test_branch_exists(self):
        gd = GitData(repo="./treenexus")
        exists = gd.branch_exists("nothisdoesnotexist")
        self.assertTrue( exists == 0, "branch does not exist")

        exists = gd.branch_exists("master")
        self.assertTrue( exists, "master branch exists")

def suite():
    loader = unittest.TestLoader()
    testsuite = loader.loadTestsFromTestCase(TestGitData)
    return testsuite

def test_main():
    testsuite = suite()
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    result = runner.run(testsuite)

if __name__ == "__main__":
    test_main()

Prompt:
Convert GitData tests to a unittest suite

from nose       import with_setup
from nose.tools import *
import os
import sys
from gitdata import GitData
import simplejson as json

def test_fetch():
    gd = GitData(repo="./treenexus")

    study_id = 438
    study_nexson = gd.fetch_study(study_id)
    valid = 1
    try:
        json.loads(study_nexson)
    except:
        valid = 0
    assert valid, "fetch_study(%s) returned valid JSON" % study_id

def test_write():
    gd = GitData(repo="./treenexus")
    author   = "John Doe <john@doe.com>"
    content  = '{"foo":"bar"}'
    study_id = 999
    branch   = "johndoe_study_%s" % study_id
    new_sha  = gd.write_study(study_id,content,branch,author)
    assert new_sha != "", "new_sha is non-empty"

def test_branch_exists():
    gd = GitData(repo="./treenexus")
    exists = gd.branch_exists("nothisdoesnotexist")
    assert exists == 0, "branch does not exist"

    exists = gd.branch_exists("master")
    assert exists, "master branch exists"

test_branch_exists()
test_fetch()
test_write()


from __future__ import absolute_import

from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue

@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
    def get_attrs(self, item_list, user):
        assert len(set(i.key for i in item_list)) < 2

        tagvalues = dict(
            (t.value, t)
            for t in TagValue.objects.filter(
                project=item_list[0].project,
                key=item_list[0].key,
                value__in=[i.value for i in item_list]
            )
        )

        result = {}
        for item in item_list:
            result[item] = {
                'name': tagvalues[item.value].get_label(),
            }
        return result

    def serialize(self, obj, attrs, user):
        d = {
            'name': attrs['name'],
            'key': obj.key,
            'value': obj.value,
            'count': obj.times_seen,
            'lastSeen': obj.last_seen,
            'firstSeen': obj.first_seen,
        }
        return d

Implement labels on group tag values

Implement labels on group tag values

Response:
<REPLACE_OLD> GroupTagValue

@register(GroupTagValue)
class <REPLACE_NEW> GroupTagValue, TagValue

@register(GroupTagValue)
class <REPLACE_END> <INSERT>    def get_attrs(self, item_list, user):
        assert len(set(i.key for i in item_list)) < 2

        tagvalues = dict(
            (t.value, t)
            for t in TagValue.objects.filter(
                project=item_list[0].project,
                key=item_list[0].key,
                value__in=[i.value for i in item_list]
            )
        )

        result = {}
        for item in item_list:
            result[item] = {
                'name': tagvalues[item.value].get_label(),
            }
        return result

 <INSERT_END> <INSERT> 'name': attrs['name'],
            <INSERT_END> <|endoftext|> from __future__ import absolute_import

from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue

@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
    def get_attrs(self, item_list, user):
        assert len(set(i.key for i in item_list)) < 2

        tagvalues = dict(
            (t.value, t)
            for t in TagValue.objects.filter(
                project=item_list[0].project,
                key=item_list[0].key,
                value__in=[i.value for i in item_list]
            )
        )

        result = {}
        for item in item_list:
            result[item] = {
                'name': tagvalues[item.value].get_label(),
            }
        return result

    def serialize(self, obj, attrs, user):
        d = {
            'name': attrs['name'],
            'key': obj.key,
            'value': obj.value,
            'count': obj.times_seen,
            'lastSeen': obj.last_seen,
            'firstSeen': obj.first_seen,
        }
        return d

Prompt:
Implement labels on group tag values

from __future__ import absolute_import

from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue

@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
    def serialize(self, obj, attrs, user):
        d = {
            'key': obj.key,
            'value': obj.value,
            'count': obj.times_seen,
            'lastSeen': obj.last_seen,
            'firstSeen': obj.first_seen,
        }
        return d


from databin.parsers.util import ParseException
from databin.parsers.simple import parse_csv, parse_tsv
from databin.parsers.psql import parse_psql

PARSERS = [
    ('Excel copy & paste', 'excel', parse_tsv),
    ('Comma-Separated Values', 'csv', parse_csv),
    ('Tab-Separated Values', 'tsv', parse_tsv),
    ('psql Shell', 'psql', parse_psql),
]

def parse(format, data):
    for name, key, func in PARSERS:
        if key == format:
            return func(data)
    raise ParseException()

def get_parsers():
    for name, key, func in PARSERS:
        yield (key, name)

Make excel format the default

Make excel format the default

Response:
<INSERT> ('Excel copy & paste', 'excel', parse_tsv),
    <INSERT_END> <DELETE> parse_tsv),
    ('Excel copy & paste', 'excel', <DELETE_END> <|endoftext|> from databin.parsers.util import ParseException
from databin.parsers.simple import parse_csv, parse_tsv
from databin.parsers.psql import parse_psql

PARSERS = [
    ('Excel copy & paste', 'excel', parse_tsv),
    ('Comma-Separated Values', 'csv', parse_csv),
    ('Tab-Separated Values', 'tsv', parse_tsv),
    ('psql Shell', 'psql', parse_psql),
]

def parse(format, data):
    for name, key, func in PARSERS:
        if key == format:
            return func(data)
    raise ParseException()

def get_parsers():
    for name, key, func in PARSERS:
        yield (key, name)

Prompt:
Make excel format the default

from databin.parsers.util import ParseException
from databin.parsers.simple import parse_csv, parse_tsv
from databin.parsers.psql import parse_psql

PARSERS = [
    ('Comma-Separated Values', 'csv', parse_csv),
    ('Tab-Separated Values', 'tsv', parse_tsv),
    ('Excel copy & paste', 'excel', parse_tsv),
    ('psql Shell', 'psql', parse_psql),
]

def parse(format, data):
    for name, key, func in PARSERS:
        if key == format:
            return func(data)
    raise ParseException()

def get_parsers():
    for name, key, func in PARSERS:
        yield (key, name)


# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
from . import cfop
# from . import document_cancel
# from . import document_correction
from . import document_invalidate_number
from . import spec_mixin

Response:
<REPLACE_OLD> cfop
from <REPLACE_NEW> cfop
# from <REPLACE_END> <REPLACE_OLD> document_cancel
from <REPLACE_NEW> document_cancel
# from <REPLACE_END> <|endoftext|> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
from . import cfop
# from . import document_cancel
# from . import document_correction
from . import document_invalidate_number
from . import spec_mixin

Prompt:
[REF] Disable import of document_cancel and document_correction

# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
from . import cfop
from . import document_cancel
from . import document_correction
from . import document_invalidate_number
from . import spec_mixin


import glob
import os
import unittest
import sys

def build_test_suite():
    suite = unittest.TestSuite()

    for test_case in glob.glob('tests/test_*.py'):
        modname = os.path.splitext(test_case)[0]
        modname = modname.replace('/', '.')
        module = __import__(modname, {}, {}, ['1'])
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    return suite

if __name__ == "__main__":
    suite = build_test_suite()
    runner = unittest.TextTestRunner()

    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())

Response:
<REPLACE_OLD> unittest

def <REPLACE_NEW> unittest
import sys

def <REPLACE_END> <INSERT> result = <INSERT_END> <INSERT>    sys.exit(not result.wasSuccessful())
 <INSERT_END> <|endoftext|> import glob
import os
import unittest
import sys

def build_test_suite():
    suite = unittest.TestSuite()

    for test_case in glob.glob('tests/test_*.py'):
        modname = os.path.splitext(test_case)[0]
        modname = modname.replace('/', '.')
        module = __import__(modname, {}, {}, ['1'])
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    return suite

if __name__ == "__main__":
    suite = build_test_suite()
    runner = unittest.TextTestRunner()

    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())

Prompt:
Make unittest return exit code 1 on failure

This is to allow travis to catch test failures

import glob
import os
import unittest

def build_test_suite():
    suite = unittest.TestSuite()

    for test_case in glob.glob('tests/test_*.py'):
        modname = os.path.splitext(test_case)[0]
        modname = modname.replace('/', '.')
        module = __import__(modname, {}, {}, ['1'])
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    return suite

if __name__ == "__main__":
    suite = build_test_suite()
    runner = unittest.TextTestRunner()

    runner.run(suite)


from django.shortcuts import render
from django.utils.datastructures import SortedDict

def _get_key_details(conn, db):
    conn.execute_command('SELECT', db)
    keys = conn.keys()
    key_details = {}
    for key in keys:
        details = conn.execute_command('DEBUG', 'OBJECT', key)

        key_details[key] = {
            'type': conn.type(key),
            'details': dict(
                i.split(':') for i in details.split() if ':' in i
            ),
            'ttl': conn.ttl(key),
        }
    return key_details

def inspect(request, server):
    stats = server.stats
    if stats['status'] == 'UP':
        conn = server.connection
        databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
        database_details = SortedDict()
        for db in databases:
            database_details[db] = _get_key_details(conn, db)
    else:
        database_details = {}

    return render(request, "redisboard/inspect.html", {
        'databases': database_details,
        'original': server,
        'stats': stats,
        'app_label': 'redisboard',
    })

Response:
<REPLACE_OLD> render

def <REPLACE_NEW> render
from django.utils.datastructures import SortedDict

def <REPLACE_END> <REPLACE_OLD> [name[2:] <REPLACE_NEW> sorted(name[2:] <REPLACE_END> <REPLACE_OLD> name.startswith('db')]
 <REPLACE_NEW> name.startswith('db'))
 <REPLACE_END> <REPLACE_OLD> {}
 <REPLACE_NEW> SortedDict()
 <REPLACE_END> <|endoftext|> from django.shortcuts import render
from django.utils.datastructures import SortedDict

def _get_key_details(conn, db):
    conn.execute_command('SELECT', db)
    keys = conn.keys()
    key_details = {}
    for key in keys:
        details = conn.execute_command('DEBUG', 'OBJECT', key)

        key_details[key] = {
            'type': conn.type(key),
            'details': dict(
                i.split(':') for i in details.split() if ':' in i
            ),
            'ttl': conn.ttl(key),
        }
    return key_details

def inspect(request, server):
    stats = server.stats
    if stats['status'] == 'UP':
        conn = server.connection
        databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
        database_details = SortedDict()
        for db in databases:
            database_details[db] = _get_key_details(conn, db)
    else:
        database_details = {}

    return render(request, "redisboard/inspect.html", {
        'databases': database_details,
        'original': server,
        'stats': stats,
        'app_label': 'redisboard',
    })

Prompt:
Sort the database order in the inspect page.

from django.shortcuts import render

def _get_key_details(conn, db):
    conn.execute_command('SELECT', db)
    keys = conn.keys()
    key_details = {}
    for key in keys:
        details = conn.execute_command('DEBUG', 'OBJECT', key)

        key_details[key] = {
            'type': conn.type(key),
            'details': dict(
                i.split(':') for i in details.split() if ':' in i
            ),
            'ttl': conn.ttl(key),
        }
    return key_details

def inspect(request, server):
    stats = server.stats
    if stats['status'] == 'UP':
        conn = server.connection
        databases = [name[2:] for name in conn.info() if name.startswith('db')]
        database_details = {}
        for db in databases:
            database_details[db] = _get_key_details(conn, db)
    else:
        database_details = {}

    return render(request, "redisboard/inspect.html", {
        'databases': database_details,
        'original': server,
        'stats': stats,
        'app_label': 'redisboard',
    })


from zope.component import adapts
from zope.component import provideAdapter

from sboard.nodes import CreateView
from sboard.nodes import DetailsView
from sboard.nodes import TagListView

from .forms import PolicyIssueForm
from .interfaces import IVoting
from .interfaces import IPolicyIssue

class VotingView(DetailsView):
    adapts(IVoting)

    templates = {
        'details': 'votings/voting_details.html',
    }

provideAdapter(VotingView)

class CreatePolicyIssueView(CreateView):
    adapts(object, IPolicyIssue)

    form = PolicyIssueForm

provideAdapter(CreatePolicyIssueView, name="create")

provideAdapter(TagListView, (IPolicyIssue,))

Response:
<REPLACE_OLD> DetailsView

from <REPLACE_NEW> DetailsView
from sboard.nodes import TagListView

from <REPLACE_END> <REPLACE_OLD> name="create")
 <REPLACE_NEW> name="create")

provideAdapter(TagListView, (IPolicyIssue,))
 <REPLACE_END> <|endoftext|> from zope.component import adapts
from zope.component import provideAdapter

from sboard.nodes import CreateView
from sboard.nodes import DetailsView
from sboard.nodes import TagListView

from .forms import PolicyIssueForm
from .interfaces import IVoting
from .interfaces import IPolicyIssue

class VotingView(DetailsView):
    adapts(IVoting)

    templates = {
        'details': 'votings/voting_details.html',
    }

provideAdapter(VotingView)

class CreatePolicyIssueView(CreateView):
    adapts(object, IPolicyIssue)

    form = PolicyIssueForm

provideAdapter(CreatePolicyIssueView, name="create")

provideAdapter(TagListView, (IPolicyIssue,))

Prompt:
Use TagListView for IPolicyIssue as default view.

from zope.component import adapts
from zope.component import provideAdapter

from sboard.nodes import CreateView
from sboard.nodes import DetailsView

from .forms import PolicyIssueForm
from .interfaces import IVoting
from .interfaces import IPolicyIssue

class VotingView(DetailsView):
    adapts(IVoting)

    templates = {
        'details': 'votings/voting_details.html',
    }

provideAdapter(VotingView)

class CreatePolicyIssueView(CreateView):
    adapts(object, IPolicyIssue)

    form = PolicyIssueForm

provideAdapter(CreatePolicyIssueView, name="create")


from Cookie import SimpleCookie
from urlparse import parse_qs

from utils import MultiDict, cached_property

class Request(object):
    def __init__(self, event, context):
        self.event = event
        self.context = context

    @property
    def method(self):
        return self.event['httpMethod']

    @property
    def query(self):
        return self.event['queryStringParameters']

    @cached_property
    def post(self):
        return MultiDict(parse_qs(self.event.get('body', '') or ''))

    @cached_property
    def cookies(self):
        jar = SimpleCookie()
        if self.event['headers'].get('Cookie'):
            jar.load(self.event['headers']['Cookie'].encode('utf-8'))
        return jar

    @property
    def stage(self):
        return self.event['stage']

    @property
    def stageVar(self):
        return self.event['stageVariables']

    @property
    def params(self):
        return self.event['pathParameters']

Add cookies property to Request

Add cookies property to Request

Response:
<INSERT> Cookie import SimpleCookie
from <INSERT_END> <REPLACE_OLD> cached_property, MultiDict

class <REPLACE_NEW> MultiDict, cached_property

class <REPLACE_END> <INSERT> @cached_property
    def cookies(self):
        jar = SimpleCookie()
        if self.event['headers'].get('Cookie'):
            jar.load(self.event['headers']['Cookie'].encode('utf-8'))
        return jar

    <INSERT_END> <|endoftext|> from Cookie import SimpleCookie
from urlparse import parse_qs

from utils import MultiDict, cached_property

class Request(object):
    def __init__(self, event, context):
        self.event = event
        self.context = context

    @property
    def method(self):
        return self.event['httpMethod']

    @property
    def query(self):
        return self.event['queryStringParameters']

    @cached_property
    def post(self):
        return MultiDict(parse_qs(self.event.get('body', '') or ''))

    @cached_property
    def cookies(self):
        jar = SimpleCookie()
        if self.event['headers'].get('Cookie'):
            jar.load(self.event['headers']['Cookie'].encode('utf-8'))
        return jar

    @property
    def stage(self):
        return self.event['stage']

    @property
    def stageVar(self):
        return self.event['stageVariables']

    @property
    def params(self):
        return self.event['pathParameters']

Prompt:
Add cookies property to Request

from urlparse import parse_qs

from utils import cached_property, MultiDict

class Request(object):
    def __init__(self, event, context):
        self.event = event
        self.context = context

    @property
    def method(self):
        return self.event['httpMethod']

    @property
    def query(self):
        return self.event['queryStringParameters']

    @cached_property
    def post(self):
        return MultiDict(parse_qs(self.event.get('body', '') or ''))

    @property
    def stage(self):
        return self.event['stage']

    @property
    def stageVar(self):
        return self.event['stageVariables']

    @property
    def params(self):
        return self.event['pathParameters']


#!/usr/bin/env python
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requirements = [
]

test_requirements = [
]

setup(
    name='adb_android',
    version='0.2.0',
    description="Enables android adb in your python script",
    long_description='This python package is a wrapper for standard android adb\
    implementation. It allows you to execute android adb commands in your \
    python script.',
    author='Viktor Malyi',
    author_email='v.stratus@gmail.com',
    url='https://github.com/vmalyi/adb_android',
    packages=[
        'adb_android',
    ],
    package_dir={'adb_android':'adb_android'},
    include_package_data=True,
    install_requires=requirements,
    license="GNU",
    keywords='adb, android',
    #TODO: check compatibitily with >2.7
    classifiers=[
    'Development Status :: 4 - Beta',
    'Programming Language :: Python :: 2.7',
    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    'Topic :: Software Development :: Testing',
    'Intended Audience :: Developers'
    ],
    test_suite='tests',
)

Update package description and version

Update package description and version

Response:
<REPLACE_OLD> version='0.1.0',
 <REPLACE_NEW> version='0.2.0',
 <REPLACE_END> <INSERT> python <INSERT_END> <REPLACE_OLD> can be used by everyone who implements some <REPLACE_NEW> is a wrapper for standard android adb\
    implementation. It allows you to execute android adb commands in your <REPLACE_END> <REPLACE_OLD> android-related stuff on Python and at the same time has to interact with \
    android adb. It makes interaction with android adb easier because of proper \
    error handling and some useful features.',
 <REPLACE_NEW> python script.',
 <REPLACE_END> <REPLACE_OLD> url='https://github.com/vmalyi/adb',
 <REPLACE_NEW> url='https://github.com/vmalyi/adb_android',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requirements = [
]

test_requirements = [
]

setup(
    name='adb_android',
    version='0.2.0',
    description="Enables android adb in your python script",
    long_description='This python package is a wrapper for standard android adb\
    implementation. It allows you to execute android adb commands in your \
    python script.',
    author='Viktor Malyi',
    author_email='v.stratus@gmail.com',
    url='https://github.com/vmalyi/adb_android',
    packages=[
        'adb_android',
    ],
    package_dir={'adb_android':'adb_android'},
    include_package_data=True,
    install_requires=requirements,
    license="GNU",
    keywords='adb, android',
    #TODO: check compatibitily with >2.7
    classifiers=[
    'Development Status :: 4 - Beta',
    'Programming Language :: Python :: 2.7',
    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    'Topic :: Software Development :: Testing',
    'Intended Audience :: Developers'
    ],
    test_suite='tests',
)

Prompt:
Update package description and version

#!/usr/bin/env python
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requirements = [
]

test_requirements = [
]

setup(
    name='adb_android',
    version='0.1.0',
    description="Enables android adb in your python script",
    long_description='This package can be used by everyone who implements some \
    android-related stuff on Python and at the same time has to interact with \
    android adb. It makes interaction with android adb easier because of proper \
    error handling and some useful features.',
    author='Viktor Malyi',
    author_email='v.stratus@gmail.com',
    url='https://github.com/vmalyi/adb',
    packages=[
        'adb_android',
    ],
    package_dir={'adb_android':'adb_android'},
    include_package_data=True,
    install_requires=requirements,
    license="GNU",
    keywords='adb, android',
    #TODO: check compatibitily with >2.7
    classifiers=[
    'Development Status :: 4 - Beta',
    'Programming Language :: Python :: 2.7',
    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    'Topic :: Software Development :: Testing',
    'Intended Audience :: Developers'
    ],
    test_suite='tests',
)


import logging

from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response

# Import the Game Controller
from Game.GameController import GameController

class GameModes(MethodView):
    def get(self):
        logging.debug("GameModes: GET: Initializing GameObject")
        game_object = GameController()
        logging.debug("GameModes: GET: GameObject initialized to {}".format(game_object.save()))

        logging.debug("GameModes: GET: Checking if textmode flag set")
        if request.args.get('textmode', None):
            logging.debug("GameModes: GET: Responding with list of names")
            response_data = game_object.game_mode_names
        else:
            logging.debug("GameModes: GET: Responding with JSON object: {}".format(game_object.game_modes))
            response_data = [{"mode": gt.mode,
                              "digits": gt.digits,
                              "digit-type": gt.digit_type,
                              "guesses": gt.guesses_allowed
                             } for gt in game_object.game_modes]

        logging.debug("GameModes: GET: Return {}".format(response_data))
        return build_response(
            html_status=200,
            response_data=response_data,
            response_mimetype="application/json"
        )

Response:
<REPLACE_OLD> object")
 <REPLACE_NEW> object: {}".format(game_object.game_modes))
 <REPLACE_END> <|endoftext|> import logging

from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response

# Import the Game Controller
from Game.GameController import GameController

class GameModes(MethodView):
    def get(self):
        logging.debug("GameModes: GET: Initializing GameObject")
        game_object = GameController()
        logging.debug("GameModes: GET: GameObject initialized to {}".format(game_object.save()))

        logging.debug("GameModes: GET: Checking if textmode flag set")
        if request.args.get('textmode', None):
            logging.debug("GameModes: GET: Responding with list of names")
            response_data = game_object.game_mode_names
        else:
            logging.debug("GameModes: GET: Responding with JSON object: {}".format(game_object.game_modes))
            response_data = [{"mode": gt.mode,
                              "digits": gt.digits,
                              "digit-type": gt.digit_type,
                              "guesses": gt.guesses_allowed
                             } for gt in game_object.game_modes]

        logging.debug("GameModes: GET: Return {}".format(response_data))
        return build_response(
            html_status=200,
            response_data=response_data,
            response_mimetype="application/json"
        )

Prompt:
Update logging for message output and consistency.

import logging

from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response

# Import the Game Controller
from Game.GameController import GameController

class GameModes(MethodView):
    def get(self):
        logging.debug("GameModes: GET: Initializing GameObject")
        game_object = GameController()
        logging.debug("GameModes: GET: GameObject initialized to {}".format(game_object.save()))

        logging.debug("GameModes: GET: Checking if textmode flag set")
        if request.args.get('textmode', None):
            logging.debug("GameModes: GET: Responding with list of names")
            response_data = game_object.game_mode_names
        else:
            logging.debug("GameModes: GET: Responding with JSON object")
            response_data = [{"mode": gt.mode,
                              "digits": gt.digits,
                              "digit-type": gt.digit_type,
                              "guesses": gt.guesses_allowed
                             } for gt in game_object.game_modes]

        logging.debug("GameModes: GET: Return {}".format(response_data))
        return build_response(
            html_status=200,
            response_data=response_data,
            response_mimetype="application/json"
        )


from twisted.web.server import Site, Request

class AddSecurityHeadersRequest(Request):
    CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)

class PixelatedSite(Site):

    requestFactory = AddSecurityHeadersRequest

    @classmethod
    def enable_csp_requests(cls):
        cls.requestFactory = AddSecurityHeadersRequest

    @classmethod
    def disable_csp_requests(cls):
        cls.requestFactory = Site.requestFactory

Rename class to match intent

Rename class to match intent

Response:
<REPLACE_OLD> AddCSPHeaderRequest(Request):
 <REPLACE_NEW> AddSecurityHeadersRequest(Request):
 <REPLACE_END> <REPLACE_OLD> AddCSPHeaderRequest

 <REPLACE_NEW> AddSecurityHeadersRequest

 <REPLACE_END> <REPLACE_OLD> AddCSPHeaderRequest

 <REPLACE_NEW> AddSecurityHeadersRequest

 <REPLACE_END> <|endoftext|> from twisted.web.server import Site, Request

class AddSecurityHeadersRequest(Request):
    CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)

class PixelatedSite(Site):

    requestFactory = AddSecurityHeadersRequest

    @classmethod
    def enable_csp_requests(cls):
        cls.requestFactory = AddSecurityHeadersRequest

    @classmethod
    def disable_csp_requests(cls):
        cls.requestFactory = Site.requestFactory

Prompt:
Rename class to match intent

from twisted.web.server import Site, Request

class AddCSPHeaderRequest(Request):
    CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)

class PixelatedSite(Site):

    requestFactory = AddCSPHeaderRequest

    @classmethod
    def enable_csp_requests(cls):
        cls.requestFactory = AddCSPHeaderRequest

    @classmethod
    def disable_csp_requests(cls):
        cls.requestFactory = Site.requestFactory


import sys

def add_all(nums):
	return sum(nums)

def multiply_all(nums):
	return reduce(lambda a, b: a * b, nums)

if __name__== '__main__':
	command = sys.argv[1]
	nums = map(float, sys.argv[2:])
	if command == 'add':
		print(add_all(nums))
	elif command == 'multiply':
		print(multiply_all(nums))

Fix bug in 'multiply' support

Fix bug in 'multiply' support

Response:
<REPLACE_OLD> 'multiply':
		print(multiply_all(sums))
 <REPLACE_NEW> 'multiply':
		print(multiply_all(nums))
 <REPLACE_END> <|endoftext|> import sys

def add_all(nums):
	return sum(nums)

def multiply_all(nums):
	return reduce(lambda a, b: a * b, nums)

if __name__== '__main__':
	command = sys.argv[1]
	nums = map(float, sys.argv[2:])
	if command == 'add':
		print(add_all(nums))
	elif command == 'multiply':
		print(multiply_all(nums))

Prompt:
Fix bug in 'multiply' support

import sys

def add_all(nums):
	return sum(nums)

def multiply_all(nums):
	return reduce(lambda a, b: a * b, nums)

if __name__== '__main__':
	command = sys.argv[1]
	nums = map(float, sys.argv[2:])
	if command == 'add':
		print(add_all(nums))
	elif command == 'multiply':
		print(multiply_all(sums))


from flask import render_template
from flask.ext.login import login_required

from .. import app

@app.route('/')
@login_required
def index():
    return render_template('base.html')

Response:
<DELETE> collections import OrderedDict
from urllib.parse import urlparse
import re

from <DELETE_END> <REPLACE_OLD> render_template, redirect, url_for, request, abort, jsonify,\
        flash, Markup, session
from flask.views import View
from <REPLACE_NEW> render_template
from <REPLACE_END> <REPLACE_OLD> login_user, login_required, logout_user, \
        current_user
from flask.ext.wtf import Form
from flask.ext.principal import identity_changed, AnonymousIdentity
from sqlalchemy.orm.exc import NoResultFound
from wtforms.fields import StringField, PasswordField, SelectField, \
        SubmitField, TextAreaField, HiddenField
from wtforms.fields.html5 import URLField, DecimalField
from wtforms.widgets import HiddenInput
from wtforms.validators import InputRequired, ValidationError, AnyOf, URL

from <REPLACE_NEW> login_required

from <REPLACE_END> <REPLACE_OLD> app, auth_methods, db, requests_session, killmail_sources
from ..auth import SubmitRequestsPermission, ReviewRequestsPermission, \
        PayoutRequestsPermission, admin_permission
from ..auth.models import User, Group, Division, Pilot
from ..models import Request, Modifier, Action

@app.route('/')
@login_required
def <REPLACE_NEW> app

@app.route('/')
@login_required
def <REPLACE_END> <|endoftext|> from flask import render_template
from flask.ext.login import login_required

from .. import app

@app.route('/')
@login_required
def index():
    return render_template('base.html')

Prompt:
Remove extraneous imports in the base view package
from collections import OrderedDict
from urllib.parse import urlparse
import re

from flask import render_template, redirect, url_for, request, abort, jsonify,\
        flash, Markup, session
from flask.views import View
from flask.ext.login import login_user, login_required, logout_user, \
        current_user
from flask.ext.wtf import Form
from flask.ext.principal import identity_changed, AnonymousIdentity
from sqlalchemy.orm.exc import NoResultFound
from wtforms.fields import StringField, PasswordField, SelectField, \
        SubmitField, TextAreaField, HiddenField
from wtforms.fields.html5 import URLField, DecimalField
from wtforms.widgets import HiddenInput
from wtforms.validators import InputRequired, ValidationError, AnyOf, URL

from .. import app, auth_methods, db, requests_session, killmail_sources
from ..auth import SubmitRequestsPermission, ReviewRequestsPermission, \
        PayoutRequestsPermission, admin_permission
from ..auth.models import User, Group, Division, Pilot
from ..models import Request, Modifier, Action

@app.route('/')
@login_required
def index():
    return render_template('base.html')


from __future__ import unicode_literals
import logging

from django.core.management.base import BaseCommand

from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated

logger = logging.getLogger(__name__)

def update_share_preprint_modified_dates(dry_run=False):
    dates_updated = 0
    for preprint in PreprintService.objects.filter():
        if preprint.node.date_modified > preprint.date_modified:
            if not dry_run:
                on_preprint_updated(preprint._id)
            dates_updated += 1
    return dates_updated

class Command(BaseCommand):
    """
    Send more accurate preprint modified dates to Share (max of node.date_modified and preprint.date_modified)
    """
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Say how many preprint updates would be sent to share',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
            dates_updated = update_share_preprint_modified_dates()
            logger.info('Sent %d new preprint modified dates to Share' % dates_updated)

        else:
            dates_updated = update_share_preprint_modified_dates(dry_run=True)
            logger.info('Would have sent %d new preprint modified dates to Share' % dates_updated)

Add management command to update preprint share dates

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import unicode_literals
import logging

from django.core.management.base import BaseCommand

from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated

logger = logging.getLogger(__name__)

def update_share_preprint_modified_dates(dry_run=False):
    dates_updated = 0
    for preprint in PreprintService.objects.filter():
        if preprint.node.date_modified > preprint.date_modified:
            if not dry_run:
                on_preprint_updated(preprint._id)
            dates_updated += 1
    return dates_updated

class Command(BaseCommand):
    """
    Send more accurate preprint modified dates to Share (max of node.date_modified and preprint.date_modified)
    """
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Say how many preprint updates would be sent to share',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
            dates_updated = update_share_preprint_modified_dates()
            logger.info('Sent %d new preprint modified dates to Share' % dates_updated)

        else:
            dates_updated = update_share_preprint_modified_dates(dry_run=True)
            logger.info('Would have sent %d new preprint modified dates to Share' % dates_updated)
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals
import logging

from django.core.management.base import BaseCommand

from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated

logger = logging.getLogger(__name__)

def update_share_preprint_modified_dates(dry_run=False):
    dates_updated = 0
    for preprint in PreprintService.objects.filter():
        if preprint.node.date_modified > preprint.date_modified:
            if not dry_run:
                on_preprint_updated(preprint._id)
            dates_updated += 1
    return dates_updated

class Command(BaseCommand):
    """
    Send more accurate preprint modified dates to Share (max of node.date_modified and preprint.date_modified)
    """
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Say how many preprint updates would be sent to share',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
            dates_updated = update_share_preprint_modified_dates()
            logger.info('Sent %d new preprint modified dates to Share' % dates_updated)

        else:
            dates_updated = update_share_preprint_modified_dates(dry_run=True)
            logger.info('Would have sent %d new preprint modified dates to Share' % dates_updated)

Prompt: Add management command to update preprint share dates


from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View

from .pdf import generate_receipt_pdf

class ReceiptHTMLView(View):
    """Renders a receipt as HTML."""
    def get(self, request, pk):
        return HttpResponse(
            generate_receipt_pdf(pk, request, True),
        )

class ReceiptPDFView(View):
    """Renders a receipt as a PDF, prompting to download it."""

    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + \
            _('receipt %s.pdf' % pk)

        generate_receipt_pdf(pk, response)
        return response

class ReceiptPDFDisplayView(View):
    """
    Renders a receipt as a PDF.

    Browsers should render the file, rather than prompt to download it.
    """
    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        generate_receipt_pdf(pk, response)
        return response

Add a view to display PDF receipts

Response:
<REPLACE_OLD> ReceiptHTMLView(View):

 <REPLACE_NEW> ReceiptHTMLView(View):
    """Renders a receipt as HTML."""
 <REPLACE_END> <REPLACE_OLD> ReceiptPDFView(View):

 <REPLACE_NEW> ReceiptPDFView(View):
    """Renders a receipt as a PDF, prompting to download it."""

 <REPLACE_END> <INSERT> response

class ReceiptPDFDisplayView(View):
    """
    Renders a receipt as a PDF.

    Browsers should render the file, rather than prompt to download it.
    """
    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        generate_receipt_pdf(pk, response)
        return <INSERT_END> <|endoftext|> from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View

from .pdf import generate_receipt_pdf

class ReceiptHTMLView(View):
    """Renders a receipt as HTML."""
    def get(self, request, pk):
        return HttpResponse(
            generate_receipt_pdf(pk, request, True),
        )

class ReceiptPDFView(View):
    """Renders a receipt as a PDF, prompting to download it."""

    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + \
            _('receipt %s.pdf' % pk)

        generate_receipt_pdf(pk, response)
        return response

class ReceiptPDFDisplayView(View):
    """
    Renders a receipt as a PDF.

    Browsers should render the file, rather than prompt to download it.
    """
    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        generate_receipt_pdf(pk, response)
        return response

Prompt:
Add a view to display PDF receipts

Fixes #23
Closes !7
Closes !8

from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View

from .pdf import generate_receipt_pdf

class ReceiptHTMLView(View):

    def get(self, request, pk):
        return HttpResponse(
            generate_receipt_pdf(pk, request, True),
        )

class ReceiptPDFView(View):

    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + \
            _('receipt %s.pdf' % pk)

        generate_receipt_pdf(pk, response)
        return response


#! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calibre_books.settings')

setup(
    name='calibre-books',
    author='Adam Bogdał',
    author_email='adam@bogdal.pl',
    description="Calibre server in Django",
    license='BSD',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.6',
        'django-bootstrap3>=4.8.2',
        'django-dropbox==0.0.2',
        'dj_database_url>=0.2.2',
        'python-memcached==1.53',
        'Pillow==2.5.2',
        'gunicorn==19.1.0',
        'psycopg2==2.5.3',

    ],
    entry_points={
        'console_scripts': ['manage.py = calibre_books:manage']},
)

Use pillow instead of ordinary pil

Use pillow instead of ordinary pil

Response:
<REPLACE_OLD> 'PIL==1.1.7',
 <REPLACE_NEW> 'Pillow==2.5.2',
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calibre_books.settings')

setup(
    name='calibre-books',
    author='Adam Bogdał',
    author_email='adam@bogdal.pl',
    description="Calibre server in Django",
    license='BSD',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.6',
        'django-bootstrap3>=4.8.2',
        'django-dropbox==0.0.2',
        'dj_database_url>=0.2.2',
        'python-memcached==1.53',
        'Pillow==2.5.2',
        'gunicorn==19.1.0',
        'psycopg2==2.5.3',

    ],
    entry_points={
        'console_scripts': ['manage.py = calibre_books:manage']},
)

Prompt:
Use pillow instead of ordinary pil

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calibre_books.settings')

setup(
    name='calibre-books',
    author='Adam Bogdał',
    author_email='adam@bogdal.pl',
    description="Calibre server in Django",
    license='BSD',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.6',
        'django-bootstrap3>=4.8.2',
        'django-dropbox==0.0.2',
        'dj_database_url>=0.2.2',
        'python-memcached==1.53',
        'PIL==1.1.7',
        'gunicorn==19.1.0',
        'psycopg2==2.5.3',

    ],
    entry_points={
        'console_scripts': ['manage.py = calibre_books:manage']},
)