from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from rest_framework.utils.serializer_helpers import ReturnDict

class CustomLimitOffsetPagination(LimitOffsetPagination):
    max_limit = 50

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('meta', OrderedDict([
                ('limit', self.limit),
                ('next', self.get_next_link()),
                ('offset', self.offset),
                ('previous', self.get_previous_link()),
                ('total_count', self.count),
            ])),
            ('objects', data),
        ]))

class SearchFacetListSerializer(ListSerializer):
    @property
    def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        ret = super(SearchFacetListSerializer, self).to_representation(instance)

        ret = OrderedDict([
            ('results', ret),
            ('facets', self._context.get('facets', {'fields': {}})),
        ])
        return ret

Add max limit to api pagination

Add max limit to api pagination

Response:
from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from rest_framework.utils.serializer_helpers import ReturnDict

class CustomLimitOffsetPagination(LimitOffsetPagination):
    max_limit = 50

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('meta', OrderedDict([
                ('limit', self.limit),
                ('next', self.get_next_link()),
                ('offset', self.offset),
                ('previous', self.get_previous_link()),
                ('total_count', self.count),
            ])),
            ('objects', data),
        ]))

class SearchFacetListSerializer(ListSerializer):
    @property
    def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        ret = super(SearchFacetListSerializer, self).to_representation(instance)

        ret = OrderedDict([
            ('results', ret),
            ('facets', self._context.get('facets', {'fields': {}})),
        ])
        return ret

Prompt:
Add max limit to api pagination
from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from rest_framework.utils.serializer_helpers import ReturnDict

class CustomLimitOffsetPagination(LimitOffsetPagination):
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('meta', OrderedDict([
                ('limit', self.limit),
                ('next', self.get_next_link()),
                ('offset', self.offset),
                ('previous', self.get_previous_link()),
                ('total_count', self.count),
            ])),
            ('objects', data),
        ]))

class SearchFacetListSerializer(ListSerializer):
    @property
    def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        ret = super(SearchFacetListSerializer, self).to_representation(instance)

        ret = OrderedDict([
            ('results', ret),
            ('facets', self._context.get('facets', {'fields': {}})),
        ])
        return ret


import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "{{cookiecutter.repo_name}}",
    version = "{{cookiecutter.version}}",
    author = "{{cookiecutter.full_name}}",
    author_email = "{{cookiecutter.email}}",
    description = "{{cookiecutter.short_description}}",
    license = "MIT",
    keywords=(
        "Python, cookiecutter, kivy, buildozer, pytest, projects, project "
        "templates, example, documentation, tutorial, setup.py, package, "
        "android, touch, mobile, NUI"
    ),
    url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires = ['kivy>=1.8.0'],
    package_data={
        '{{cookiecutter.repo_name}}': ['*.kv*']
    },
    entry_points={
        'console_scripts': [
            '{{cookiecutter.repo_name}}={{cookiecutter.repo_name}}.main:main'
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: X11 Applications',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Artistic Software',
        'Topic :: Multimedia :: Graphics :: Presentation',
        'Topic :: Software Development :: User Interfaces',
    ],
)

Set up console script for main

Set up console script for main

Response:
import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "{{cookiecutter.repo_name}}",
    version = "{{cookiecutter.version}}",
    author = "{{cookiecutter.full_name}}",
    author_email = "{{cookiecutter.email}}",
    description = "{{cookiecutter.short_description}}",
    license = "MIT",
    keywords=(
        "Python, cookiecutter, kivy, buildozer, pytest, projects, project "
        "templates, example, documentation, tutorial, setup.py, package, "
        "android, touch, mobile, NUI"
    ),
    url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires = ['kivy>=1.8.0'],
    package_data={
        '{{cookiecutter.repo_name}}': ['*.kv*']
    },
    entry_points={
        'console_scripts': [
            '{{cookiecutter.repo_name}}={{cookiecutter.repo_name}}.main:main'
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: X11 Applications',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Artistic Software',
        'Topic :: Multimedia :: Graphics :: Presentation',
        'Topic :: Software Development :: User Interfaces',
    ],
)

Prompt:
Set up console script for main

import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "{{cookiecutter.repo_name}}",
    version = "{{cookiecutter.version}}",
    author = "{{cookiecutter.full_name}}",
    author_email = "{{cookiecutter.email}}",
    description = "{{cookiecutter.short_description}}",
    license = "MIT",
    keywords=(
        "Python, cookiecutter, kivy, buildozer, pytest, projects, project "
        "templates, example, documentation, tutorial, setup.py, package, "
        "android, touch, mobile, NUI"
    ),
    url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires = ['kivy>=1.8.0'],
    package_data={
        '{{cookiecutter.repo_name}}': ['*.kv*']
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: X11 Applications',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Artistic Software',
        'Topic :: Multimedia :: Graphics :: Presentation',
        'Topic :: Software Development :: User Interfaces',
    ],
)


# Generated by Django 2.0.13 on 2020-04-23 12:55

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('signage', '0012_auto_20200406_1411'),
    ]

    operations = [
        migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]),
        migrations.RemoveField(
            model_name='blade',
            name='deleted',
        ),
        migrations.RemoveField(
            model_name='blade',
            name='structure',
        ),
        migrations.RemoveField(
            model_name='line',
            name='structure',
        ),
        migrations.AlterField(
            model_name='line',
            name='blade',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines',
                                    to='signage.Blade', verbose_name='Blade'),
        ),
    ]

Response:
# Generated by Django 2.0.13 on 2020-04-23 12:55

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('signage', '0012_auto_20200406_1411'),
    ]

    operations = [
        migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]),
        migrations.RemoveField(
            model_name='blade',
            name='deleted',
        ),
        migrations.RemoveField(
            model_name='blade',
            name='structure',
        ),
        migrations.RemoveField(
            model_name='line',
            name='structure',
        ),
        migrations.AlterField(
            model_name='line',
            name='blade',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines',
                                    to='signage.Blade', verbose_name='Blade'),
        ),
    ]

Prompt:
Remove element with deleted=true before removefield

# Generated by Django 2.0.13 on 2020-04-23 12:55

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('signage', '0012_auto_20200406_1411'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='blade',
            name='deleted',
        ),
        migrations.RemoveField(
            model_name='blade',
            name='structure',
        ),
        migrations.RemoveField(
            model_name='line',
            name='structure',
        ),
        migrations.AlterField(
            model_name='line',
            name='blade',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines',
                                    to='signage.Blade', verbose_name='Blade'),
        ),
    ]


from share.provider import ProviderAppConfig
from .harvester import OSFRegistrationsHarvester

class AppConfig(ProviderAppConfig):
    name = 'providers.io.osf.registrations'
    version = '0.0.1'
    title = 'osf_registrations'
    long_title = 'Open Science Framework Registrations'
    home_page = 'http://api.osf.io/registrations/'
    harvester = OSFRegistrationsHarvester

Add the app config for osf registrations

Response:
from share.provider import ProviderAppConfig
from .harvester import OSFRegistrationsHarvester

class AppConfig(ProviderAppConfig):
    name = 'providers.io.osf.registrations'
    version = '0.0.1'
    title = 'osf_registrations'
    long_title = 'Open Science Framework Registrations'
    home_page = 'http://api.osf.io/registrations/'
    harvester = OSFRegistrationsHarvester

Prompt: Add the app config for osf registrations


from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

for template_engine in TEMPLATES:
    template_engine['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'

try:
    import debug_toolbar
except ImportError:
     pass
else:
    INSTALLED_APPS += ('debug_toolbar',)
    MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INTERNAL_IPS = ('127.0.0.1', 'localhost')
    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

try:
    from .local import *
except ImportError:
    pass

try:
    from .polygons import *
except ImportError:
    pass

LOGGING = {
        'version': 1,
        'handlers': {
                'console': {
                        'class': 'logging.StreamHandler'},
        },
        'loggers': {'background_task': {'handlers': ['console'], 'level': 'INFO'}}}

try:
    INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
    pass

Print tracebacks that happened in tasks

Print tracebacks that happened in tasks

Response:
from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

for template_engine in TEMPLATES:
    template_engine['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'

try:
    import debug_toolbar
except ImportError:
     pass
else:
    INSTALLED_APPS += ('debug_toolbar',)
    MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INTERNAL_IPS = ('127.0.0.1', 'localhost')
    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

try:
    from .local import *
except ImportError:
    pass

try:
    from .polygons import *
except ImportError:
    pass

LOGGING = {
        'version': 1,
        'handlers': {
                'console': {
                        'class': 'logging.StreamHandler'},
        },
        'loggers': {'background_task': {'handlers': ['console'], 'level': 'INFO'}}}

try:
    INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
    pass

Prompt:
Print tracebacks that happened in tasks

from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

for template_engine in TEMPLATES:
    template_engine['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'

try:
    import debug_toolbar
except ImportError:
     pass
else:
    INSTALLED_APPS += ('debug_toolbar',)
    MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INTERNAL_IPS = ('127.0.0.1', 'localhost')
    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

try:
    from .local import *
except ImportError:
    pass

try:
    from .polygons import *
except ImportError:
    pass

try:
    INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
    pass


# -*- coding: utf-8 -*-

VERSION = (0, 12,)

__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)

Change the version to v0.12

Change the version to v0.12

Response:
# -*- coding: utf-8 -*-

VERSION = (0, 12,)

__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)

Prompt:
Change the version to v0.12

# -*- coding: utf-8 -*-

VERSION = (0, 11,)

__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)


