#!/usr/bin/env python

from setuptools import setup, find_packages
from dreambeam import __version__

setup(name='dreamBeam',
      version=__version__,
      description='Measurement equation framework for radio interferometry.',
      author='Tobia D. Carozzi',
      author_email='tobia.carozzi@chalmers.se',
      packages=find_packages(),
      package_data={'dreambeam.telescopes.LOFAR':
                    ['share/*.cc', 'share/simmos/*.cfg',
                     'share/alignment/*.txt', 'data/*teldat.p'],
                    'dreambeam':
                    ['configs/*.txt']},
      include_package_data=True,
      license='ISC',
      classifiers=[
          'Development Status :: 1 - Planning',
          'Intended Audience :: Science/Research',
          'License :: OSI Approved :: ISC License',
          'Programming Language :: Python :: 2.7',
          'Topic :: Scientific/Engineering :: Astronomy',
          'Topic :: Scientific/Engineering :: Mathematics',
          'Topic :: Scientific/Engineering :: Visualization'
      ],
      install_requires=[
          'numpy>=1.10',
          'python-casacore',
          'matplotlib>2.0',
          'antpat>=0.4'
      ],
      entry_points={
        'console_scripts': [
            'pointing_jones = scripts.pointing_jones:cli_main',
            'FoV_jones = scripts.FoV_jones:main'
        ]

      }
      )

Include config files in the pip install

Include config files in the pip install

Response:
#!/usr/bin/env python

from setuptools import setup, find_packages
from dreambeam import __version__

setup(name='dreamBeam',
      version=__version__,
      description='Measurement equation framework for radio interferometry.',
      author='Tobia D. Carozzi',
      author_email='tobia.carozzi@chalmers.se',
      packages=find_packages(),
      package_data={'dreambeam.telescopes.LOFAR':
                    ['share/*.cc', 'share/simmos/*.cfg',
                     'share/alignment/*.txt', 'data/*teldat.p'],
                    'dreambeam':
                    ['configs/*.txt']},
      include_package_data=True,
      license='ISC',
      classifiers=[
          'Development Status :: 1 - Planning',
          'Intended Audience :: Science/Research',
          'License :: OSI Approved :: ISC License',
          'Programming Language :: Python :: 2.7',
          'Topic :: Scientific/Engineering :: Astronomy',
          'Topic :: Scientific/Engineering :: Mathematics',
          'Topic :: Scientific/Engineering :: Visualization'
      ],
      install_requires=[
          'numpy>=1.10',
          'python-casacore',
          'matplotlib>2.0',
          'antpat>=0.4'
      ],
      entry_points={
        'console_scripts': [
            'pointing_jones = scripts.pointing_jones:cli_main',
            'FoV_jones = scripts.FoV_jones:main'
        ]

      }
      )

Prompt:
Include config files in the pip install

#!/usr/bin/env python

from setuptools import setup, find_packages
from dreambeam import __version__

setup(name='dreamBeam',
      version=__version__,
      description='Measurement equation framework for radio interferometry.',
      author='Tobia D. Carozzi',
      author_email='tobia.carozzi@chalmers.se',
      packages=find_packages(),
      package_data={'dreambeam.telescopes.LOFAR':
                    ['share/*.cc', 'share/simmos/*.cfg',
                     'share/alignment/*.txt', 'data/*teldat.p']},
      license='ISC',
      classifiers=[
          'Development Status :: 1 - Planning',
          'Intended Audience :: Science/Research',
          'License :: OSI Approved :: ISC License',
          'Programming Language :: Python :: 2.7',
          'Topic :: Scientific/Engineering :: Astronomy',
          'Topic :: Scientific/Engineering :: Mathematics',
          'Topic :: Scientific/Engineering :: Visualization'
      ],
      install_requires=[
          'numpy>=1.10',
          'python-casacore',
          'matplotlib>2.0',
          'antpat>=0.4'
      ],
      entry_points={
        'console_scripts': [
            'pointing_jones = scripts.pointing_jones:cli_main',
            'FoV_jones = scripts.FoV_jones:main'
        ]

      }
      )


__version__ = '1.7.3'
__copyright__ = 'Copyright (c) 2020, Skioo SA'
__licence__ = 'MIT'
__URL__ = 'https://github.com/skioo/django-customer-billing'

Update project version to 1.7.3

Update project version to 1.7.3

Response:
__version__ = '1.7.3'
__copyright__ = 'Copyright (c) 2020, Skioo SA'
__licence__ = 'MIT'
__URL__ = 'https://github.com/skioo/django-customer-billing'

Prompt:
Update project version to 1.7.3

__version__ = '1.7.2'
__copyright__ = 'Copyright (c) 2020, Skioo SA'
__licence__ = 'MIT'
__URL__ = 'https://github.com/skioo/django-customer-billing'


from setuptools import setup, find_packages
import os
import subprocess

os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")

versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
    os.remove(versionFile)
git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()
with open(versionFile, 'w') as versionFH:
    versionFH.write("cactus_commit = '%s'" % git_commit)