"""
Warnings Module
===============

Contains a collection of warning messages for consistent package wide notifications

"""

#-Numba-#
numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n"
                            "This will reduce the overall performance of this package.\n"
                            "To install please use the anaconda distribution.\n"
                            "http://continuum.io/downloads")

Response:
"""
Warnings Module
===============

Contains a collection of warning messages for consistent package wide notifications

"""

#-Numba-#
numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n"
                            "This will reduce the overall performance of this package.\n"
                            "To install please use the anaconda distribution.\n"
                            "http://continuum.io/downloads")

Prompt:
Update warning message if numba import fails

"""
Warnings Module
===============

Contains a collection of warning messages for consistent package wide notifications

"""

#-Numba-#
numba_import_fail_message = "Numba import failed.  Falling back to non-optimized routine."


from os import environ

import dj_database_url

from .base import *

INSTALLED_APPS += (
    'djangosecure',
)

PRODUCTION_MIDDLEWARE_CLASSES = (
    'djangosecure.middleware.SecurityMiddleware',
)

MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES

DATABASES = {'default': dj_database_url.config()}

SECRET_KEY = environ.get('SECRET_KEY')

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [DOMAIN]

# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

SECURE_REDIRECT_EXEMPT = [
    '^(?!hub/).*'
]

Response:
from os import environ

import dj_database_url

from .base import *

INSTALLED_APPS += (
    'djangosecure',
)

PRODUCTION_MIDDLEWARE_CLASSES = (
    'djangosecure.middleware.SecurityMiddleware',
)

MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES

DATABASES = {'default': dj_database_url.config()}

SECRET_KEY = environ.get('SECRET_KEY')

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [DOMAIN]

# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

SECURE_REDIRECT_EXEMPT = [
    '^(?!hub/).*'
]

Prompt:
Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks
from os import environ

import dj_database_url

from .base import *

INSTALLED_APPS += (
    'djangosecure',
)

PRODUCTION_MIDDLEWARE_CLASSES = (
    'djangosecure.middleware.SecurityMiddleware',
)

MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES

DATABASES = {'default': dj_database_url.config()}

SECRET_KEY = environ.get('SECRET_KEY')

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [DOMAIN]

# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')


"""Utility for clearing all keys out of redis -- do not use in production!"""

import sys
from optparse import OptionParser

import redis

def option_parser():
    parser = OptionParser()
    parser.add_option("-f", "--force",
                      action="store_true", dest="force", default=False,
                      help="Don't ask for confirmation.")
    return parser

def main():
    parser = option_parser()
    options, args = parser.parse_args()
    if args:
        parser.print_help()
        return 1
    if not options.force:
        confirm = raw_input("About to delete ALL redis keys. "
                            "Press Y to confirm, N to exit: ")
        if confirm.lower() != 'y':
            return 1
    r_server = redis.Redis()
    keys = r_server.keys()
    for key in keys:
        r_server.delete(key)
    print "Deleted %i keys." % len(keys)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Add utility for clearing out redis keys from tests.

Response:
"""Utility for clearing all keys out of redis -- do not use in production!"""

import sys
from optparse import OptionParser

import redis

def option_parser():
    parser = OptionParser()
    parser.add_option("-f", "--force",
                      action="store_true", dest="force", default=False,
                      help="Don't ask for confirmation.")
    return parser

def main():
    parser = option_parser()
    options, args = parser.parse_args()
    if args:
        parser.print_help()
        return 1
    if not options.force:
        confirm = raw_input("About to delete ALL redis keys. "
                            "Press Y to confirm, N to exit: ")
        if confirm.lower() != 'y':
            return 1
    r_server = redis.Redis()
    keys = r_server.keys()
    for key in keys:
        r_server.delete(key)
    print "Deleted %i keys." % len(keys)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Prompt: Add utility for clearing out redis keys from tests.


import sys

s = 0.0

for line in sys.stdin:
    _, b, c = line.split()
    b, c = int(b), float(c)
    s += c * b

print(f'VALOR A PAGAR: R$ {s:.2f}')

Response:
import sys

s = 0.0

for line in sys.stdin:
    _, b, c = line.split()
    b, c = int(b), float(c)
    s += c * b

print(f'VALOR A PAGAR: R$ {s:.2f}')

Prompt:
Refactor python version of Simple Calculate

import sys

s = 0.0

for line in sys.stdin:
    a, b, c = line.split()
    a, b, c = int(a), int(b), float(c)
    s += c * b

print(f'VALOR A PAGAR: R$ {s:.2f}')


"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015  Dirk Beyer
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 benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])

class Tool(yogar_cbmc.Tool):

    REQUIRED_PATHS = [
                  "yogar-cbmc"
                  ]

    def executable(self):
        return util.find_executable('yogar-cbmc-parallel')

    def name(self):
        return 'Yogar-CBMC-Parallel'

    def cmdline(self, executable, options, tasks, propertyfile, rlimits):
        return [executable] + options + tasks

Response:
"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015  Dirk Beyer
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 benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])

class Tool(yogar_cbmc.Tool):

    REQUIRED_PATHS = [
                  "yogar-cbmc"
                  ]

    def executable(self):
        return util.find_executable('yogar-cbmc-parallel')

    def name(self):
        return 'Yogar-CBMC-Parallel'

    def cmdline(self, executable, options, tasks, propertyfile, rlimits):
        return [executable] + options + tasks

Prompt:
Add forgotten program file for deployment

"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015  Dirk Beyer
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 benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])

class Tool(yogar_cbmc.Tool):

    def executable(self):
        return util.find_executable('yogar-cbmc-parallel')

    def name(self):
        return 'Yogar-CBMC-Parallel'

    def cmdline(self, executable, options, tasks, propertyfile, rlimits):
        return [executable] + options + tasks


import warnings

from signac import *
__all__ = ['core', 'contrib', 'db']

msg = "compdb was renamed to signac. Please import signac in the future."
print('Warning!',msg)
warnings.warn(msg, DeprecationWarning)

Response:
import warnings

from signac import *
__all__ = ['core', 'contrib', 'db']

msg = "compdb was renamed to signac. Please import signac in the future."
print('Warning!',msg)
warnings.warn(msg, DeprecationWarning)

Prompt:
Add surrogate compdb package, linking to signac.

Provided to guarantee compatibility.
Prints warning on import.

import warnings

from signac import *

msg = "compdb was renamed to signac. Please import signac in the future."
warnings.warn(DeprecationWarning, msg)


import time
from datetime import timedelta

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils import timezone

from players.models import Player

class Command(BaseCommand):
    def handle(self, *args, **options):
        start_date = timezone.now() - timedelta(days=7)
        players = Player.objects.filter(Q(mmr_last_updated__isnull=True) | Q(mmr_last_updated__lt=start_date))
        self.stdout.write('Updating MMR for {} players.'.format(players.count()))
        for player in players:
            player.update_mmr()
            time.sleep(1)
        self.stdout.write(self.style.SUCCESS('Finished updating all player MMRs.'))

Add management command to update all player MMRs

Response:
import time
from datetime import timedelta

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils import timezone

from players.models import Player

class Command(BaseCommand):
    def handle(self, *args, **options):
        start_date = timezone.now() - timedelta(days=7)
        players = Player.objects.filter(Q(mmr_last_updated__isnull=True) | Q(mmr_last_updated__lt=start_date))
        self.stdout.write('Updating MMR for {} players.'.format(players.count()))
        for player in players:
            player.update_mmr()
            time.sleep(1)
        self.stdout.write(self.style.SUCCESS('Finished updating all player MMRs.'))

Prompt: Add management command to update all player MMRs


import numpy as np
from menpofit.math.correlationfilter import mccf, imccf

# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
    r"""
    """
    def __init__(self, cf_callable=mccf, icf_callable=imccf):
        self.cf_callable = cf_callable
        self.icf_callable = icf_callable

    def increment(self, A, B, n_x, Z, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(Z, list):
            Z = np.asarray(Z)
        return self.icf_callable(A, B, n_x, Z, t)

    def train(self, X, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(X, list):
            X = np.asarray(X)
        # Return linear svm filter and bias
        return self.cf_callable(X, t)

Add dummy wrapper for correlation filters

Response:
import numpy as np
from menpofit.math.correlationfilter import mccf, imccf

# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
    r"""
    """
    def __init__(self, cf_callable=mccf, icf_callable=imccf):
        self.cf_callable = cf_callable
        self.icf_callable = icf_callable

    def increment(self, A, B, n_x, Z, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(Z, list):
            Z = np.asarray(Z)
        return self.icf_callable(A, B, n_x, Z, t)

    def train(self, X, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(X, list):
            X = np.asarray(X)
        # Return linear svm filter and bias
        return self.cf_callable(X, t)

Prompt: Add dummy wrapper for correlation filters


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

import unittest

from ParseArticleReferenceTest import ParseArticleReferenceTest
from SortReferencesVisitorTest import SortReferencesVisitorTest
from ParseEditTest import ParseEditTest
from ParseAlineaReferenceTest import ParseAlineaReferenceTest
from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest
from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest
from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest

if __name__ == '__main__':
    unittest.main()

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

import unittest

from ParseArticleReferenceTest import ParseArticleReferenceTest
from SortReferencesVisitorTest import SortReferencesVisitorTest
from ParseEditTest import ParseEditTest
from ParseAlineaReferenceTest import ParseAlineaReferenceTest
from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest
from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest
from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest

if __name__ == '__main__':
    unittest.main()

Prompt:
Fix broken reference to ParseSentenceDefinitionTest.

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

import unittest

from ParseArticleReferenceTest import ParseArticleReferenceTest
from SortReferencesVisitorTest import SortReferencesVisitorTest
from ParseEditTest import ParseEditTest
from ParseAlineaReferenceTest import ParseAlineaReferenceTest
from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest
from ParseSentenceDefinitionTest import ParseSentenceDefinitionTest
from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest
from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest

if __name__ == '__main__':
    unittest.main()


# define flask extensions in separate file, to resolve import dependencies

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_caching import Cache
cache = Cache()

from flask_assets import Environment
assets = Environment()

from flask_babel import Babel
babel = Babel()

from flask_mail import Mail
mail = Mail()

from flask_login import LoginManager
login_manager = LoginManager()

from flask_restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

from flask_store import Store
store = Store()

from flask_rq2 import RQ
rq = RQ()

from flask_talisman import Talisman
CALLPOWER_CSP = {
    'default-src':'\'self\'',
    'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
    'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
    'font-src': ['\'self\'', 'fonts.gstatic.com'],
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman()

Response:
# define flask extensions in separate file, to resolve import dependencies

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_caching import Cache
cache = Cache()

from flask_assets import Environment
assets = Environment()

from flask_babel import Babel
babel = Babel()

from flask_mail import Mail
mail = Mail()

from flask_login import LoginManager
login_manager = LoginManager()

from flask_restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

from flask_store import Store
store = Store()

from flask_rq2 import RQ
rq = RQ()

from flask_talisman import Talisman
CALLPOWER_CSP = {
    'default-src':'\'self\'',
    'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
    'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
    'font-src': ['\'self\'', 'fonts.gstatic.com'],
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman()

Prompt:
Include script-src unsafe-eval to allow underscore templating
Long term, we should pre-compile with webpack to avoid needing this

# define flask extensions in separate file, to resolve import dependencies

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_caching import Cache
cache = Cache()

from flask_assets import Environment
assets = Environment()

from flask_babel import Babel
babel = Babel()

from flask_mail import Mail
mail = Mail()

from flask_login import LoginManager
login_manager = LoginManager()

from flask_restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

from flask_store import Store
store = Store()

from flask_rq2 import RQ
rq = RQ()

from flask_talisman import Talisman
CALLPOWER_CSP = {
    'default-src':'\'self\'',
    'script-src':['\'self\'', '\'unsafe-inline\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
    'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
    'font-src': ['\'self\'', 'fonts.gstatic.com'],
}
talisman = Talisman()


# -*- coding: utf-8 -*-
"""\
- Add a ``media_type`` column to the ``files`` table.
- Move the mimetype value from ``module_files`` to ``files``.

"""
from __future__ import print_function
import sys

def up(cursor):
    # Add a ``media_type`` column to the ``files`` table.
    cursor.execute("ALTER TABLE files ADD COLUMN media_type TEXT")

    # Move the mimetype value from ``module_files`` to ``files``.
    cursor.execute("UPDATE files AS f SET media_type = mf.mimetype "
                   "FROM module_files AS mf "
                   "WHERE mf.fileid = f.fileid")

    # Warn about missing mimetype.
    cursor.execute("SELECT fileid, sha1 "
                   "FROM files AS f "
                   "WHERE f.fileid NOT IN (SELECT fileid FROM module_files)")
    rows = '\n'.join(['{}, {}'.format(fid, sha1)
                      for fid, sha1 in cursor.fetchall()])
    print("These files (fileid, sha1) do not have a corresponding "
          "module_files entry:\n{}\n".format(rows),
          file=sys.stderr)

def down(cursor):
    # Remove the ``mimetype`` column from the ``files`` table.
    cursor.execute("ALTER TABLE files DROP COLUMN media_type")

Move mimetype column from module_files to files

Response:
# -*- coding: utf-8 -*-
"""\
- Add a ``media_type`` column to the ``files`` table.
- Move the mimetype value from ``module_files`` to ``files``.

"""
from __future__ import print_function
import sys

def up(cursor):
    # Add a ``media_type`` column to the ``files`` table.
    cursor.execute("ALTER TABLE files ADD COLUMN media_type TEXT")

    # Move the mimetype value from ``module_files`` to ``files``.
    cursor.execute("UPDATE files AS f SET media_type = mf.mimetype "
                   "FROM module_files AS mf "
                   "WHERE mf.fileid = f.fileid")

    # Warn about missing mimetype.
    cursor.execute("SELECT fileid, sha1 "
                   "FROM files AS f "
                   "WHERE f.fileid NOT IN (SELECT fileid FROM module_files)")
    rows = '\n'.join(['{}, {}'.format(fid, sha1)
                      for fid, sha1 in cursor.fetchall()])
    print("These files (fileid, sha1) do not have a corresponding "
          "module_files entry:\n{}\n".format(rows),
          file=sys.stderr)

def down(cursor):
    # Remove the ``mimetype`` column from the ``files`` table.
    cursor.execute("ALTER TABLE files DROP COLUMN media_type")

Prompt: Move mimetype column from module_files to files


from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

from models import *

bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")

class ButtonPlugin(CMSPluginBase):
    model = ButtonPluginModel
    name = _("Button")
    #module = bootstrap_module_name
    render_template = "button_plugin.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        if instance.page_link:
            context['link'] = instance.page_link.get_absolute_url()
        else:
            context['link'] = instance.button_link
        return context

plugin_pool.register_plugin(ButtonPlugin)

Response:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

from models import *

bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")

class ButtonPlugin(CMSPluginBase):
    model = ButtonPluginModel
    name = _("Button")
    #module = bootstrap_module_name
    render_template = "button_plugin.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        if instance.page_link:
            context['link'] = instance.page_link.get_absolute_url()
        else:
            context['link'] = instance.button_link
        return context

plugin_pool.register_plugin(ButtonPlugin)

Prompt:
Make Button plugin usable inside Text plugin

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

from models import *

bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")

class ButtonPlugin(CMSPluginBase):
    model = ButtonPluginModel
    name = _("Button")
    #module = bootstrap_module_name
    render_template = "button_plugin.html"

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        if instance.page_link:
            context['link'] = instance.page_link.get_absolute_url()
        else:
            context['link'] = instance.button_link
        return context

plugin_pool.register_plugin(ButtonPlugin)


import __builtin__

def any(it):
    for obj in it:
        if obj:
            return True
    return False

def all(it):
    for obj in it:
        if not obj:
            return False
    return True

def max(it, key=None):
    if key is not None:
        k, value = max((key(value), value) for value in it)
        return value
    return max(it)

def min(it, key=None):
    if key is not None:
        k, value = min((key(value), value) for value in it)
        return value
    return min(it)

class Condition(object):
    """
    This wraps a condition so that it can be shared by everyone and modified
    by whomever wants to.
    """
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return self.value

class ComparableObjectMixin(object):

    def __hash__(self):
        "Implement in subclasses"
        raise NotImplementedError

    def __eq__(self, other):
        "Implement in subclasses"
        return NotImplemented

Return an actual bool from any()

Return an actual bool from any()

Response:
import __builtin__

def any(it):
    for obj in it:
        if obj:
            return True
    return False

def all(it):
    for obj in it:
        if not obj:
            return False
    return True

def max(it, key=None):
    if key is not None:
        k, value = max((key(value), value) for value in it)
        return value
    return max(it)

def min(it, key=None):
    if key is not None:
        k, value = min((key(value), value) for value in it)
        return value
    return min(it)

class Condition(object):
    """
    This wraps a condition so that it can be shared by everyone and modified
    by whomever wants to.
    """
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return self.value

class ComparableObjectMixin(object):

    def __hash__(self):
        "Implement in subclasses"
        raise NotImplementedError

    def __eq__(self, other):
        "Implement in subclasses"
        return NotImplemented

Prompt:
Return an actual bool from any()

import __builtin__

def any(it):
    for obj in it:
        if obj:
            return True

def all(it):
    for obj in it:
        if not obj:
            return False
    return True

def max(it, key=None):
    if key is not None:
        k, value = max((key(value), value) for value in it)
        return value
    return max(it)

def min(it, key=None):
    if key is not None:
        k, value = min((key(value), value) for value in it)
        return value
    return min(it)

class Condition(object):
    """
    This wraps a condition so that it can be shared by everyone and modified
    by whomever wants to.
    """
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return self.value

class ComparableObjectMixin(object):

    def __hash__(self):
        "Implement in subclasses"
        raise NotImplementedError

    def __eq__(self, other):
        "Implement in subclasses"
        return NotImplemented


import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        "access the database"
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        "connect to SQS"
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()

Response:
import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        "access the database"
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        "connect to SQS"
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()

Prompt:
Add docstrings so that hubot can say what went wrong

import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()


# https://leetcode.com/problems/delete-node-in-a-linked-list/

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """

        while node.next != None:
            node.val = node.next.val
            if node.next.next is None:
                node.next = None
            else:
                node = node.next

Add problem delete note in a linked list

Response:
# https://leetcode.com/problems/delete-node-in-a-linked-list/

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """

        while node.next != None:
            node.val = node.next.val
            if node.next.next is None:
                node.next = None
            else:
                node = node.next

Prompt: Add problem delete note in a linked list


"""
Documentation-related helper classes/functions
"""

class soft_wraps:
    """
    A Python decorator which concatenates two functions' docstrings: one
    function is defined at initialization and the other one is defined when
    soft_wraps is called.

    This helps reduce the ammount of documentation to write: one can use
    this decorator on child classes' functions when their implementation is
    similar to the one of the parent class. Conversely, if a function defined
    in a child class departs from its parent's implementation, one can simply
    explain the differences in a 'Notes' section without re-writing the whole
    docstring.

    Examples
    --------
    >>> class Parent(object):
    ...     def f(x):
    ...        '''
    ...        Adds 1 to x
    ...
    ...        Parameters
    ...        ----------
    ...        x : int
    ...            Variable to increment by 1
    ...
    ...        Returns
    ...        -------
    ...        rval : int
    ...            x incremented by 1
    ...        '''
    ...        rval = x + 1
    ...        return rval
    ...
    >>> class Child(Parent):
    ...     @soft_wraps(Parent.f)
    ...     def f(x):
    ...        '''
    ...        Notes
    ...        -----
    ...        Also prints the incremented value
    ...        '''
    ...        rval = x + 1
    ...        print rval
    ...        return rval
    ...
    >>> c = Child()
    >>> print c.f.__doc__

        Adds 1 to x

        Parameters
        ----------
        x : int
            Variable to increment by 1

        Returns
        -------
        rval : int
           x incremented by 1

        Notes
        -----
        Also prints the incremented value
    """

    def __init__(self, f, append=False):
        """
        Parameters
        ----------
        f : function
            Function whose docstring will be concatenated with the decorated
            function's docstring
        prepend : bool, optional
            If True, appends f's docstring to the decorated function's
            docstring instead of prepending it. Defaults to False.
        """
        self.f = f
        self.append = append

    def __call__(self, f):
        """
        Prepend self.f's docstring to f's docstring (or append it if
        `self.append == True`).

        Parameters
        ----------
        f : function
            Function to decorate

        Returns
        -------
        f : function
            Function f passed as argument with self.f's docstring
            {pre,ap}pended to it
        """
        if self.append:
            f.__doc__ +=  + self.f.__doc__
        else:
            f.__doc__ = self.f.__doc__ + f.__doc__

        return f

Add function decorator to improve functools.wraps

Response:
"""
Documentation-related helper classes/functions
"""

class soft_wraps:
    """
    A Python decorator which concatenates two functions' docstrings: one
    function is defined at initialization and the other one is defined when
    soft_wraps is called.

    This helps reduce the ammount of documentation to write: one can use
    this decorator on child classes' functions when their implementation is
    similar to the one of the parent class. Conversely, if a function defined
    in a child class departs from its parent's implementation, one can simply
    explain the differences in a 'Notes' section without re-writing the whole
    docstring.

    Examples
    --------
    >>> class Parent(object):
    ...     def f(x):
    ...        '''
    ...        Adds 1 to x
    ...
    ...        Parameters
    ...        ----------
    ...        x : int
    ...            Variable to increment by 1
    ...
    ...        Returns
    ...        -------
    ...        rval : int
    ...            x incremented by 1
    ...        '''
    ...        rval = x + 1
    ...        return rval
    ...
    >>> class Child(Parent):
    ...     @soft_wraps(Parent.f)
    ...     def f(x):
    ...        '''
    ...        Notes
    ...        -----
    ...        Also prints the incremented value
    ...        '''
    ...        rval = x + 1
    ...        print rval
    ...        return rval
    ...
    >>> c = Child()
    >>> print c.f.__doc__

        Adds 1 to x

        Parameters
        ----------
        x : int
            Variable to increment by 1

        Returns
        -------
        rval : int
           x incremented by 1

        Notes
        -----
        Also prints the incremented value
    """

    def __init__(self, f, append=False):
        """
        Parameters
        ----------
        f : function
            Function whose docstring will be concatenated with the decorated
            function's docstring
        prepend : bool, optional
            If True, appends f's docstring to the decorated function's
            docstring instead of prepending it. Defaults to False.
        """
        self.f = f
        self.append = append

    def __call__(self, f):
        """
        Prepend self.f's docstring to f's docstring (or append it if
        `self.append == True`).

        Parameters
        ----------
        f : function
            Function to decorate

        Returns
        -------
        f : function
            Function f passed as argument with self.f's docstring
            {pre,ap}pended to it
        """
        if self.append:
            f.__doc__ +=  + self.f.__doc__
        else:
            f.__doc__ = self.f.__doc__ + f.__doc__

        return f

Prompt: Add function decorator to improve functools.wraps


"""Displays a randomly generated witticism from Brian Chu himself."""

import json
import random

__match__ = r"!brian"

attribution = [
    "salad master",
    "esquire",
    "the one and only",
    "startup enthusiast",
    "boba king",
    "not-dictator",
    "normal citizen",
    "ping-pong expert"
]

with open('plugins/brian_corpus/phrases.json', 'r') as infile:
    phrases = json.load(infile)

with open('plugins/brian_corpus/cache.json', 'r') as infile:
    cache = json.load(infile)

def generate_phrase(phrases, cache, max_length=40):
    seed_phrase = []
    while len(seed_phrase) < 2:
        seed_phrase = random.choice(phrases).split()

    w1, = seed_phrase[:1]
    chosen = [w1]

    while w1 in cache and len(chosen)<max_length:
        w1 = random.choice(cache[w1])
        chosen.append(w1)

    return ' '.join(chosen)

def on_message(bot, channel, user, message):
    return '> {} ~ Brian Chu, {}'.format(generate_phrase(phrases, cache),
        random.choice(attribution))

Use bigrams in Markov chain generator

Use bigrams in Markov chain generator

Response:
"""Displays a randomly generated witticism from Brian Chu himself."""

import json
import random

__match__ = r"!brian"

attribution = [
    "salad master",
    "esquire",
    "the one and only",
    "startup enthusiast",
    "boba king",
    "not-dictator",
    "normal citizen",
    "ping-pong expert"
]

with open('plugins/brian_corpus/phrases.json', 'r') as infile:
    phrases = json.load(infile)

with open('plugins/brian_corpus/cache.json', 'r') as infile:
    cache = json.load(infile)

def generate_phrase(phrases, cache, max_length=40):
    seed_phrase = []
    while len(seed_phrase) < 2:
        seed_phrase = random.choice(phrases).split()

    w1, = seed_phrase[:1]
    chosen = [w1]

    while w1 in cache and len(chosen)<max_length:
        w1 = random.choice(cache[w1])
        chosen.append(w1)

    return ' '.join(chosen)

def on_message(bot, channel, user, message):
    return '> {} ~ Brian Chu, {}'.format(generate_phrase(phrases, cache),
        random.choice(attribution))

Prompt:
Use bigrams in Markov chain generator

"""Displays a randomly generated witticism from Brian Chu himself."""

import json
import random

__match__ = r"!brian"

with open('plugins/brian_corpus/cache.json', 'r') as infile:
    cache = json.load(infile)

with open('plugins/brian_corpus/phrases.json', 'r') as infile:
    phrases = json.load(infile)

def generate_phrase(phrases, cache):
    seed_phrase = []
    while len(seed_phrase) < 3:
        seed_phrase = random.choice(phrases).split()

    w1, w2 = seed_phrase[:2]
    chosen = [w1, w2]

    while "{}|{}".format(w1, w2) in cache:
        choice = random.choice(cache["{}|{}".format(w1, w2)])
        w1, w2 = w2, choice
        chosen.append(choice)

    return ' '.join(chosen)

def on_message(bot, channel, user, message):
    return '> {} ~brian'.format(generate_phrase(phrases, cache))


from pyramid.view import view_config

from ....views.finalisecontext import FinaliseContext

class APIV1(FinaliseContext):
    @view_config(context='...traversal.v1.Root', route_name='api', renderer='json')
    def main(self):
        sites = []
        for site in self.context.sites:
            sites.append(
                        {
                            'id': site.id,
                            'title': site.title,
                            'tagline': site.tagline,
                        }
                    )
        return {
                'sites': sites,
                }

Add view for API v1 Root

Add view for API v1 Root

This sends back a JSON response contain sites with ID's as well as
title/tagline.

Response:
from pyramid.view import view_config

from ....views.finalisecontext import FinaliseContext

class APIV1(FinaliseContext):
    @view_config(context='...traversal.v1.Root', route_name='api', renderer='json')
    def main(self):
        sites = []
        for site in self.context.sites:
            sites.append(
                        {
                            'id': site.id,
                            'title': site.title,
                            'tagline': site.tagline,
                        }
                    )
        return {
                'sites': sites,
                }

Prompt:
Add view for API v1 Root

This sends back a JSON response contain sites with ID's as well as
title/tagline.


# Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
    '_foo_bucket': '_foo_bucket-bearer-token',
    'bucket': 'bucket-bearer-token',
    'foo': 'foo-bearer-token',
    'foo_bucket': 'foo_bucket-bearer-token',
    'licensing': 'licensing-bearer-token',
    'licensing_journey': 'licensing_journey-bearer-token',
    'licensing_live_data': 'licensing_live_data_bearer_token',
    'licence_finder_live_data': 'licence_finder_live_data_bearer_token'
}
PERMISSIONS = {}
OAUTH_CLIENT_ID = \
    "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844"
OAUTH_CLIENT_SECRET = \
    "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a"
OAUTH_BASE_URL = "http://signon.dev.gov.uk"

Add buckets for collecting pingdom data

Add buckets for collecting pingdom data

Response:
# Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
    '_foo_bucket': '_foo_bucket-bearer-token',
    'bucket': 'bucket-bearer-token',
    'foo': 'foo-bearer-token',
    'foo_bucket': 'foo_bucket-bearer-token',
    'licensing': 'licensing-bearer-token',
    'licensing_journey': 'licensing_journey-bearer-token',
    'licensing_live_data': 'licensing_live_data_bearer_token',
    'licence_finder_live_data': 'licence_finder_live_data_bearer_token'
}
PERMISSIONS = {}
OAUTH_CLIENT_ID = \
    "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844"
OAUTH_CLIENT_SECRET = \
    "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a"
OAUTH_BASE_URL = "http://signon.dev.gov.uk"

Prompt:
Add buckets for collecting pingdom data

# Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
    '_foo_bucket': '_foo_bucket-bearer-token',
    'bucket': 'bucket-bearer-token',
    'foo': 'foo-bearer-token',
    'foo_bucket': 'foo_bucket-bearer-token',
    'licensing': 'licensing-bearer-token',
    'licensing_journey': 'licensing_journey-bearer-token'
}
PERMISSIONS = {}
OAUTH_CLIENT_ID = \
    "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844"
OAUTH_CLIENT_SECRET = \
    "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a"
OAUTH_BASE_URL = "http://signon.dev.gov.uk"


''' test_deltaprel - Test functions for deltaprel module

Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises

from pyflation.analysis import deltaprel
import nose

class TestSoundSpeeds():

    def setup(self):
        self.Vphi = np.arange(24).reshape((4,3,2))
        self.phidot = self.Vphi
        self.H = np.arange(8).reshape((4,1,2))

    def test_shape(self):
        """Test whether the soundspeeds are shaped correctly."""
        arr = deltaprel.soundspeeds(self.Vphi, self.phidot, self.H)
        assert_(arr.shape == self.Vphi.shape)

    def test_scalar(self):
        """Test results of 1x1x1 calculation."""
        arr = deltaprel.soundspeeds(3, 2, 0.5)
        assert_(arr == 3)

    def test_wrongshape(self):
        """Test that wrong shapes raise exception."""
        self.H = np.arange(8).reshape((4,2))
        assert_raises(ValueError, deltaprel.soundspeeds, self.Vphi, self.phidot, self.H)

Add test for scalar values.

Add test for scalar values.

Response:
''' test_deltaprel - Test functions for deltaprel module

Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises

from pyflation.analysis import deltaprel
import nose

class TestSoundSpeeds():

    def setup(self):
        self.Vphi = np.arange(24).reshape((4,3,2))
        self.phidot = self.Vphi
        self.H = np.arange(8).reshape((4,1,2))

    def test_shape(self):
        """Test whether the soundspeeds are shaped correctly."""
        arr = deltaprel.soundspeeds(self.Vphi, self.phidot, self.H)
        assert_(arr.shape == self.Vphi.shape)

    def test_scalar(self):
        """Test results of 1x1x1 calculation."""
        arr = deltaprel.soundspeeds(3, 2, 0.5)
        assert_(arr == 3)

    def test_wrongshape(self):
        """Test that wrong shapes raise exception."""
        self.H = np.arange(8).reshape((4,2))
        assert_raises(ValueError, deltaprel.soundspeeds, self.Vphi, self.phidot, self.H)

Prompt:
Add test for scalar values.

''' test_deltaprel - Test functions for deltaprel module

Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises

from pyflation.analysis import deltaprel
import nose

class TestSoundSpeeds():

    def setup(self):
        self.Vphi = np.arange(24).reshape((4,3,2))
        self.phidot = self.Vphi
        self.H = np.arange(8).reshape((4,1,2))

    def test_shape(self):
        """Test whether the soundspeeds are shaped correctly."""
        arr = deltaprel.soundspeeds(self.Vphi, self.phidot, self.H)
        assert_(arr.shape == self.Vphi.shape)

    def test_calc(self):
        """Test results of calculation."""
        arr = deltaprel.soundspeeds(self.Vphi, self.phidot, self.H)

    def test_wrongshape(self):
        """Test that wrong shapes raise exception."""
        self.H = np.arange(8).reshape((4,2))
        assert_raises(ValueError, deltaprel.soundspeeds, self.Vphi, self.phidot, self.H)


from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase

class Meta(MetaBase):
    name = 'Diesel Sweeties (web)'
    language = 'en'
    url = 'http://www.dieselsweeties.com/'
    start_date = '2000-01-01'
    rights = 'Richard Stevens'

class Crawler(CrawlerBase):
    history_capable_date = '2000-01-01'
    schedule = 'Mo,Tu,We,Th,Fr'
    time_zone = -5

    def crawl(self, pub_date):
        feed = self.parse_feed('http://www.dieselsweeties.com/ds-unifeed.xml')
        for entry in feed.for_date(pub_date):
            if not hasattr(entry, 'summary'):
                continue
            url = entry.summary.src('img[src*="/strips/"]')
            title = entry.title
            text = entry.summary.alt('img[src*="/strips/"]')
            return CrawlerImage(url, title, text)

Response:
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase

class Meta(MetaBase):
    name = 'Diesel Sweeties (web)'
    language = 'en'
    url = 'http://www.dieselsweeties.com/'
    start_date = '2000-01-01'
    rights = 'Richard Stevens'

class Crawler(CrawlerBase):
    history_capable_date = '2000-01-01'
    schedule = 'Mo,Tu,We,Th,Fr'
    time_zone = -5

    def crawl(self, pub_date):
        feed = self.parse_feed('http://www.dieselsweeties.com/ds-unifeed.xml')
        for entry in feed.for_date(pub_date):
            if not hasattr(entry, 'summary'):
                continue
            url = entry.summary.src('img[src*="/strips/"]')
            title = entry.title
            text = entry.summary.alt('img[src*="/strips/"]')
            return CrawlerImage(url, title, text)

Prompt:
Check if field exists, not if it's empty

from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase

class Meta(MetaBase):
    name = 'Diesel Sweeties (web)'
    language = 'en'
    url = 'http://www.dieselsweeties.com/'
    start_date = '2000-01-01'
    rights = 'Richard Stevens'

class Crawler(CrawlerBase):
    history_capable_date = '2000-01-01'
    schedule = 'Mo,Tu,We,Th,Fr'
    time_zone = -5

    def crawl(self, pub_date):
        feed = self.parse_feed('http://www.dieselsweeties.com/ds-unifeed.xml')
        for entry in feed.for_date(pub_date):
            if not entry.summary:
                continue
            url = entry.summary.src('img[src*="/strips/"]')
            title = entry.title
            text = entry.summary.alt('img[src*="/strips/"]')
            return CrawlerImage(url, title, text)


import gmpy

def powMod( x, y, mod ):
    """
    Efficiently calculate and return `x' to the power of `y' mod `mod'.

    Before the modular exponentiation, the three numbers are converted to
    GMPY's bignum representation which speeds up exponentiation.
    """

    x = gmpy.mpz(x)
    y = gmpy.mpz(y)
    mod = gmpy.mpz(mod)

    return pow(x, y, mod)

Add function for fast modular exponentiation.

The function uses GMPY's bignum arithmetic which speeds up the calculation.

Response:
import gmpy

def powMod( x, y, mod ):
    """
    Efficiently calculate and return `x' to the power of `y' mod `mod'.

    Before the modular exponentiation, the three numbers are converted to
    GMPY's bignum representation which speeds up exponentiation.
    """

    x = gmpy.mpz(x)
    y = gmpy.mpz(y)
    mod = gmpy.mpz(mod)

    return pow(x, y, mod)

Prompt:
Add function for fast modular exponentiation.

The function uses GMPY's bignum arithmetic which speeds up the calculation.


# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Guewen Baconnier
#    Copyright 2015 Camptocamp SA
#
#    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 Payment Method - Automatic Reconcile',
 'version': '1.0',
 'author': ['Camptocamp', 'Akretion'],
 'license': 'AGPL-3',
 'category': 'Generic Modules/Others',
 'depends': ['sale_payment_method',
             'sale_automatic_workflow'],
 'website': 'http://www.camptocamp.com',
 'data': [],
 'test': [],
 'installable': True,
 'auto_install': True,
 }

Set the module as auto_install

Response:
# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Guewen Baconnier
#    Copyright 2015 Camptocamp SA
#
#    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 Payment Method - Automatic Reconcile',
 'version': '1.0',
 'author': ['Camptocamp', 'Akretion'],
 'license': 'AGPL-3',
 'category': 'Generic Modules/Others',
 'depends': ['sale_payment_method',
             'sale_automatic_workflow'],
 'website': 'http://www.camptocamp.com',
 'data': [],
 'test': [],
 'installable': True,
 'auto_install': True,
 }

Prompt:
Set the module as auto_install

So it installs when both sale_payment_method and sale_automatic_workflow are installed.
This module acts as the glue between them

# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Guewen Baconnier
#    Copyright 2015 Camptocamp SA
#
#    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 Payment Method - Automatic Reconcile',
 'version': '1.0',
 'author': ['Camptocamp', 'Akretion'],
 'license': 'AGPL-3',
 'category': 'Generic Modules/Others',
 'depends': ['sale_payment_method',
             'sale_automatic_workflow'],
 'website': 'http://www.camptocamp.com',
 'data': [],
 'test': [],
 'installable': True,
 'auto_install': False,
 }


# TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realistic_rendering import TestRealisticRendering

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI

    args = parser.parse_args()
    suites = []

    load = unittest.TestLoader().loadTestsFromTestCase
    s = load(TestMessageServer); suites.append(s)
    s = load(TestClientWithDummyServer); suites.append(s)
    if not args.travis:
        s = load(TestCommands); suites.append(s)
        s = load(TestRealisticRendering); suites.append(s)

    suite_obj = unittest.TestSuite(suites)
    ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSucessful()
    sys.exit(ret)

Fix exit code of unittest.

Fix exit code of unittest.

Response:
# TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realistic_rendering import TestRealisticRendering

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI

    args = parser.parse_args()
    suites = []

    load = unittest.TestLoader().loadTestsFromTestCase
    s = load(TestMessageServer); suites.append(s)
    s = load(TestClientWithDummyServer); suites.append(s)
    if not args.travis:
        s = load(TestCommands); suites.append(s)
        s = load(TestRealisticRendering); suites.append(s)

    suite_obj = unittest.TestSuite(suites)
    ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSucessful()
    sys.exit(ret)

Prompt:
Fix exit code of unittest.

# TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realistic_rendering import TestRealisticRendering

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI

    args = parser.parse_args()
    suites = []

    load = unittest.TestLoader().loadTestsFromTestCase
    s = load(TestMessageServer); suites.append(s)
    s = load(TestClientWithDummyServer); suites.append(s)
    if not args.travis:
        s = load(TestCommands); suites.append(s)
        s = load(TestRealisticRendering); suites.append(s)

    suite_obj = unittest.TestSuite(suites)
    unittest.TextTestRunner(verbosity = 2).run(suite_obj)


# coding: utf-8

from setuptools import setup, find_packages

setup(
	name = 'thumbor_aws',
	version = "1",
	description = 'Thumbor AWS extensions',
	author = 'William King',
	author_email = 'willtrking@gmail.com',
	zip_safe = False,
	include_package_data = True,
	packages=find_packages(),
	install_requires=['python-dateutil','thumbor','boto']
)

Response:
# coding: utf-8

from setuptools import setup, find_packages

setup(
	name = 'thumbor_aws',
	version = "1",
	description = 'Thumbor AWS extensions',
	author = 'William King',
	author_email = 'willtrking@gmail.com',
	zip_safe = False,
	include_package_data = True,
	packages=find_packages(),
	install_requires=['python-dateutil','thumbor','boto']
)

Prompt:
Use python-dateutil instead of py-dateutil

# coding: utf-8

from setuptools import setup, find_packages

setup(
	name = 'thumbor_aws',
	version = "1",
	description = 'Thumbor AWS extensions',
	author = 'William King',
	author_email = 'willtrking@gmail.com',
	zip_safe = False,
	include_package_data = True,
	packages=find_packages(),
	install_requires=['py-dateutil','thumbor','boto']
)


import json
from indra.literature.dart_client import jsonify_query_data

def test_timestamp():
    # Should ignore "after"
    assert jsonify_query_data(timestamp={'on': '2020-01-01',
                                         'after': '2020-01-02'}) == \
        json.dumps({"timestamp": {"on": "2020-01-01"}})
    assert jsonify_query_data(timestamp={'after': '2020-01-01',
                                         'before': '2020-01-05'}) == \
        json.dumps(
            {'timestamp': {'after': '2020-01-01', 'before': '2020-01-05'}})

def test_lists():
    # Check lists, ignore the lists that have non-str objects
    assert jsonify_query_data(readers=['hume', 123456],
                              versions=['123', '456']) ==\
        json.dumps({'versions': ['123', '456']})

Add two tests for dart client

Add two tests for dart client

Response:
import json
from indra.literature.dart_client import jsonify_query_data

def test_timestamp():
    # Should ignore "after"
    assert jsonify_query_data(timestamp={'on': '2020-01-01',
                                         'after': '2020-01-02'}) == \
        json.dumps({"timestamp": {"on": "2020-01-01"}})
    assert jsonify_query_data(timestamp={'after': '2020-01-01',
                                         'before': '2020-01-05'}) == \
        json.dumps(
            {'timestamp': {'after': '2020-01-01', 'before': '2020-01-05'}})

def test_lists():
    # Check lists, ignore the lists that have non-str objects
    assert jsonify_query_data(readers=['hume', 123456],
                              versions=['123', '456']) ==\
        json.dumps({'versions': ['123', '456']})

Prompt: Add two tests for dart client


"""Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User

class UserSerializer(serializers.ModelSerializer):
    """Serializer for Users"""

    class Meta:
        """Model and field definitions"""

        model = User
        fields = (
            "id",
            "username",
            "email",
            "website",
            "avatar_url",
            "steamid",
            "is_staff",
        )

Response:
"""Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User

class UserSerializer(serializers.ModelSerializer):
    """Serializer for Users"""

    class Meta:
        """Model and field definitions"""

        model = User
        fields = (
            "id",
            "username",
            "email",
            "website",
            "avatar_url",
            "steamid",
            "is_staff",
        )

Prompt:
Change avatar to avatar_url in the user API

"""Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User

class UserSerializer(serializers.ModelSerializer):
    """Serializer for Users"""

    class Meta:
        """Model and field definitions"""
        model = User
        fields = (
            'id',
            'username',
            'email',
            'website',
            'avatar',
            'steamid',
            'is_staff',
        )


# License under the MIT License - see LICENSE

import boto.ec2
import os
import time

def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
           instance_type='t2.micro', security_groups='launch-wizard-1',
           user_data=None, initial_check=False):
    '''
    '''

    if not isinstance(security_groups, list):
        security_groups = [security_groups]

    ec2 = boto.ec2.connect_to_region(region)

    reserve = ec2.run_instances(image_id, key_name=key_name,
                                instance_type=instance_type,
                                security_groups=security_groups,
                                user_data=user_data)

    inst = reserve.instances[0]

    while inst.state == u'pending':
        time.sleep(10)
        inst.update()

    if initial_check:
        # Wait for the status checks first
        status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

        check_stat = "Status:initializing"

        while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
            time.sleep(10)
            status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    return inst

    # ec2.get_instance_attribute('i-336b69f6', 'instanceType')

Disable the extra check by default

Disable the extra check by default

Response:
# License under the MIT License - see LICENSE

import boto.ec2
import os
import time

def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
           instance_type='t2.micro', security_groups='launch-wizard-1',
           user_data=None, initial_check=False):
    '''
    '''

    if not isinstance(security_groups, list):
        security_groups = [security_groups]

    ec2 = boto.ec2.connect_to_region(region)

    reserve = ec2.run_instances(image_id, key_name=key_name,
                                instance_type=instance_type,
                                security_groups=security_groups,
                                user_data=user_data)

    inst = reserve.instances[0]

    while inst.state == u'pending':
        time.sleep(10)
        inst.update()

    if initial_check:
        # Wait for the status checks first
        status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

        check_stat = "Status:initializing"

        while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
            time.sleep(10)
            status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    return inst

    # ec2.get_instance_attribute('i-336b69f6', 'instanceType')

Prompt:
Disable the extra check by default

# License under the MIT License - see LICENSE

import boto.ec2
import os
import time

def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
           instance_type='t2.micro', security_groups='launch-wizard-1',
           user_data=None, initial_check=True):
    '''
    '''

    if not isinstance(security_groups, list):
        security_groups = [security_groups]

    ec2 = boto.ec2.connect_to_region(region)

    reserve = ec2.run_instances(image_id, key_name=key_name,
                                instance_type=instance_type,
                                security_groups=security_groups,
                                user_data=user_data)

    inst = reserve.instances[0]

    while inst.state == u'pending':
        time.sleep(10)
        inst.update()

    if initial_check:
        # Wait for the status checks first
        status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

        check_stat = "Status:initializing"

        while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
            time.sleep(10)
            status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    return inst

    # ec2.get_instance_attribute('i-336b69f6', 'instanceType')


#!/usr/bin/python

# Polyfilter - filters polygon files for very small polygons

import sys

f = open(sys.argv[1])

def PolygonArea(corners):
    n = len(corners) # of corners
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

allAreas = []
maxArea = 0
while True:
    line = f.readline().strip()
    if line=="": break
    points = line.split(" ")
    corners = []
    for p in points:
        ip = map(float,p.split(","))
        corners.append(ip)
    area = PolygonArea(corners)
    if (area > 500):
        print " ".join(points)

Add filter program to remove small polygons

Response:
#!/usr/bin/python

# Polyfilter - filters polygon files for very small polygons

import sys

f = open(sys.argv[1])

def PolygonArea(corners):
    n = len(corners) # of corners
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

allAreas = []
maxArea = 0
while True:
    line = f.readline().strip()
    if line=="": break
    points = line.split(" ")
    corners = []
    for p in points:
        ip = map(float,p.split(","))
        corners.append(ip)
    area = PolygonArea(corners)
    if (area > 500):
        print " ".join(points)

Prompt: Add filter program to remove small polygons


from __future__ import absolute_import

from django.http import HttpResponse
from django.views.generic.base import View

from icalendar import Calendar, Event

from wanikani.core import WaniKani, Radical, Kanji

class WaniKaniView(View):
    def get(self, request, **kwargs):
        client = WaniKani(kwargs['api_key'])

        level = client.profile()['level']
        queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])

        cal = Calendar()
        cal.add('prodid', '-//Wanikani Blockers//github.com/kfdm/wanikani//')
        cal.add('version', '2.0')

        for ts in sorted(queue):
            if not len(queue[ts]):
                continue

            counts = {
                Radical: 0,
                Kanji: 0,
            }

            for obj in queue[ts]:
                counts[obj.__class__] += 1

            event = Event()
            event.add('summary', 'R: {0} K: {1}'.format(
                counts[Radical], counts[Kanji]
            ))
            event.add('dtstart', ts)
            event.add('dtend', ts)
            event['uid'] = str(ts)

            cal.add_component(event)

        return HttpResponse(
            content=cal.to_ical(),
            content_type='text/plain; charset=utf-8'
        )

Response:
from __future__ import absolute_import

from django.http import HttpResponse
from django.views.generic.base import View

from icalendar import Calendar, Event

from wanikani.core import WaniKani, Radical, Kanji

class WaniKaniView(View):
    def get(self, request, **kwargs):
        client = WaniKani(kwargs['api_key'])

        level = client.profile()['level']
        queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])

        cal = Calendar()
        cal.add('prodid', '-//Wanikani Blockers//github.com/kfdm/wanikani//')
        cal.add('version', '2.0')

        for ts in sorted(queue):
            if not len(queue[ts]):
                continue

            counts = {
                Radical: 0,
                Kanji: 0,
            }

            for obj in queue[ts]:
                counts[obj.__class__] += 1

            event = Event()
            event.add('summary', 'R: {0} K: {1}'.format(
                counts[Radical], counts[Kanji]
            ))
            event.add('dtstart', ts)
            event.add('dtend', ts)
            event['uid'] = str(ts)

            cal.add_component(event)

        return HttpResponse(
            content=cal.to_ical(),
            content_type='text/plain; charset=utf-8'
        )

Prompt:
Switch to getting the API key from the URL instead of a config file.

Allows other people to get their anki calendar if they want.
from __future__ import absolute_import

import os
import logging

from django.http import HttpResponse
from django.views.generic.base import View

from icalendar import Calendar, Event

from wanikani.core import WaniKani, Radical, Kanji

CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')

with open(CONFIG_PATH) as fp:
    API_KEY = fp.read()

logger = logging.getLogger(__name__)

class WaniKaniView(View):
    def get(self, request, *args, **kwargs):
        client = WaniKani(API_KEY)

        level = client.profile()['level']
        queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])

        cal = Calendar()
        cal.add('prodid', '-//My calendar product//mxm.dk//')
        cal.add('version', '2.0')

        for ts in sorted(queue):
            if not len(queue[ts]):
                continue

            counts = {
                Radical: 0,
                Kanji: 0,
            }

            for obj in queue[ts]:
                counts[obj.__class__] += 1

            event = Event()
            event.add('summary', 'R: {0} K: {1}'.format(
                counts[Radical], counts[Kanji]
            ))
            event.add('dtstart', ts)
            event.add('dtend', ts)
            event['uid'] = str(ts)

            cal.add_component(event)

        return HttpResponse(
            content=cal.to_ical(),
            content_type='text/plain; charset=utf-8'
        )


class Countable(object):
    @classmethod
    def count(cls, _options=None, **kwargs):
        if _options is None:
            _options = kwargs
        return int(cls.get("count", **_options))

class Metafields(object):
    def metafields(self):
        return Metafield.find(resource=self.__class__.plural, resource_id=self.id)

    def add_metafield(self, metafield):
        if self.is_new():
            raise ValueError("You can only add metafields to a resource that has been saved")

        metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
        metafield.save()
        return metafield

class Events(object):
    def events(self):
        return Event.find(resource=self.__class__.plural, resource_id=self.id)

Response:
class Countable(object):
    @classmethod
    def count(cls, _options=None, **kwargs):
        if _options is None:
            _options = kwargs
        return int(cls.get("count", **_options))

class Metafields(object):
    def metafields(self):
        return Metafield.find(resource=self.__class__.plural, resource_id=self.id)

    def add_metafield(self, metafield):
        if self.is_new():
            raise ValueError("You can only add metafields to a resource that has been saved")

        metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
        metafield.save()
        return metafield

class Events(object):
    def events(self):
        return Event.find(resource=self.__class__.plural, resource_id=self.id)

Prompt:
Allow count method to be used the same way as find.

class Countable(object):
    @classmethod
    def count(cls, options={}):
        return int(cls.get("count", **options))

class Metafields(object):
    def metafields(self):
        return Metafield.find(resource=self.__class__.plural, resource_id=self.id)

    def add_metafield(self, metafield):
        if self.is_new():
            raise ValueError("You can only add metafields to a resource that has been saved")

        metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
        metafield.save()
        return metafield

class Events(object):
    def events(self):
        return Event.find(resource=self.__class__.plural, resource_id=self.id)


# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 Canonical Corp.
# 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.

from nova import exception
from nova import test
from nova.virt.vmwareapi import fake
from nova.virt.vmwareapi import vm_util

class fake_session(object):
    def __init__(self, ret=None):
        self.ret = ret

    def _call_method(self, *args):
        return self.ret

class VMwareVMUtilTestCase(test.TestCase):
    def setUp(self):
        super(VMwareVMUtilTestCase, self).setUp()

    def tearDown(self):
        super(VMwareVMUtilTestCase, self).tearDown()

    def test_get_datastore_ref_and_name(self):
        result = vm_util.get_datastore_ref_and_name(
            fake_session([fake.Datastore()]))

        self.assertEquals(result[1], "fake-ds")
        self.assertEquals(result[2], 1024 * 1024 * 1024)
        self.assertEquals(result[3], 1024 * 1024 * 500)

    def test_get_datastore_ref_and_name_without_datastore(self):

        self.assertRaises(exception.DatastoreNotFound,
                vm_util.get_datastore_ref_and_name,
                fake_session(), host="fake-host")

        self.assertRaises(exception.DatastoreNotFound,
                vm_util.get_datastore_ref_and_name,
                fake_session(), cluster="fake-cluster")

Fix variable referenced before assginment in vmwareapi code.

Add unitests for VMwareapi vm_util.
fix bug #1177689

Change-Id: If16109ee626c197227affba122c2e4986d92d2df

Response:
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 Canonical Corp.
# 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.

from nova import exception
from nova import test
from nova.virt.vmwareapi import fake
from nova.virt.vmwareapi import vm_util

class fake_session(object):
    def __init__(self, ret=None):
        self.ret = ret

    def _call_method(self, *args):
        return self.ret

class VMwareVMUtilTestCase(test.TestCase):
    def setUp(self):
        super(VMwareVMUtilTestCase, self).setUp()

    def tearDown(self):
        super(VMwareVMUtilTestCase, self).tearDown()

    def test_get_datastore_ref_and_name(self):
        result = vm_util.get_datastore_ref_and_name(
            fake_session([fake.Datastore()]))

        self.assertEquals(result[1], "fake-ds")
        self.assertEquals(result[2], 1024 * 1024 * 1024)
        self.assertEquals(result[3], 1024 * 1024 * 500)

    def test_get_datastore_ref_and_name_without_datastore(self):

        self.assertRaises(exception.DatastoreNotFound,
                vm_util.get_datastore_ref_and_name,
                fake_session(), host="fake-host")

        self.assertRaises(exception.DatastoreNotFound,
                vm_util.get_datastore_ref_and_name,
                fake_session(), cluster="fake-cluster")

Prompt:
Fix variable referenced before assginment in vmwareapi code.

Add unitests for VMwareapi vm_util.
fix bug #1177689

Change-Id: If16109ee626c197227affba122c2e4986d92d2df


#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013

"""Blitz++ Array bindings for Python"""

import pkg_resources

from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__

def get_include():
  """Returns the directory containing the C/C++ API include directives"""

  return pkg_resources.resource_filename(__name__, 'include')

def get_config():
  """Returns a string containing the configuration information.
  """

  from .version import externals

  packages = pkg_resources.require(__name__)
  this = packages[0]
  deps = packages[1:]

  retval =  "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version,
      version.api, this.location)
  retval += "  - c/c++ dependencies:\n"
  for k in sorted(externals): retval += "    - %s: %s\n" % (k, externals[k])
  retval += "  - python dependencies:\n"
  for d in deps: retval += "    - %s: %s (%s)\n" % (d.key, d.version, d.location)

  return retval.strip()

# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]

Add API number in get_config()

Add API number in get_config()

Response:
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013

"""Blitz++ Array bindings for Python"""

import pkg_resources

from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__

def get_include():
  """Returns the directory containing the C/C++ API include directives"""

  return pkg_resources.resource_filename(__name__, 'include')

def get_config():
  """Returns a string containing the configuration information.
  """

  from .version import externals

  packages = pkg_resources.require(__name__)
  this = packages[0]
  deps = packages[1:]

  retval =  "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version,
      version.api, this.location)
  retval += "  - c/c++ dependencies:\n"
  for k in sorted(externals): retval += "    - %s: %s\n" % (k, externals[k])
  retval += "  - python dependencies:\n"
  for d in deps: retval += "    - %s: %s (%s)\n" % (d.key, d.version, d.location)

  return retval.strip()

# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]

Prompt:
Add API number in get_config()

#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013

"""Blitz++ Array bindings for Python"""

import pkg_resources

from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__

def get_include():
  """Returns the directory containing the C/C++ API include directives"""

  return pkg_resources.resource_filename(__name__, 'include')

def get_config():
  """Returns a string containing the configuration information.
  """

  from .version import externals

  packages = pkg_resources.require(__name__)
  this = packages[0]
  deps = packages[1:]

  retval =  "%s: %s (%s)\n" % (this.key, this.version, this.location)
  retval += "  - c/c++ dependencies:\n"
  for k in sorted(externals): retval += "    - %s: %s\n" % (k, externals[k])
  retval += "  - python dependencies:\n"
  for d in deps: retval += "    - %s: %s (%s)\n" % (d.key, d.version, d.location)

  return retval.strip()

# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]


from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0007_changeemailrequest'),
    ]

    operations = [
        migrations.AddField(
            model_name='changeemailrequest',
            name='uuid',
            field=models.UUIDField(null=True),
        ),
    ]

Allow null values in UUID field.

Allow null values in UUID field.

Response:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0007_changeemailrequest'),
    ]

    operations = [
        migrations.AddField(
            model_name='changeemailrequest',
            name='uuid',
            field=models.UUIDField(null=True),
        ),
    ]

Prompt:
Allow null values in UUID field.

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0007_changeemailrequest'),
    ]

    operations = [
        migrations.AddField(
            model_name='changeemailrequest', name='uuid', field=models.UUIDField(),
        ),
    ]


import os

from collections import defaultdict

import click

import dtoolcore

@click.command()
@click.argument('dataset_path')
def main(dataset_path):

    uri = "disk:{}".format(dataset_path)

    proto_dataset = dtoolcore.ProtoDataSet.from_uri(uri)

    overlays = defaultdict(dict)
    for handle in proto_dataset._storage_broker.iter_item_handles():
        identifier = dtoolcore.utils.generate_identifier(handle)
        item_metadata = proto_dataset._storage_broker.get_item_metadata(handle)
        for k, v in item_metadata.items():
            overlays[k][identifier] = v

    print overlays.keys()

    # for handle in proto_dataset._storage_broker.iter_item_handles():
    #     print(handle)

    for overlay in overlays:
        print len(overlays[overlay])

if __name__ == '__main__':
    main()

Add script to check dataset integrity

Add script to check dataset integrity

Response:
import os

from collections import defaultdict

import click

import dtoolcore

@click.command()
@click.argument('dataset_path')
def main(dataset_path):

    uri = "disk:{}".format(dataset_path)

    proto_dataset = dtoolcore.ProtoDataSet.from_uri(uri)

    overlays = defaultdict(dict)
    for handle in proto_dataset._storage_broker.iter_item_handles():
        identifier = dtoolcore.utils.generate_identifier(handle)
        item_metadata = proto_dataset._storage_broker.get_item_metadata(handle)
        for k, v in item_metadata.items():
            overlays[k][identifier] = v

    print overlays.keys()

    # for handle in proto_dataset._storage_broker.iter_item_handles():
    #     print(handle)

    for overlay in overlays:
        print len(overlays[overlay])

if __name__ == '__main__':
    main()

Prompt: Add script to check dataset integrity