setup(
    name="progressiveCactus",
    version="1.0",
    author="Benedict Paten",
    package_dir = {'': 'src'},
    packages=find_packages(where='src'),
    include_package_data=True,
    package_data={'cactus': ['*_config.xml']},
    # We use the __file__ attribute so this package isn't zip_safe.
    zip_safe=False,

    install_requires=[
        'decorator',
        'subprocess32',
        'psutil',
        'networkx==1.11'],

    entry_points={
        'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)

Response:
from setuptools import setup, find_packages
import os
import subprocess

os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")

versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
    os.remove(versionFile)
git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()
with open(versionFile, 'w') as versionFH:
    versionFH.write("cactus_commit = '%s'" % git_commit)

setup(
    name="progressiveCactus",
    version="1.0",
    author="Benedict Paten",
    package_dir = {'': 'src'},
    packages=find_packages(where='src'),
    include_package_data=True,
    package_data={'cactus': ['*_config.xml']},
    # We use the __file__ attribute so this package isn't zip_safe.
    zip_safe=False,

    install_requires=[
        'decorator',
        'subprocess32',
        'psutil',
        'networkx==1.11'],

    entry_points={
        'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)

Prompt:
Fix Docker image tag inconsistency after merge commits

The image pushed is always given by `git rev-parse HEAD`, but the tag
for the image requested from Docker was retrieved from git log. Merge
commits were ignored by the latter. Now the tag is set to `git
rev-parse HEAD` both on push and retrieve.

from setuptools import setup, find_packages
import os
import subprocess

os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")

versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
    os.remove(versionFile)
git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0]
with open(versionFile, 'w') as versionFH:
    versionFH.write("cactus_commit = '%s'" % git_commit)

setup(
    name="progressiveCactus",
    version="1.0",
    author="Benedict Paten",
    package_dir = {'': 'src'},
    packages=find_packages(where='src'),
    include_package_data=True,
    package_data={'cactus': ['*_config.xml']},
    # We use the __file__ attribute so this package isn't zip_safe.
    zip_safe=False,

    install_requires=[
        'decorator',
        'subprocess32',
        'psutil',
        'networkx==1.11'],

    entry_points={
        'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)


Remove vim header from source files

Response:
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.

import fixtures
from mox3 import mox
from mox3 import stubout

class MoxStubout(fixtures.Fixture):
    """Deal with code around mox and stubout as a fixture."""

    def setUp(self):
        super(MoxStubout, self).setUp()
        self.mox = mox.Mox()
        self.stubs = stubout.StubOutForTesting()
        self.addCleanup(self.mox.UnsetStubs)
        self.addCleanup(self.stubs.UnsetAll)
        self.addCleanup(self.stubs.SmartUnsetAll)
        self.addCleanup(self.mox.VerifyAll)

Prompt:
Remove vim header from source files

Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765

# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.

import fixtures
from mox3 import mox
from mox3 import stubout

class MoxStubout(fixtures.Fixture):
    """Deal with code around mox and stubout as a fixture."""

    def setUp(self):
        super(MoxStubout, self).setUp()
        self.mox = mox.Mox()
        self.stubs = stubout.StubOutForTesting()
        self.addCleanup(self.mox.UnsetStubs)
        self.addCleanup(self.stubs.UnsetAll)
        self.addCleanup(self.stubs.SmartUnsetAll)
        self.addCleanup(self.mox.VerifyAll)


import logging

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

from eventkit_cloud.auth.models import OAuth
from eventkit_cloud.jobs.models import UserLicense

logger = logging.getLogger(__name__)

class OAuthAdmin(admin.ModelAdmin):

    search_fields = ['user__username', 'identification', 'commonname', 'user_info']
    list_display = ['user', 'identification', 'commonname']

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(OAuthAdmin, self).get_actions(request)
        actions.pop('delete_selected', None)
        return actions

class OAuthInline(admin.StackedInline):
    model = OAuth

class UserLicenseInline(admin.TabularInline):
    model = UserLicense
    extra = 0

UserAdmin.inlines = [OAuthInline, UserLicenseInline]
UserAdmin.readonly_fields += 'last_login', 'date_joined'

admin.site.unregister(Token)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.register(OAuth, OAuthAdmin)

Response:
import logging

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

from eventkit_cloud.auth.models import OAuth
from eventkit_cloud.jobs.models import UserLicense

logger = logging.getLogger(__name__)

class OAuthAdmin(admin.ModelAdmin):

    search_fields = ['user__username', 'identification', 'commonname', 'user_info']
    list_display = ['user', 'identification', 'commonname']

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(OAuthAdmin, self).get_actions(request)
        actions.pop('delete_selected', None)
        return actions

class OAuthInline(admin.StackedInline):
    model = OAuth

class UserLicenseInline(admin.TabularInline):
    model = UserLicense
    extra = 0

UserAdmin.inlines = [OAuthInline, UserLicenseInline]
UserAdmin.readonly_fields += 'last_login', 'date_joined'

admin.site.unregister(Token)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.register(OAuth, OAuthAdmin)

Prompt:
Add OAuth class information to the UserAdmin page.

import logging

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

from eventkit_cloud.auth.models import OAuth
from eventkit_cloud.jobs.models import UserLicense

logger = logging.getLogger(__name__)

class OAuthAdmin(admin.ModelAdmin):

    search_fields = ['user__username', 'identification', 'commonname', 'user_info']
    list_display = ['user', 'identification', 'commonname']

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(OAuthAdmin, self).get_actions(request)
        actions.pop('delete_selected', None)
        return actions

class UserLicenseInline(admin.TabularInline):
    model = UserLicense
    extra = 0

UserAdmin.inlines = [UserLicenseInline]
UserAdmin.readonly_fields += 'last_login', 'date_joined'

admin.site.unregister(Token)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.register(OAuth, OAuthAdmin)


#!/usr/bin/env python

from numpy import all, allclose, array, float32, max

from .. import interp

def test_interp2():
    x = array([
        [0, 1, 0],
        [1, 1, 1],
        [0, 1, 0],
    ], dtype=float32)
    y = interp._interp2(1.0, x)
    assert allclose(x, y)

if __name__ == '__main__':
    pass

Add a unit test for the interp module.

Add a unit test for the interp module.

Response:
#!/usr/bin/env python

from numpy import all, allclose, array, float32, max

from .. import interp

def test_interp2():
    x = array([
        [0, 1, 0],
        [1, 1, 1],
        [0, 1, 0],
    ], dtype=float32)
    y = interp._interp2(1.0, x)
    assert allclose(x, y)

if __name__ == '__main__':
    pass

Prompt: Add a unit test for the interp module.


import sqlite3

from django.db import OperationalError

def fts5_available():
    # based on https://stackoverflow.com/a/36656216/1853523
    if sqlite3.sqlite_version_info < (3, 19, 0):
        # Prior to version 3.19, SQLite doesn't support FTS5 queries with
        # column filters ('{column_1 column_2} : query'), which the sqlite
        # fulltext backend needs
        return False

    tmp_db = sqlite3.connect(':memory:')
    try:
        tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);')
    except sqlite3.OperationalError:
        return False
    finally:
        tmp_db.close()

    return True

def fts_table_exists():
    from wagtail.search.models import SQLiteFTSIndexEntry

    try:
        # ignore result of query; we are only interested in the query failing,
        # not the presence of index entries
        SQLiteFTSIndexEntry.objects.exists()
    except OperationalError:
        return False

    return True

Fix Sqlite FTS5 compatibility check

Response:
import sqlite3

from django.db import OperationalError

def fts5_available():
    # based on https://stackoverflow.com/a/36656216/1853523
    if sqlite3.sqlite_version_info < (3, 19, 0):
        # Prior to version 3.19, SQLite doesn't support FTS5 queries with
        # column filters ('{column_1 column_2} : query'), which the sqlite
        # fulltext backend needs
        return False

    tmp_db = sqlite3.connect(':memory:')
    try:
        tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);')
    except sqlite3.OperationalError:
        return False
    finally:
        tmp_db.close()

    return True

def fts_table_exists():
    from wagtail.search.models import SQLiteFTSIndexEntry

    try:
        # ignore result of query; we are only interested in the query failing,
        # not the presence of index entries
        SQLiteFTSIndexEntry.objects.exists()
    except OperationalError:
        return False

    return True

Prompt:
Fix Sqlite FTS5 compatibility check

As per https://github.com/wagtail/wagtail/issues/7798#issuecomment-1021544265 - the direct query against the sqlite3 library will fail with sqlite3.OperationalError, not django.db.OperationalError.

import sqlite3

from django.db import OperationalError

def fts5_available():
    # based on https://stackoverflow.com/a/36656216/1853523
    if sqlite3.sqlite_version_info < (3, 19, 0):
        # Prior to version 3.19, SQLite doesn't support FTS5 queries with
        # column filters ('{column_1 column_2} : query'), which the sqlite
        # fulltext backend needs
        return False

    tmp_db = sqlite3.connect(':memory:')
    try:
        tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);')
    except OperationalError:
        return False
    finally:
        tmp_db.close()

    return True

def fts_table_exists():
    from wagtail.search.models import SQLiteFTSIndexEntry

    try:
        # ignore result of query; we are only interested in the query failing,
        # not the presence of index entries
        SQLiteFTSIndexEntry.objects.exists()
    except OperationalError:
        return False

    return True


import pymodm
import slugify

class DevicePlot(pymodm.MongoModel):
    device_name = pymodm.fields.CharField()
    slug = pymodm.fields.CharField()
    plot_title = pymodm.fields.CharField()
    x_label = pymodm.fields.CharField()
    y_label = pymodm.fields.CharField()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify.slugify(self.device_name)
        super(DevicePlot, self).save(*args, **kwargs)

class PlotPoints(pymodm.MongoModel):
    device_plot = pymodm.fields.ReferenceField(DevicePlot)
    label = pymodm.fields.CharField()
    points = pymodm.fields.ListField(default=[])

    def save(self, *args, **kwargs):
        # TODO: configurable setting...
	if len(self.points) >= 30:
	    self.points = self.points[-30:]
	super(PlotPoints, self).save(*args, **kwargs)

Response:
import pymodm
import slugify

class DevicePlot(pymodm.MongoModel):
    device_name = pymodm.fields.CharField()
    slug = pymodm.fields.CharField()
    plot_title = pymodm.fields.CharField()
    x_label = pymodm.fields.CharField()
    y_label = pymodm.fields.CharField()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify.slugify(self.device_name)
        super(DevicePlot, self).save(*args, **kwargs)

class PlotPoints(pymodm.MongoModel):
    device_plot = pymodm.fields.ReferenceField(DevicePlot)
    label = pymodm.fields.CharField()
    points = pymodm.fields.ListField(default=[])

    def save(self, *args, **kwargs):
        # TODO: configurable setting...
	if len(self.points) >= 30:
	    self.points = self.points[-30:]
	super(PlotPoints, self).save(*args, **kwargs)

Prompt:
Fix bug to only store the 30 most recent points

import pymodm
import slugify

class DevicePlot(pymodm.MongoModel):
    device_name = pymodm.fields.CharField()
    slug = pymodm.fields.CharField()
    plot_title = pymodm.fields.CharField()
    x_label = pymodm.fields.CharField()
    y_label = pymodm.fields.CharField()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify.slugify(self.device_name)
        super(DevicePlot, self).save(*args, **kwargs)

class PlotPoints(pymodm.MongoModel):
    device_plot = pymodm.fields.ReferenceField(DevicePlot)
    label = pymodm.fields.CharField()
    points = pymodm.fields.ListField(default=[])

    def save(self, *args, **kwargs):
        # TODO: configurable setting...
	if len(self.points) >= 30:
	    self.points = self.points[30:]
	super(PlotPoints, self).save(*args, **kwargs)


from fabric.api import run, quiet
from braid import succeeds, cacheInEnvironment

@cacheInEnvironment
def distroName():
    """
    Get the name of the distro.
    """
    with quiet():
        lsb = run('lsb_release --id --short', warn_only=True)
        if lsb.succeeded:
            return lsb.lower()

        distros = [
                ('centos', '/etc/centos-release'),
                ('fedora', '/etc/fedora-release'),
                ]
        for distro, sentinel in distros:
            if succeeds('test -f {}'.format(sentinel)):
                return distro

def distroFamily():
    """
    Get the family of the distro.

    @returns: C{'debian'} or C{'fedora'}
    """
    families = {
            'debian': ['debian', 'ubuntu'],
            'fedora': ['fedora', 'centos', 'rhel'],
            }
    distro = distroName()
    for family, members in families.iteritems():
        if distro in members:
            return family
    return 'other'

Add some tools for detecting the remote distribution.

Response:
from fabric.api import run, quiet
from braid import succeeds, cacheInEnvironment

@cacheInEnvironment
def distroName():
    """
    Get the name of the distro.
    """
    with quiet():
        lsb = run('lsb_release --id --short', warn_only=True)
        if lsb.succeeded:
            return lsb.lower()

        distros = [
                ('centos', '/etc/centos-release'),
                ('fedora', '/etc/fedora-release'),
                ]
        for distro, sentinel in distros:
            if succeeds('test -f {}'.format(sentinel)):
                return distro

def distroFamily():
    """
    Get the family of the distro.

    @returns: C{'debian'} or C{'fedora'}
    """
    families = {
            'debian': ['debian', 'ubuntu'],
            'fedora': ['fedora', 'centos', 'rhel'],
            }
    distro = distroName()
    for family, members in families.iteritems():
        if distro in members:
            return family
    return 'other'

Prompt: Add some tools for detecting the remote distribution.


from django.apps import AppConfig
from django.conf import settings

import session_csrf

class AtmoAppConfig(AppConfig):
    name = 'atmo'

    def ready(self):
        # The app is now ready. Include any monkey patches here.

        # Monkey patch CSRF to switch to session based CSRF. Session
        # based CSRF will prevent attacks from apps under the same
        # domain. If you're planning to host your app under it's own
        # domain you can remove session_csrf and use Django's CSRF
        # library. See also
        # https://github.com/mozilla/sugardough/issues/38
        session_csrf.monkeypatch()

        # Under some circumstances (e.g. when calling collectstatic)
        # REDIS_URL is not available and we can skip the job schedule registration.
        if settings.REDIS_URL.hostname:
            # This module  contains references to some orm models, so it's
            # safer to import it here.
            from .schedule import register_job_schedule
            # Register rq scheduled jobs
            register_job_schedule()

Fix rq jobs registration check

Fix rq jobs registration check

Response:
from django.apps import AppConfig
from django.conf import settings

import session_csrf

class AtmoAppConfig(AppConfig):
    name = 'atmo'

    def ready(self):
        # The app is now ready. Include any monkey patches here.

        # Monkey patch CSRF to switch to session based CSRF. Session
        # based CSRF will prevent attacks from apps under the same
        # domain. If you're planning to host your app under it's own
        # domain you can remove session_csrf and use Django's CSRF
        # library. See also
        # https://github.com/mozilla/sugardough/issues/38
        session_csrf.monkeypatch()

        # Under some circumstances (e.g. when calling collectstatic)
        # REDIS_URL is not available and we can skip the job schedule registration.
        if settings.REDIS_URL.hostname:
            # This module  contains references to some orm models, so it's
            # safer to import it here.
            from .schedule import register_job_schedule
            # Register rq scheduled jobs
            register_job_schedule()

Prompt:
Fix rq jobs registration check

from django.apps import AppConfig
from django.conf import settings

import session_csrf

class AtmoAppConfig(AppConfig):
    name = 'atmo'

    def ready(self):
        # The app is now ready. Include any monkey patches here.

        # Monkey patch CSRF to switch to session based CSRF. Session
        # based CSRF will prevent attacks from apps under the same
        # domain. If you're planning to host your app under it's own
        # domain you can remove session_csrf and use Django's CSRF
        # library. See also
        # https://github.com/mozilla/sugardough/issues/38
        session_csrf.monkeypatch()

        # Under some circumstances (e.g. when calling collectstatic)
        # REDIS_URL is not available and we can skip the job schedule registration.
        if getattr(settings, 'REDIS_URL'):
            # This module  contains references to some orm models, so it's
            # safer to import it here.
            from .schedule import register_job_schedule
            # Register rq scheduled jobs
            register_job_schedule()


from numba import *
import unittest

class TestRedefine(unittest.TestCase):
    def test_redefine(self):

        def foo(x):
            return x + 1

        jfoo = jit(int32(int32))(foo)

        # Test original function
        self.assertTrue(jfoo(1), 2)

        jfoo = jit(int32(int32))(foo)

        # Test re-compiliation
        self.assertTrue(jfoo(2), 3)

        def foo(x):
            return x + 2

        jfoo = jit(int32(int32))(foo)

        # Test redefinition
        self.assertTrue(jfoo(1), 3)

Add test for function re-definition

Add test for function re-definition

Response:
from numba import *
import unittest

class TestRedefine(unittest.TestCase):
    def test_redefine(self):

        def foo(x):
            return x + 1

        jfoo = jit(int32(int32))(foo)

        # Test original function
        self.assertTrue(jfoo(1), 2)

        jfoo = jit(int32(int32))(foo)

        # Test re-compiliation
        self.assertTrue(jfoo(2), 3)

        def foo(x):
            return x + 2

        jfoo = jit(int32(int32))(foo)

        # Test redefinition
        self.assertTrue(jfoo(1), 3)

Prompt: Add test for function re-definition


from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from keras.engine.topology import merge

from eva.layers.masked_convolution2d import MaskedConvolution2D

def ResidualBlock(model, filters):
    # 2h -> h
    block = Convolution2D(filters//2, 1, 1)(model)
    block = PReLU()(block)

    # h 3x3 -> h
    block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block)
    block = PReLU()(block)

    # h -> 2h
    block = Convolution2D(filters, 1, 1)(block)

    return PReLU()(merge([model, block], mode='sum'))

def ResidualBlockList(model, filters, length):
    for _ in range(length):
        model = ResidualBlock(model, filters)

    return model

Response:
from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from keras.engine.topology import merge

from eva.layers.masked_convolution2d import MaskedConvolution2D

def ResidualBlock(model, filters):
    # 2h -> h
    block = Convolution2D(filters//2, 1, 1)(model)
    block = PReLU()(block)

    # h 3x3 -> h
    block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block)
    block = PReLU()(block)

    # h -> 2h
    block = Convolution2D(filters, 1, 1)(block)

    return PReLU()(merge([model, block], mode='sum'))

def ResidualBlockList(model, filters, length):
    for _ in range(length):
        model = ResidualBlock(model, filters)

    return model

Prompt:
Use the functional merge; just for formatting

from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from keras.engine.topology import merge

from eva.layers.masked_convolution2d import MaskedConvolution2D

def ResidualBlock(model, filters):
    # 2h -> h
    block = Convolution2D(filters//2, 1, 1)(model)
    block = PReLU()(block)

    # h 3x3 -> h
    block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block)
    block = PReLU()(block)

    # h -> 2h
    block = Convolution2D(filters, 1, 1)(block)

    return PReLU()(Merge(mode='sum')([model, block]))

def ResidualBlockList(model, filters, length):
    for _ in range(length):
        model = ResidualBlock(model, filters)

    return model


from os.path import join, splitext, basename
from bricks.staticfiles import StaticCss, StaticJs, StaticFile

class _BuiltStatic(StaticFile):
    has_build_stage = True

    def __init__(self, *args):
        StaticFile.__init__(self, *args)
        self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type

class Sass(_BuiltStatic):
    relpath = 'scss'
    target_type = 'css'

class Coffee(_BuiltStatic):
    relpath = 'coffee'
    target_type = 'js'

class StaticLib(StaticFile):
    """A static asset or a directory with static assets that's needed
    to build other static assets but is not directly used by the page."""
    has_build_stage = True

    def __call__(self):
        return ''

class SassLib(StaticLib):
    relpath = 'scss'

Response:
from os.path import join, splitext, basename
from bricks.staticfiles import StaticCss, StaticJs, StaticFile

class _BuiltStatic(StaticFile):
    has_build_stage = True

    def __init__(self, *args):
        StaticFile.__init__(self, *args)
        self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type

class Sass(_BuiltStatic):
    relpath = 'scss'
    target_type = 'css'

class Coffee(_BuiltStatic):
    relpath = 'coffee'
    target_type = 'js'

class StaticLib(StaticFile):
    """A static asset or a directory with static assets that's needed
    to build other static assets but is not directly used by the page."""
    has_build_stage = True

    def __call__(self):
        return ''

class SassLib(StaticLib):
    relpath = 'scss'

Prompt:
Revert "fixed rendering of Sass and Coffee"

This reverts commit b21834c9d439603f666d17aea338934bae063ef4.

from os.path import join, splitext, basename
from bricks.staticfiles import StaticCss, StaticJs, StaticFile

class _BuiltStatic(StaticFile):
    has_build_stage = True

    def __init__(self, *args):
        StaticFile.__init__(self, *args)
        self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type

class Sass(_BuiltStatic):
    relpath = 'scss'
    target_type = 'css'

    def __call__(self):
        return '<link rel="stylesheet" href="{}" />'.format(self.url)

class Coffee(_BuiltStatic):
    relpath = 'coffee'
    target_type = 'js'

    def __call__(self):
        return '<script src="{}"></script>'.format(self.url)

class StaticLib(StaticFile):
    """A static asset or a directory with static assets that's needed
    to build other static assets but is not directly used by the page."""
    has_build_stage = True

    def __call__(self):
        return ''

class SassLib(StaticLib):
    relpath = 'scss'


import logging
import telebot
import timer
import bot
import os

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logging.info("Begin start server.")
tgBot = telebot.TeleBot(os.getenv("BOT_ID", ""))

bot.getTracker(tgBot, logging)()

timer.getTimer(tgBot, logging)("Timer").start()

logging.info("Start polling")

tgBot.polling(none_stop=True)

Change While True Try to none_stop=True

Change While True Try to none_stop=True

Response:
import logging
import telebot
import timer
import bot
import os

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logging.info("Begin start server.")
tgBot = telebot.TeleBot(os.getenv("BOT_ID", ""))

bot.getTracker(tgBot, logging)()

timer.getTimer(tgBot, logging)("Timer").start()

logging.info("Start polling")

tgBot.polling(none_stop=True)

Prompt:
Change While True Try to none_stop=True

import logging
import telebot
import timer
import bot
import os

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logging.info("Begin start server.")
tgBot = telebot.TeleBot(os.getenv("BOT_ID", ""))

bot.getTracker(tgBot, logging)()

timer.getTimer(tgBot, logging)("Timer").start()

logging.info("Start polling")
while True:
    try:
        tgBot.polling()
    except Exception as e:
        logging.error(e.message)

#
# import api
#
# print api.TrackerApi.getPackageInformation(3325607157191, "shentong")


# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-05-07 16:20
from __future__ import unicode_literals

import django.contrib.postgres.fields.jsonb
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('councilmatic_core', '0040_mediaevent_meta'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='extras',
            field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
        ),
        migrations.RunSQL('''
            UPDATE councilmatic_core_event
              SET extras = json_build_object('guid', guid)
              WHERE guid IS NOT NULL
        ''', reverse_sql='''
            UPDATE councilmatic_core_event
              SET guid = extras->'guid'
              WHERE extras->'guid' IS NOT NULL
        '''),
        migrations.RemoveField(
            model_name='event',
            name='guid',
        ),
    ]

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-05-07 16:20
from __future__ import unicode_literals

import django.contrib.postgres.fields.jsonb
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('councilmatic_core', '0040_mediaevent_meta'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='extras',
            field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
        ),
        migrations.RunSQL('''
            UPDATE councilmatic_core_event
              SET extras = json_build_object('guid', guid)
              WHERE guid IS NOT NULL
        ''', reverse_sql='''
            UPDATE councilmatic_core_event
              SET guid = extras->'guid'
              WHERE extras->'guid' IS NOT NULL
        '''),
        migrations.RemoveField(
            model_name='event',
            name='guid',
        ),
    ]

Prompt:
Use json_build_object, rather than jsonb_build_object

# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-05-07 16:20
from __future__ import unicode_literals

import django.contrib.postgres.fields.jsonb
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('councilmatic_core', '0040_mediaevent_meta'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='extras',
            field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
        ),
        migrations.RunSQL('''
            UPDATE councilmatic_core_event
              SET extras = jsonb_build_object('guid', guid)
              WHERE guid IS NOT NULL
        ''', reverse_sql='''
            UPDATE councilmatic_core_event
              SET guid = extras->'guid'
              WHERE extras->'guid' IS NOT NULL
        '''),
        migrations.RemoveField(
            model_name='event',
            name='guid',
        ),
    ]


import urllib as _urllib

class HTTPError(IOError):
    def __init__(self, code, msg, headers):
        IOError.__init__(self, 'HTTP error', code, msg, headers)
    def __str__(self):
        return "HTTP: %d %s" % (self.args[1], self.args[2])

class MyURLOpener(_urllib.FancyURLopener):
    def http_error_default(self, url, fp, errcode, errmsg, headers):
        fp.close()
        raise HTTPError(errcode, errmsg, headers)

_urlopener = None
def myurlopen(url, data=None, proxies=None):
    """
    As urllib.urlopen, but raises HTTPErrors on HTTP failure
    """
    global _urlopener
    if proxies is not None:
        opener = MyURLOpener(proxies=proxies)
    elif not _urlopener:
        opener = MyURLOpener()
        _urlopener = opener
    else:
        opener = _urlopener
    if data is None:
        return opener.open(url)
    else:
        return opener.open(url, data)

__all__ = ['myurlopen']

Add an exception-raising-on-http-error urlopen function

Response:
import urllib as _urllib

class HTTPError(IOError):
    def __init__(self, code, msg, headers):
        IOError.__init__(self, 'HTTP error', code, msg, headers)
    def __str__(self):
        return "HTTP: %d %s" % (self.args[1], self.args[2])

class MyURLOpener(_urllib.FancyURLopener):
    def http_error_default(self, url, fp, errcode, errmsg, headers):
        fp.close()
        raise HTTPError(errcode, errmsg, headers)

_urlopener = None
def myurlopen(url, data=None, proxies=None):
    """
    As urllib.urlopen, but raises HTTPErrors on HTTP failure
    """
    global _urlopener
    if proxies is not None:
        opener = MyURLOpener(proxies=proxies)
    elif not _urlopener:
        opener = MyURLOpener()
        _urlopener = opener
    else:
        opener = _urlopener
    if data is None:
        return opener.open(url)
    else:
        return opener.open(url, data)

__all__ = ['myurlopen']

Prompt: Add an exception-raising-on-http-error urlopen function


"""
Glue some events together
"""

from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.translation import ugettext as _

import helios.views, helios.signals

import views

def vote_cast_send_message(user, voter, election, cast_vote, **kwargs):
  ## FIXME: this doesn't work for voters that are not also users
  # prepare the message
  subject = _("%(election_name)s - vote cast") % {'election_name' : election.name}

  body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name}

  body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)}

  if election.use_voter_aliases:
    body += _('\nThis election uses voter aliases to protect your privacy.'
'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias}

  body += """

--
%s
""" % settings.SITE_TITLE

  # send it via the notification system associated with the auth system
  user.send_message(subject, body)

helios.signals.vote_cast.connect(vote_cast_send_message)

def election_tallied(election, **kwargs):
  pass

helios.signals.election_tallied.connect(election_tallied)

Add blank space in email message

Add blank space in email message

Response:
"""
Glue some events together
"""

from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.translation import ugettext as _

import helios.views, helios.signals

import views

def vote_cast_send_message(user, voter, election, cast_vote, **kwargs):
  ## FIXME: this doesn't work for voters that are not also users
  # prepare the message
  subject = _("%(election_name)s - vote cast") % {'election_name' : election.name}

  body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name}

  body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)}

  if election.use_voter_aliases:
    body += _('\nThis election uses voter aliases to protect your privacy.'
'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias}

  body += """

--
%s
""" % settings.SITE_TITLE

  # send it via the notification system associated with the auth system
  user.send_message(subject, body)

helios.signals.vote_cast.connect(vote_cast_send_message)

def election_tallied(election, **kwargs):
  pass

helios.signals.election_tallied.connect(election_tallied)

Prompt:
Add blank space in email message

"""
Glue some events together
"""

from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.translation import ugettext as _

import helios.views, helios.signals

import views

def vote_cast_send_message(user, voter, election, cast_vote, **kwargs):
  ## FIXME: this doesn't work for voters that are not also users
  # prepare the message
  subject = _("%(election_name)s - vote cast") % {'election_name' : election.name}

  body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name}

  body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)}

  if election.use_voter_aliases:
    body += _('This election uses voter aliases to protect your privacy.'
'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias}

  body += """

--
%s
""" % settings.SITE_TITLE

  # send it via the notification system associated with the auth system
  user.send_message(subject, body)

helios.signals.vote_cast.connect(vote_cast_send_message)

def election_tallied(election, **kwargs):
  pass

helios.signals.election_tallied.connect(election_tallied)


# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp.tests.common import TransactionCase
from openerp.exceptions import Warning

class TestMedicalPatientSpecies(TransactionCase):

    def setUp(self):
        super(TestMedicalPatientSpecies, self).setUp()
        self.human = self.env.ref('medical_patient_species.human')
        self.dog = self.env.ref('medical_patient_species.dog')

    def test_unlink_human(self):
        ''' Test raises Warning if unlinking human '''
        with self.assertRaises(Warning):
            self.human.unlink()

Response:
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp.tests.common import TransactionCase
from openerp.exceptions import Warning

class TestMedicalPatientSpecies(TransactionCase):

    def setUp(self):
        super(TestMedicalPatientSpecies, self).setUp()
        self.human = self.env.ref('medical_patient_species.human')
        self.dog = self.env.ref('medical_patient_species.dog')

    def test_unlink_human(self):
        ''' Test raises Warning if unlinking human '''
        with self.assertRaises(Warning):
            self.human.unlink()

Prompt:
[FIX] medical_patient_species: Remove tests for is_person (default is False, human set to True in xml).
Re-add test ensuring warning raised if trying to unlink Human.

# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp.tests.common import TransactionCase

class TestMedicalPatientSpecies(TransactionCase):

    def setUp(self):
        super(TestMedicalPatientSpecies, self).setUp()
        self.human = self.env.ref('medical_patient_species.human')
        self.dog = self.env.ref('medical_patient_species.dog')

    def test_create_is_person(self):
        ''' Tests on creation if Human, is_person is True '''
        self.assertTrue(
            self.human.is_person, 'Should be True if Human'
        )

    def test_create_not_is_person(self):
        ''' Tests on creation if not Human, is_person is False '''
        self.assertFalse(
            self.dog.is_person, 'Should be False if not Human'
        )


'''
   Copyright 2015 OneRTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin)

   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.
'''

Use source file with license 2

Use source file with license 2

Response:
'''
   Copyright 2015 OneRTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin)

   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.
'''

Prompt:
Use source file with license 2

'''   Copyright 2015 RTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin)

   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.
'''


# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1

import pep8

class RespectNoqaReport(pep8.StandardReport):

    def error(self, line_number, offset, text, check):
        if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
            return
        else:
            return super(RespectNoqaReport, self).error(line_number, offset,
                                                        text, check)

class RespectNoqa(object):
    name = 'flake8-respect-noqa'
    version = __version__

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def parse_options(cls, options):
        # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
        # or put "jobs = 1" in your [flake8] config.
        # Otherwise, flake8 replaces this reported with it's own.
        # See https://gitlab.com/pycqa/flake8/issues/66
        options.reporter = RespectNoqaReport
        options.report = RespectNoqaReport(options)

Response:
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1

import pep8

class RespectNoqaReport(pep8.StandardReport):

    def error(self, line_number, offset, text, check):
        if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
            return
        else:
            return super(RespectNoqaReport, self).error(line_number, offset,
                                                        text, check)

class RespectNoqa(object):
    name = 'flake8-respect-noqa'
    version = __version__

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def parse_options(cls, options):
        # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
        # or put "jobs = 1" in your [flake8] config.
        # Otherwise, flake8 replaces this reported with it's own.
        # See https://gitlab.com/pycqa/flake8/issues/66
        options.reporter = RespectNoqaReport
        options.report = RespectNoqaReport(options)

Prompt:
Fix for case when file can't be opened due to IOError or similar

# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1

import pep8

class RespectNoqaReport(pep8.StandardReport):

    def error(self, line_number, offset, text, check):
        if pep8.noqa(self.lines[line_number - 1]):
            return
        else:
            return super(RespectNoqaReport, self).error(line_number, offset,
                                                        text, check)

class RespectNoqa(object):
    name = 'flake8-respect-noqa'
    version = __version__

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def parse_options(cls, options):
        # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
        # or put "jobs = 1" in your [flake8] config.
        # Otherwise, flake8 replaces this reported with it's own.
        # See https://gitlab.com/pycqa/flake8/issues/66
        options.reporter = RespectNoqaReport
        options.report = RespectNoqaReport(options)


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

from solum.api import auth

# Pecan Application Configurations
app = {
    'root': 'solum.builder.controllers.root.RootController',
    'modules': ['solum.builder'],
    'debug': True,
    'hooks': [auth.AuthInformationHook()]
}

# Custom Configurations must be in Python dictionary format::
#
# foo = {'bar':'baz'}
#
# All configurations are accessible at::
# pecan.conf

Add missing Auth hook to image builder

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

from solum.api import auth

# Pecan Application Configurations
app = {
    'root': 'solum.builder.controllers.root.RootController',
    'modules': ['solum.builder'],
    'debug': True,
    'hooks': [auth.AuthInformationHook()]
}

# Custom Configurations must be in Python dictionary format::
#
# foo = {'bar':'baz'}
#
# All configurations are accessible at::
# pecan.conf

Prompt:
Add missing Auth hook to image builder

Change-Id: I73f17c17a1f4d530c0351dacc2b10fbdcf3122e0

# Copyright 2014 - Rackspace Hosting
#
# 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.

# Pecan Application Configurations
app = {
    'root': 'solum.builder.controllers.root.RootController',
    'modules': ['solum.builder'],
    'debug': True,
}

# Custom Configurations must be in Python dictionary format::
#
# foo = {'bar':'baz'}
#
# All configurations are accessible at::
# pecan.conf


# -*- coding: utf-8 -*-
import numpy as np
import ibei
from astropy import units
import unittest

temp_sun = 5762.
temp_earth = 288.
bandgap = 1.15

class Issues(unittest.TestCase):
    """
    Tests output types of the calculator methods.
    """
    def test_issue_1_devos_efficiency(self):
        """
        Unit system needs to be specified for astropy.constants.e to work.
        """
        try:
            ibei.devos_efficiency(bandgap, temp_sun, temp_earth, 1.09)
        except:
            self.fail("Unit system not initialized.")

Add tests for issues causing exceptions

Add tests for issues causing exceptions

Response:
# -*- coding: utf-8 -*-
import numpy as np
import ibei
from astropy import units
import unittest

temp_sun = 5762.
temp_earth = 288.
bandgap = 1.15

class Issues(unittest.TestCase):
    """
    Tests output types of the calculator methods.
    """
    def test_issue_1_devos_efficiency(self):
        """
        Unit system needs to be specified for astropy.constants.e to work.
        """
        try:
            ibei.devos_efficiency(bandgap, temp_sun, temp_earth, 1.09)
        except:
            self.fail("Unit system not initialized.")

Prompt: Add tests for issues causing exceptions


"""Read and print an integer series."""

import sys

def read_series(filename):
    try:
        f = open(filename, mode='rt', encoding='utf-8')
        return [int(line.strip()) for line in f]
    finally:
        f.close()

def main(filename):
    print(read_series(filename))

if __name__ == '__main__':
    main(sys.argv[1])

Response:
"""Read and print an integer series."""

import sys

def read_series(filename):
    try:
        f = open(filename, mode='rt', encoding='utf-8')
        return [int(line.strip()) for line in f]
    finally:
        f.close()

def main(filename):
    print(read_series(filename))

if __name__ == '__main__':
    main(sys.argv[1])

Prompt:
Refactor to ensure closing and also use list comprehension

"""Read and print an integer series."""

import sys

def read_series(filename):
    f = open(filename, mode='rt', encoding='utf-8')
    series = []
    for line in f:
        a = int(line.strip())
        series.append(a)
    f.close()
    return series

def main(filename):
    print(read_series(filename))

if __name__ == '__main__':
    main(sys.argv[1])


"""
========================================
The :mod:`array_split.split_plot` Module
========================================

Uses :mod:`matplotlib` to plot a split.

Classes and Functions
=====================

.. autosummary::
   :toctree: generated/

   SplitPlotter - Plots a split.
   plot - Plots split shapes.

"""

from __future__ import absolute_import

from .license import license as _license, copyright as _copyright, version as _version

__author__ = "Shane J. Latham"
__license__ = _license()
__copyright__ = _copyright()
__version__ = _version()

class SplitPlotter(object):
    """
    Plots a split.
    """

    def __init__(self):
        """
        """
        pass

def plot(split):
    """
    Plots a split.
    """

Add skeleton for plotting split.

Add skeleton for plotting split.

Response:
"""
========================================
The :mod:`array_split.split_plot` Module
========================================

Uses :mod:`matplotlib` to plot a split.

Classes and Functions
=====================

.. autosummary::
   :toctree: generated/

   SplitPlotter - Plots a split.
   plot - Plots split shapes.

"""

from __future__ import absolute_import

from .license import license as _license, copyright as _copyright, version as _version

__author__ = "Shane J. Latham"
__license__ = _license()
__copyright__ = _copyright()
__version__ = _version()

class SplitPlotter(object):
    """
    Plots a split.
    """

    def __init__(self):
        """
        """
        pass

def plot(split):
    """
    Plots a split.
    """

Prompt: Add skeleton for plotting split.


# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-19 11:14
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import modelcluster.fields
import wagtail.wagtailcore.fields

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('longclawproducts', '0002_auto_20170219_0804'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProductVariant',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('price', models.DecimalField(decimal_places=2, max_digits=12)),
                ('ref', models.CharField(max_length=32)),
                ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')),
                ('description', wagtail.wagtailcore.fields.RichTextField()),
                ('stock', models.IntegerField(default=0)),
                ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]

Correct migration in project template

Correct migration in project template

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-19 11:14
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import modelcluster.fields
import wagtail.wagtailcore.fields

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('longclawproducts', '0002_auto_20170219_0804'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProductVariant',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('price', models.DecimalField(decimal_places=2, max_digits=12)),
                ('ref', models.CharField(max_length=32)),
                ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')),
                ('description', wagtail.wagtailcore.fields.RichTextField()),
                ('stock', models.IntegerField(default=0)),
                ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]

Prompt:
Correct migration in project template

# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-19 11:14
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import modelcluster.fields
import wagtail.wagtailcore.fields

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('longclawproducts', '0002_auto_20170219_0804'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProductVariant',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('price', models.DecimalField(decimal_places=2, max_digits=12)),
                ('ref', models.CharField(max_length=32)),
                ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')),
                ('description', wagtail.wagtailcore.fields.RichTextField()),
                ('stock', models.IntegerField(default=0)),
                ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]


import xml.etree.ElementTree as ET
from urllib.parse import unquote, urlparse
import os
import sys
from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]'
import re

files = [unquote(urlparse(el.text).path)
		for el in ET.parse(sys.argv[1]).getroot()
			.findall(".//*/{http://xspf.org/ns/0/}location")
	]
pfx = len(os.path.commonprefix(files))
trimmed = [re.search(r" - ([^_]+)", f[pfx:]).group(1) for f in files]
for i, file in enumerate(files):
	others = trimmed[i + 1:] # Assume that similarity is commutative
	any = False
	for name, score in process.extractBests(trimmed[i], others, score_cutoff=80, scorer=fuzz.token_set_ratio):
		if not any:
			any = True
			print(file)
		print(name)
	if any: print("-----")

Create a little dedup script, probably not very general

Response:
import xml.etree.ElementTree as ET
from urllib.parse import unquote, urlparse
import os
import sys
from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]'
import re

files = [unquote(urlparse(el.text).path)
		for el in ET.parse(sys.argv[1]).getroot()
			.findall(".//*/{http://xspf.org/ns/0/}location")
	]
pfx = len(os.path.commonprefix(files))
trimmed = [re.search(r" - ([^_]+)", f[pfx:]).group(1) for f in files]
for i, file in enumerate(files):
	others = trimmed[i + 1:] # Assume that similarity is commutative
	any = False
	for name, score in process.extractBests(trimmed[i], others, score_cutoff=80, scorer=fuzz.token_set_ratio):
		if not any:
			any = True
			print(file)
		print(name)
	if any: print("-----")

Prompt: Create a little dedup script, probably not very general


'''Script to help generate item names.'''

def int_to_str(num, alphabet):
    '''Convert integer to string.'''
    # http://stackoverflow.com/a/1119769/1524507
    if (num == 0):
        return alphabet[0]
    arr = []
    base = len(alphabet)
    while num:
        rem = num % base
        num = num // base
        arr.append(alphabet[rem])
    arr.reverse()
    return ''.join(arr)

def main():
    start_num = 0
    end_num = 2176782335
    pics_per_item = 1000

    counter = start_num
    while True:
        lower = counter
        upper = min(counter + pics_per_item, end_num)

        print('picture:{0}-{1}'.format(lower, upper))

        counter += 1000
        if counter > end_num:
            break

if __name__ == '__main__':
    main()

Add util script to generate item names.

Add util script to generate item names.

Response:
'''Script to help generate item names.'''

def int_to_str(num, alphabet):
    '''Convert integer to string.'''
    # http://stackoverflow.com/a/1119769/1524507
    if (num == 0):
        return alphabet[0]
    arr = []
    base = len(alphabet)
    while num:
        rem = num % base
        num = num // base
        arr.append(alphabet[rem])
    arr.reverse()
    return ''.join(arr)

def main():
    start_num = 0
    end_num = 2176782335
    pics_per_item = 1000

    counter = start_num
    while True:
        lower = counter
        upper = min(counter + pics_per_item, end_num)

        print('picture:{0}-{1}'.format(lower, upper))

        counter += 1000
        if counter > end_num:
            break

if __name__ == '__main__':
    main()

Prompt: Add util script to generate item names.


import logging

import requests

def input_file(filename):
    """
    Read a file and return list of usernames.

    Assumes one username per line and ignores blank lines.
    """
    with open(filename, 'r') as f:
        return list(line.strip() for line in f if line.strip())

def org_members(org_name):
    """
    Query Github API and return list of members from a Github organization.
    """
    if org_name is None:
        org_name = 'pulseenergy'

    url = 'https://github.com/orgs/{}/members'.format(org_name)
    headers = {'Accept': 'application/vnd.github.ironman-preview+json'}
    try:
        r = requests.get(url, headers=headers)
    except requests.exceptions.ConnectionError:
        logging.warn('Connection error trying to get org members: [{}]'.format(url))
        return []
    if r.status_code == 404:
        print('Got 404')
        print(r.status_code)
    return []

    print('response')
    print(r.text)
    return r.text

def svg_data(username):
    """
    Returns the contribution streak SVG file contents from Github
    for a specific username.
    """
    url = 'https://github.com/users/{}/contributions'.format(username)
    try:
        r = requests.get(url)
    except requests.exceptions.ConnectionError:
        logging.warn('Connection error trying to get url: [{}]'.format(url))
        return None

    return r.text

Response:
import logging

import requests

def input_file(filename):
    """
    Read a file and return list of usernames.

    Assumes one username per line and ignores blank lines.
    """
    with open(filename, 'r') as f:
        return list(line.strip() for line in f if line.strip())

def org_members(org_name):
    """
    Query Github API and return list of members from a Github organization.
    """
    if org_name is None:
        org_name = 'pulseenergy'

    url = 'https://github.com/orgs/{}/members'.format(org_name)
    headers = {'Accept': 'application/vnd.github.ironman-preview+json'}
    try:
        r = requests.get(url, headers=headers)
    except requests.exceptions.ConnectionError:
        logging.warn('Connection error trying to get org members: [{}]'.format(url))
        return []
    if r.status_code == 404:
        print('Got 404')
        print(r.status_code)
    return []

    print('response')
    print(r.text)
    return r.text

def svg_data(username):
    """
    Returns the contribution streak SVG file contents from Github
    for a specific username.
    """
    url = 'https://github.com/users/{}/contributions'.format(username)
    try:
        r = requests.get(url)
    except requests.exceptions.ConnectionError:
        logging.warn('Connection error trying to get url: [{}]'.format(url))
        return None

    return r.text

Prompt:
Handle None for org or file with default org name

import logging

import requests

def input_file(filename):
    """
    Read a file and return list of usernames.

    Assumes one username per line and ignores blank lines.
    """
    with open(filename, 'r') as f:
        return list(line.strip() for line in f if line.strip())

def org_members(org_name):
    """
    Query Github API and return list of members from a Github organization.
    """
    url = 'https://github.com/orgs/{}/members'.format(org_name)
    headers = {'Accept': 'application/vnd.github.ironman-preview+json'}
    try:
        r = requests.get(url, headers=headers)
    except requests.exceptions.ConnectionError:
        logging.warn('Connection error trying to get org members: [{}]'.format(url))
        return []
    if r.status_code == 404:
        print('Got 404')
        print(r.status_code)
    return []

    print('response')
    print(r.text)
    return r.text

def svg_data(username):
    """
    Returns the contribution streak SVG file contents from Github
    for a specific username.
    """
    url = 'https://github.com/users/{}/contributions'.format(username)
    try:
        r = requests.get(url)
    except requests.exceptions.ConnectionError:
        logging.warn('Connection error trying to get url: [{}]'.format(url))
        return None

    return r.text


#!/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:
#!/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:
# 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:
#!/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:
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:
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:
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:
# -*- 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:
#!/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:
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:
#!/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
)