import bandicoot as bc
from os.path import dirname, abspath, join

if __name__ == '__main__':
    empty_user = bc.User()
    empty_user.attributes['empty'] = True
    empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
    bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), empty_path)

    sample_user = bc.tests.generate_user.sample_user()
    sample_path = join(dirname(abspath(__file__)), 'samples/sample_user_all_metrics.json')
    bc.io.to_json(bc.utils.all(sample_user, summary='extended', groupby=None, flatten=True), sample_path)

Add a simple command to generate automatic regressions

Response:
import bandicoot as bc
from os.path import dirname, abspath, join

if __name__ == '__main__':
    empty_user = bc.User()
    empty_user.attributes['empty'] = True
    empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
    bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), empty_path)

    sample_user = bc.tests.generate_user.sample_user()
    sample_path = join(dirname(abspath(__file__)), 'samples/sample_user_all_metrics.json')
    bc.io.to_json(bc.utils.all(sample_user, summary='extended', groupby=None, flatten=True), sample_path)

Prompt: Add a simple command to generate automatic regressions


from spyc.graph import Vertex, find_cycle, topological_sort

class CircularDependency(Exception):
    pass

class Scheduler(object):

    def __init__(self):
        self.specs = {}

    def ensure(self, spec):
        """Require that ``spec`` is satisfied."""
        if spec.key() in self.specs:
            self.specs[spec.key()].data.merge(spec)
        else:
            self.specs[spec.key()] = Vertex(spec)

    def depend(self, first, next):
        """Specify that ``first`` depends on ``next``.

        This also has the effect of invoking ``ensure`` on both resources.
        """
        first.schedule(self)
        next.schedule(self)
        self.specs[first.key()].edges.add(self.specs[next.key()])

    def apply(self):
        verticies = set(self.specs.values())
        cycle = find_cycle(verticies)
        if cycle is not None:
            raise CircularDependency(cycle)
        for v in topological_sort(verticies):
            v.data.apply()

Response:
from spyc.graph import Vertex, find_cycle, topological_sort

class CircularDependency(Exception):
    pass

class Scheduler(object):

    def __init__(self):
        self.specs = {}

    def ensure(self, spec):
        """Require that ``spec`` is satisfied."""
        if spec.key() in self.specs:
            self.specs[spec.key()].data.merge(spec)
        else:
            self.specs[spec.key()] = Vertex(spec)

    def depend(self, first, next):
        """Specify that ``first`` depends on ``next``.

        This also has the effect of invoking ``ensure`` on both resources.
        """
        first.schedule(self)
        next.schedule(self)
        self.specs[first.key()].edges.add(self.specs[next.key()])

    def apply(self):
        verticies = set(self.specs.values())
        cycle = find_cycle(verticies)
        if cycle is not None:
            raise CircularDependency(cycle)
        for v in topological_sort(verticies):
            v.data.apply()

Prompt:
Raise a more useful error for circular deps.

from spyc.graph import Vertex, find_cycle, topological_sort

class Scheduler(object):

    def __init__(self):
        self.specs = {}

    def ensure(self, spec):
        """Require that ``spec`` is satisfied."""
        if spec.key() in self.specs:
            self.specs[spec.key()].data.merge(spec)
        else:
            self.specs[spec.key()] = Vertex(spec)

    def depend(self, first, next):
        """Specify that ``first`` depends on ``next``.

        This also has the effect of invoking ``ensure`` on both resources.
        """
        first.schedule(self)
        next.schedule(self)
        self.specs[first.key()].edges.add(self.specs[next.key()])

    def apply(self):
        verticies = set(self.specs.values())
        cycle = find_cycle(verticies)
        if cycle is not None:
            assert False  # TODO proper checking
        for v in topological_sort(verticies):
            v.data.apply()


# -*- coding: utf-8 -*-
'''
url-shortener
==============

An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.

.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views

__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'

log_file = app.config['LOG_FILE']

if not app.debug and log_file is not None:
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

app.run()

Response:
# -*- coding: utf-8 -*-
'''
url-shortener
==============

An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.

.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views

__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'

log_file = app.config['LOG_FILE']

if not app.debug and log_file is not None:
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

app.run()

Prompt:
Make application use log file if its name is not None

# -*- coding: utf-8 -*-
'''
url-shortener
==============

An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.

.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views

__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'

if not app.debug:
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

app.run()


# The Fiona data tool.

if __name__ == '__main__':

    import argparse
    import fiona
    import json
    import pprint
    import sys

    parser = argparse.ArgumentParser(
        description="Serialize a file to GeoJSON or view its description")
    parser.add_argument('-i', '--info',
        action='store_true',
        help='View pretty printed description information only')
    parser.add_argument('-j', '--json',
        action='store_true',
        help='Output description as indented JSON')
    parser.add_argument('filename', help="data file name")
    args = parser.parse_args()

    with fiona.open(args.filename, 'r') as col:
        if args.info:
            if args.json:
                meta = col.meta.copy()
                meta.update(name=args.filename)
                print(json.dumps(meta, indent=2))
            else:
                print("\nDescription of: %r" % col)
                print("\nCoordinate reference system (col.crs):")
                pprint.pprint(meta['crs'])
                print("\nFormat driver (col.driver):")
                pprint.pprint(meta['driver'])
                print("\nData description (col.schema):")
                pprint.pprint(meta['schema'])
        else:
            collection = {'type': 'FeatureCollection'}
            collection['features'] = list(col)
            print(json.dumps(collection, indent=2))

Change record output to strict GeoJSON.

Response:
# The Fiona data tool.

if __name__ == '__main__':

    import argparse
    import fiona
    import json
    import pprint
    import sys

    parser = argparse.ArgumentParser(
        description="Serialize a file to GeoJSON or view its description")
    parser.add_argument('-i', '--info',
        action='store_true',
        help='View pretty printed description information only')
    parser.add_argument('-j', '--json',
        action='store_true',
        help='Output description as indented JSON')
    parser.add_argument('filename', help="data file name")
    args = parser.parse_args()

    with fiona.open(args.filename, 'r') as col:
        if args.info:
            if args.json:
                meta = col.meta.copy()
                meta.update(name=args.filename)
                print(json.dumps(meta, indent=2))
            else:
                print("\nDescription of: %r" % col)
                print("\nCoordinate reference system (col.crs):")
                pprint.pprint(meta['crs'])
                print("\nFormat driver (col.driver):")
                pprint.pprint(meta['driver'])
                print("\nData description (col.schema):")
                pprint.pprint(meta['schema'])
        else:
            collection = {'type': 'FeatureCollection'}
            collection['features'] = list(col)
            print(json.dumps(collection, indent=2))

Prompt:
Change record output to strict GeoJSON.

Meaning features in a FeatureCollection.

# The Fiona data tool.

if __name__ == '__main__':

    import argparse
    import fiona
    import json
    import pprint
    import sys

    parser = argparse.ArgumentParser(
        description="Serialize a file to GeoJSON or view its description")
    parser.add_argument('-i', '--info',
        action='store_true',
        help='View pretty printed description information only')
    parser.add_argument('-j', '--json',
        action='store_true',
        help='Output description as indented JSON')
    parser.add_argument('filename', help="data file name")
    args = parser.parse_args()

    with fiona.open(args.filename, 'r') as col:
        if args.info:
            if args.json:
                meta = col.meta.copy()
                meta.update(name=args.filename)
                print(json.dumps(meta, indent=2))
            else:
                print("\nDescription of: %r" % col)
                print("\nCoordinate reference system (col.crs):")
                pprint.pprint(meta['crs'])
                print("\nFormat driver (col.driver):")
                pprint.pprint(meta['driver'])
                print("\nData description (col.schema):")
                pprint.pprint(meta['schema'])
        else:
            print(json.dumps(list(col), indent=2))


#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#

"""This module exports the Bemlint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Bemlint(NodeLinter):
    """Provides an interface to bemlint."""

    name = 'bemlint'
    cmd = 'bemlint @ ${args}'
    config_file = ('--config', '.bemlint.json')
    regex = (
        r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
        r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
        r'(?P<message>.+)'
    )
    multiline = False
    line_col_base = (1, 1)
    error_stream = util.STREAM_BOTH
    tempfile_suffix = 'bem'

    defaults = {
        'selector': 'text.html',
        '--format': 'compact',
    }

    # the following attributes are marked useless for SL4
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'

Response:
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#

"""This module exports the Bemlint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Bemlint(NodeLinter):
    """Provides an interface to bemlint."""

    name = 'bemlint'
    cmd = 'bemlint @ ${args}'
    config_file = ('--config', '.bemlint.json')
    regex = (
        r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
        r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
        r'(?P<message>.+)'
    )
    multiline = False
    line_col_base = (1, 1)
    error_stream = util.STREAM_BOTH
    tempfile_suffix = 'bem'

    defaults = {
        'selector': 'text.html',
        '--format': 'compact',
    }

    # the following attributes are marked useless for SL4
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'

Prompt:
Fix compatibility for SublimeLinter 4.12.0

Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>

#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#

"""This module exports the Bemlint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Bemlint(NodeLinter):
    """Provides an interface to bemlint."""

    syntax = ('html', 'html+tt2', 'html+tt3')
    cmd = ('bemlint', '@', '--format', 'compact')
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'
    config_file = ('--config', '.bemlint.json')
    regex = (
        r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
        r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
        r'(?P<message>.+)'
    )
    multiline = False
    line_col_base = (1, 1)
    error_stream = util.STREAM_BOTH
    tempfile_suffix = 'bem'


import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys

from dogen.plugins.repo import Repo
from dogen.generator import Generator

class TestPackage(unittest.TestCase):
    def setUp(self):
        self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
        self.descriptor = tempfile.NamedTemporaryFile(delete=False)
        self.target_dir = os.path.join(self.workdir, "target")
        self.log = mock.Mock()

    def teardown(self):
        shutil.rmtree(self.workdir)

    def write_config(self, config):
        with self.descriptor as f:
            f.write(config.encode())

    def prepare_dogen(self, repo_files_dir=None):
        args = argparse.Namespace(path=self.descriptor.name, output=self.target_dir, without_sources=None,
                                  template=None, scripts_path=None, additional_script=None,
                                  skip_ssl_verification=None, repo_files_dir=repo_files_dir)
        self.dogen = Generator(self.log, args, [Repo])

    def test_custom_repo_files_should_add_two(self):
        open(os.path.join(self.workdir, "fedora.repo"), 'a').close()
        open(os.path.join(self.workdir, "test.repo"), 'a').close()

        self.write_config("release: '1'\nversion: '1'\ncmd:\n - whoami\nfrom: scratch\nname: someimage\npackages:\n - wget")
        self.prepare_dogen(self.workdir)
        self.dogen.run()

        self.assertIsNotNone(self.dogen.cfg)
        self.assertIsNotNone(self.dogen.cfg.get('packages'))
        self.assertIsInstance(self.dogen.cfg.get('packages'), list)
        self.assertIn("wget", self.dogen.cfg.get('packages'))

        dockerfile = open(os.path.join(self.target_dir, "Dockerfile")).read()

        sys.stderr.write("\t\t\tDEBUGDEBUG\n{}\n".format(dockerfile))
        self.assertTrue(re.match(r'.*yum install[^\n]+wget', dockerfile, re.DOTALL))
        self.assertTrue(re.match(r'.*rpm -q +wget', dockerfile, re.DOTALL))

Add a test for package generation

Add a test for package generation

Response:
import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys

from dogen.plugins.repo import Repo
from dogen.generator import Generator

class TestPackage(unittest.TestCase):
    def setUp(self):
        self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
        self.descriptor = tempfile.NamedTemporaryFile(delete=False)
        self.target_dir = os.path.join(self.workdir, "target")
        self.log = mock.Mock()

    def teardown(self):
        shutil.rmtree(self.workdir)

    def write_config(self, config):
        with self.descriptor as f:
            f.write(config.encode())

    def prepare_dogen(self, repo_files_dir=None):
        args = argparse.Namespace(path=self.descriptor.name, output=self.target_dir, without_sources=None,
                                  template=None, scripts_path=None, additional_script=None,
                                  skip_ssl_verification=None, repo_files_dir=repo_files_dir)
        self.dogen = Generator(self.log, args, [Repo])

    def test_custom_repo_files_should_add_two(self):
        open(os.path.join(self.workdir, "fedora.repo"), 'a').close()
        open(os.path.join(self.workdir, "test.repo"), 'a').close()

        self.write_config("release: '1'\nversion: '1'\ncmd:\n - whoami\nfrom: scratch\nname: someimage\npackages:\n - wget")
        self.prepare_dogen(self.workdir)
        self.dogen.run()

        self.assertIsNotNone(self.dogen.cfg)
        self.assertIsNotNone(self.dogen.cfg.get('packages'))
        self.assertIsInstance(self.dogen.cfg.get('packages'), list)
        self.assertIn("wget", self.dogen.cfg.get('packages'))

        dockerfile = open(os.path.join(self.target_dir, "Dockerfile")).read()

        sys.stderr.write("\t\t\tDEBUGDEBUG\n{}\n".format(dockerfile))
        self.assertTrue(re.match(r'.*yum install[^\n]+wget', dockerfile, re.DOTALL))
        self.assertTrue(re.match(r'.*rpm -q +wget', dockerfile, re.DOTALL))

Prompt: Add a test for package generation


from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow

LOCK_USER = 'lock_user'
STATUS = '_status'

class ItemLock():
    def __init__(self, data_layer):
        self.data_layer = data_layer

    def lock(self, filter, user, etag):
        item_model = ItemModel(self.data_layer)
        item = item_model.find_one(filter)
        if item and self._can_lock(item, user):
            # filter[ETAG] = etag
            updates = {LOCK_USER: user, 'lock_time': utcnow()}
            item_model.update(filter, updates)
            item[LOCK_USER] = user
        else:
            raise SuperdeskError('Item locked by another user')
        return item

    def unlock(self, filter, user, etag):
        item_model = ItemModel()
        filter[LOCK_USER] = user
        filter[ETAG] = etag
        item = item_model.find_one(filter)
        if item:
            update = {LOCK_USER: None}
            item_model.update(filter, update)

    def _can_lock(self, item, user):
        # TODO: implement
        return True

Set timestamp on item lock operation

Set timestamp on item lock operation

Response:
from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow

LOCK_USER = 'lock_user'
STATUS = '_status'

class ItemLock():
    def __init__(self, data_layer):
        self.data_layer = data_layer

    def lock(self, filter, user, etag):
        item_model = ItemModel(self.data_layer)
        item = item_model.find_one(filter)
        if item and self._can_lock(item, user):
            # filter[ETAG] = etag
            updates = {LOCK_USER: user, 'lock_time': utcnow()}
            item_model.update(filter, updates)
            item[LOCK_USER] = user
        else:
            raise SuperdeskError('Item locked by another user')
        return item

    def unlock(self, filter, user, etag):
        item_model = ItemModel()
        filter[LOCK_USER] = user
        filter[ETAG] = etag
        item = item_model.find_one(filter)
        if item:
            update = {LOCK_USER: None}
            item_model.update(filter, update)

    def _can_lock(self, item, user):
        # TODO: implement
        return True

Prompt:
Set timestamp on item lock operation

from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError

LOCK_USER = 'lock_user'
STATUS = '_status'

class ItemLock():
    def __init__(self, data_layer):
        self.data_layer = data_layer

    def lock(self, filter, user, etag):
        item_model = ItemModel(self.data_layer)
        item = item_model.find_one(filter)
        if item and self._can_lock(item, user):
            # filter[ETAG] = etag
            updates = {LOCK_USER: user}
            item_model.update(filter, updates)
            item[LOCK_USER] = user
        else:
            raise SuperdeskError('Item locked by another user')
        return item

    def unlock(self, filter, user, etag):
        item_model = ItemModel()
        filter[LOCK_USER] = user
        filter[ETAG] = etag
        item = item_model.find_one(filter)
        if item:
            update = {LOCK_USER: None}
            item_model.update(filter, update)

    def _can_lock(self, item, user):
        # TODO: implement
        return True


from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot

class ChatterBotView(View):

    chatterbot = ChatBot(
        settings.CHATTERBOT['NAME'],
        storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
        input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter',
        output_adapter='chatterbot.adapters.output.OutputFormatAdapter',
        output_format='json'
    )

    def post(self, request, *args, **kwargs):
        input_statement = request.POST.get('text')

        response_data = self.chatterbot.get_response(input_statement)

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def patch(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def delete(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

Response:
from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot

class ChatterBotView(View):

    chatterbot = ChatBot(
        settings.CHATTERBOT['NAME'],
        storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
        input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter',
        output_adapter='chatterbot.adapters.output.OutputFormatAdapter',
        output_format='json'
    )

    def post(self, request, *args, **kwargs):
        input_statement = request.POST.get('text')

        response_data = self.chatterbot.get_response(input_statement)

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def patch(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def delete(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

Prompt:
Initialize ChatterBot in django view module instead of settings.

from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings

class ChatterBotView(View):

    def post(self, request, *args, **kwargs):
        input_statement = request.POST.get('text')

        response_data = settings.CHATTERBOT.get_response(input_statement)

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def patch(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def delete(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('routes', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='route',
            name='slug',
            field=models.SlugField(max_length=255, help_text='The url fragment at this point in the Route hierarchy.', default=''),
        ),
    ]

Add missing migration to routes app

Add missing migration to routes app

Response:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('routes', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='route',
            name='slug',
            field=models.SlugField(max_length=255, help_text='The url fragment at this point in the Route hierarchy.', default=''),
        ),
    ]

Prompt: Add missing migration to routes app


from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.22',
        'future>=0.16,<0.18',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<2.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)

Response:
from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.22',
        'future>=0.16,<0.18',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<2.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)

Prompt:
Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22

Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.21.0)

Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.21',
        'future>=0.16,<0.18',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<2.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)


#!/usr/bin/python
#coding: utf-8
import requests
import re
import time
from time import gmtime, strftime

class GenNowPlayingID(object):
	"""docstring for ClassName"""
	def __init__(self):
		#super(ClassName, self).__init__()
		# self.arg = arg
		pass

	def GenNowPlayingIdList(self):
		page = requests.get('https://movie.douban.com/nowplaying/beijing/')
		content=page.text.encode("utf-8")
		pattern=re.compile(r'(?<=id=")\d+(?="\n)')
		result=pattern.findall(content)

		currentTime = strftime("%Y%m%d_%H:%M:%S", time.localtime(time.time()))
		print currentTime
		filename = './nowplaying_id/' + currentTime + '.id'
		fp = open(filename,'w')

		for iterm in result:
			fp.write(iterm+"\n")
		fp.close()

if __name__=="__main__":
	genNowPlayingID = GenNowPlayingID()
	genNowPlayingID.GenNowPlayingIdList()

Write the nowplaying movie id to file

Write the nowplaying movie id to file

Response:
#!/usr/bin/python
#coding: utf-8
import requests
import re
import time
from time import gmtime, strftime

class GenNowPlayingID(object):
	"""docstring for ClassName"""
	def __init__(self):
		#super(ClassName, self).__init__()
		# self.arg = arg
		pass

	def GenNowPlayingIdList(self):
		page = requests.get('https://movie.douban.com/nowplaying/beijing/')
		content=page.text.encode("utf-8")
		pattern=re.compile(r'(?<=id=")\d+(?="\n)')
		result=pattern.findall(content)

		currentTime = strftime("%Y%m%d_%H:%M:%S", time.localtime(time.time()))
		print currentTime
		filename = './nowplaying_id/' + currentTime + '.id'
		fp = open(filename,'w')

		for iterm in result:
			fp.write(iterm+"\n")
		fp.close()

if __name__=="__main__":
	genNowPlayingID = GenNowPlayingID()
	genNowPlayingID.GenNowPlayingIdList()

Prompt:
Write the nowplaying movie id to file

#!/usr/bin/python
#coding: utf-8
import requests
import re
if __name__=="__main__":
	page = requests.get('https://movie.douban.com/nowplaying/beijing/')
	content=page.text.encode("utf-8")
	pattern=re.compile(r'(?<=id=")\d+(?="\n)')
	result=pattern.findall(content)
	for iterm in result:
		print iterm


from django.apps import AppConfig

class OstinatoBlogConfig(AppConfig):
    name = 'ostinato.blog'
    label = 'ostinato_blog'
    verbose_name = 'Ostinato Blog Engine'

Correct app label of ostinato_blog

Correct app label of ostinato_blog

Response:
from django.apps import AppConfig

class OstinatoBlogConfig(AppConfig):
    name = 'ostinato.blog'
    label = 'ostinato_blog'
    verbose_name = 'Ostinato Blog Engine'

Prompt:
Correct app label of ostinato_blog

from django.apps import AppConfig

class OstinatoBlogConfig(AppConfig):
    name = 'ostinato.blog'
    label = 'ost_blog'
    verbose_name = 'Ostinato Blog Engine'


from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

def isValidUserName(username):
	try:
		User.objects.get(username=username)
	except User.DoesNotExist:
		return
	raise ValidationError('The username "%s" is already taken.' % username)

class RegistrationForm(UserCreationForm):

	username = forms.CharField(label='username',
							max_length=30,
							required=True, validators=[isValidUserName])
	class Meta:
		model = User
		fields = ('username','first_name', 'last_name', 'email',)

	def save(self, commit=True):
		new_user = super(RegistrationForm, self).save(commit=False)

		new_user.is_active = False

		if commit:
			new_user.save()

		return new_user

Response:
from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

def isValidUserName(username):
	try:
		User.objects.get(username=username)
	except User.DoesNotExist:
		return
	raise ValidationError('The username "%s" is already taken.' % username)

class RegistrationForm(UserCreationForm):

	username = forms.CharField(label='username',
							max_length=30,
							required=True, validators=[isValidUserName])
	class Meta:
		model = User
		fields = ('username','first_name', 'last_name', 'email',)

	def save(self, commit=True):
		new_user = super(RegistrationForm, self).save(commit=False)

		new_user.is_active = False

		if commit:
			new_user.save()

		return new_user

Prompt:
Implement validation to the username field.

from django import forms
from django.core import validators
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):

	username = forms.CharField(label='username',
							max_length=30,
							required=True,) #validators=[self.isValidUserName])
	class Meta:
		model = User
		fields = ('username','first_name', 'last_name', 'email',)

#	def isValidUserName(self, field_data, all_data):
#		try:
#			User.objects.get(username=field_data)
#		except User.DoesNotExist:
#			return
#		raise validators.ValidationError('The username "%s" is already taken.' % field_data)

	def save(self, commit=True):
		new_user = super(RegistrationForm, self).save(commit=False)

		new_user.is_active = False

		if commit:
			new_user.save()

		return new_user


# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop

def get_shop_from_host(host):
    """
    Try to find a shop that matches a `host`
    e.g: shop.domain.com, domain.com, localhost:8000

    :type host str
    """
    shop = Shop.objects.filter(domain=host).first()

    if not shop and ":" in host:
        shop = Shop.objects.filter(domain=host.rsplit(":")[0]).first()

    if not shop:
        subdomain = host.split(".")[0]
        shop = Shop.objects.filter(domain=subdomain).first()

    return shop

Response:
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop

def get_shop_from_host(host):
    """
    Try to find a shop that matches a `host`
    e.g: shop.domain.com, domain.com, localhost:8000

    :type host str
    """
    shop = Shop.objects.filter(domain=host).first()

    if not shop and ":" in host:
        shop = Shop.objects.filter(domain=host.rsplit(":")[0]).first()

    if not shop:
        subdomain = host.split(".")[0]
        shop = Shop.objects.filter(domain=subdomain).first()

    return shop

Prompt:
Make handle ports better when choosing shop

Refs EE-235

# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop

def get_shop_from_host(host):
    """
    Try to find a shop that matches a `host`
    e.g: shop.domain.com, domain.com, localhost:8000

    :type host str
    """
    shop = Shop.objects.filter(domain=host).first()

    if not shop:
        subdomain = host.split(".")[0]
        shop = Shop.objects.filter(domain=subdomain).first()

    return shop


# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals

from django.db import migrations, models
try:
    import django.contrib.auth.validators
    extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
    extra_kwargs = {}

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0013_profile_event_reminder_time'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'},
                                   help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
                                   max_length=150, unique=True, verbose_name='username', **extra_kwargs),
        ),
    ]

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals

from django.db import migrations, models
try:
    import django.contrib.auth.validators
    extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
    extra_kwargs = {}

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0013_profile_event_reminder_time'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'},
                                   help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
                                   max_length=150, unique=True, verbose_name='username', **extra_kwargs),
        ),
    ]

Prompt:
Fix backward compatibility of migrations

# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals

import django.contrib.auth.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0013_profile_event_reminder_time'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.ASCIIUsernameValidator()], verbose_name='username'),
        ),
    ]


import hashlib
import urllib

import bencode

class Torrent(object):

  def __init__(self, path):
    self.encoded = self._get_meta(path)
    self.decoded = bencode.bdecode(self.encoded)

  def _get_meta(self, path):
    with open(path) as f:
      return f.read()

  def __getitem__(self, item):
    return self.decoded[item]

  @property
  def hash(self):
    info_hash = hashlib.sha1(bencode.bencode(self.decoded['info'])).digest()
    return urllib.quote(info_hash)

  @property
  def urls(self):
    urls = [self.decoded['announce']]
    urls += [announce[0] for announce in self.decoded['announce-list']]

    return urls

Use __getitem__ to improve readbility

Use __getitem__ to improve readbility

Response:
import hashlib
import urllib

import bencode

class Torrent(object):

  def __init__(self, path):
    self.encoded = self._get_meta(path)
    self.decoded = bencode.bdecode(self.encoded)

  def _get_meta(self, path):
    with open(path) as f:
      return f.read()

  def __getitem__(self, item):
    return self.decoded[item]

  @property
  def hash(self):
    info_hash = hashlib.sha1(bencode.bencode(self.decoded['info'])).digest()
    return urllib.quote(info_hash)

  @property
  def urls(self):
    urls = [self.decoded['announce']]
    urls += [announce[0] for announce in self.decoded['announce-list']]

    return urls

Prompt:
Use __getitem__ to improve readbility

import hashlib
import urllib

import bencode

class Torrent(object):

  def __init__(self, path):
    self.encoded = self._get_meta(path)
    self.decoded = bencode.bdecode(self.encoded)

  def _get_meta(self, path):
    with open(path) as f:
      return f.read()

  @property
  def hash(self):
    info_hash = hashlib.sha1(bencode.bencode(self.decoded['info'])).digest()
    return urllib.quote(info_hash)

  @property
  def urls(self):
    urls = [self.decoded['announce']]
    urls += [announce[0] for announce in self.decoded['announce-list']]

    return urls


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

import unittest
import vault_shell.vault_commandhelper as VaultHelper

class VaultShellTests(unittest.TestCase):
    def test_basic(self):
        print "test basic. Pass"
        vaulthelper = VaultHelper.VaultCommandHelper()
        self.failUnless(vaulthelper is not None)

    def test_execute_vault_commands(self):
        vaulthelper = VaultHelper.VaultCommandHelper()
        output = vaulthelper.execute_vault_commands(['vault'])
        self.failUnless(output is not None)

    def test_get_commandkey_from_cmdlist(self):
        vaulthelper = VaultHelper.VaultCommandHelper()
        cmdkey = vaulthelper.get_commandkey_from_cmdlist(["token-create"])
        self.assertEqual(cmdkey,
                         "vault_token-create",
                         msg="cmdkey did not match")

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

import unittest
import vault_shell.vault_commandhelper as VaultHelper

class VaultShellTests(unittest.TestCase):
    def test_basic(self):
        print "test basic. Pass"
        vaulthelper = VaultHelper.VaultCommandHelper()
        self.failUnless(vaulthelper is not None)

    def test_execute_vault_commands(self):
        vaulthelper = VaultHelper.VaultCommandHelper()
        output = vaulthelper.execute_vault_commands(['vault'])
        self.failUnless(output is not None)

    def test_get_commandkey_from_cmdlist(self):
        vaulthelper = VaultHelper.VaultCommandHelper()
        cmdkey = vaulthelper.get_commandkey_from_cmdlist(["token-create"])
        self.assertEqual(cmdkey,
                         "vault_token-create",
                         msg="cmdkey did not match")

Prompt:
Add more tests for the vault commandhelper

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

import unittest

class VaultShellTests(unittest.TestCase):
    def test_basic(self):
        print "test basic. Pass"


from .base import AuthenticationBase

class Users(AuthenticationBase):

    """Userinfo related endpoints.

    Args:
        domain (str): Your auth0 domain (e.g: username.auth0.com)
    """

    def __init__(self, domain):
        self.domain = domain

    def userinfo(self, access_token):

        """Returns the user information based on the Auth0 access token.

        Args:
            access_token (str): Auth0 access token (obtained during login).

        Returns:
            The user profile.
        """

        return self.get(
            url='https://%s/userinfo' % self.domain,
            headers={'Authorization': 'Bearer %s' % access_token}
        )

    def tokeninfo(self, jwt):

        """Returns user profile based on the user's jwt

        Validates a JSON Web Token (signature and expiration) and returns the
        user information associated with the user id (sub property) of
        the token.

        Args:
            jwt (str): User's jwt

        Returns:
            The user profile.
        """

        return self.post(
            url='https://%s/tokeninfo' % self.domain,
            data={'id_token': jwt},
            headers={'Content-Type: application/json'}
        )

Add docstrings to Users class

Add docstrings to Users class

Response:
from .base import AuthenticationBase

class Users(AuthenticationBase):

    """Userinfo related endpoints.

    Args:
        domain (str): Your auth0 domain (e.g: username.auth0.com)
    """

    def __init__(self, domain):
        self.domain = domain

    def userinfo(self, access_token):

        """Returns the user information based on the Auth0 access token.

        Args:
            access_token (str): Auth0 access token (obtained during login).

        Returns:
            The user profile.
        """

        return self.get(
            url='https://%s/userinfo' % self.domain,
            headers={'Authorization': 'Bearer %s' % access_token}
        )

    def tokeninfo(self, jwt):

        """Returns user profile based on the user's jwt

        Validates a JSON Web Token (signature and expiration) and returns the
        user information associated with the user id (sub property) of
        the token.

        Args:
            jwt (str): User's jwt

        Returns:
            The user profile.
        """

        return self.post(
            url='https://%s/tokeninfo' % self.domain,
            data={'id_token': jwt},
            headers={'Content-Type: application/json'}
        )

Prompt:
Add docstrings to Users class

from .base import AuthenticationBase

class Users(AuthenticationBase):

    def __init__(self, domain):
        self.domain = domain

    def userinfo(self, access_token):
        return self.get(
            url='https://%s/userinfo' % self.domain,
            headers={'Authorization': 'Bearer %s' % access_token}
        )

    def tokeninfo(self, jwt):
        return self.post(
            url='https://%s/tokeninfo' % self.domain,
            data={'id_token': jwt},
            headers={'Content-Type: application/json'}
        )


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

import os
import unittest
import string
import sys

try:
    from subprocess import check_output
except ImportError:
    from subprocess import Popen, PIPE, CalledProcessError

    def check_output(*popenargs, **kwargs):
        """Lifted from python 2.7 stdlib."""
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be '
                             'overridden.')
        process = Popen(stdout=PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise CalledProcessError(retcode, cmd, output=output)
        return output

os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)

class TestTranslations(unittest.TestCase):

    def test_translations(self):
        path = ':'.join(sys.path)
        translated_message = check_output(['python', __file__, path])
        self.assertEquals(translated_message, 'testo mesaĝon\n')

if __name__ == "__main__":
    sys.path = string.split(sys.argv[1], ':')
    from swift import gettext_ as _
    print _('test message')

Make test_translations test our tree

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

import os
import unittest
import string
import sys

try:
    from subprocess import check_output
except ImportError:
    from subprocess import Popen, PIPE, CalledProcessError

    def check_output(*popenargs, **kwargs):
        """Lifted from python 2.7 stdlib."""
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be '
                             'overridden.')
        process = Popen(stdout=PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise CalledProcessError(retcode, cmd, output=output)
        return output

os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)

class TestTranslations(unittest.TestCase):

    def test_translations(self):
        path = ':'.join(sys.path)
        translated_message = check_output(['python', __file__, path])
        self.assertEquals(translated_message, 'testo mesaĝon\n')

if __name__ == "__main__":
    sys.path = string.split(sys.argv[1], ':')
    from swift import gettext_ as _
    print _('test message')

Prompt:
Make test_translations test our tree

In order to run the correct classes, Python test framework adjusts
sys.path. However, these changes are not propagated to subprocesses.
Therefore, the test actually tries to test installed Swift, not
the one in which it is running.

The usual suggestion is to run "python setup.py develop" before
testing, but it's annoying and error-prone. If you forget it,
you may test the code in /usr very easily, and never know.

Let's just pass the correct path to subprocess. Much safer.

Change-Id: Ic71314e8462cf6e0579d704ffe9fbbfac7e6ba24

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

import os
import unittest

try:
    from subprocess import check_output
except ImportError:
    from subprocess import Popen, PIPE, CalledProcessError

    def check_output(*popenargs, **kwargs):
        """Lifted from python 2.7 stdlib."""
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be '
                             'overridden.')
        process = Popen(stdout=PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise CalledProcessError(retcode, cmd, output=output)
        return output

os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)
from swift import gettext_ as _

class TestTranslations(unittest.TestCase):

    def test_translations(self):
        translated_message = check_output(['python', __file__])
        self.assertEquals(translated_message, 'testo mesaĝon\n')

if __name__ == "__main__":
    print _('test message')


"""
    persistence_engine.py
    ~~~~~~~~~~~~
    Implements put, get, delete methods for PersistenceStage.  Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
    """

class PersistenceEngine(object):
    """ Basic persistence engine implemented as a regular Python dict."""

    def __init__(self):
        self._persistence = dict()

    def keys():
        return self._persistence.keys()

    def put(self, key, value, timestamp):
        """ Put key value pair into storage"""
        self._persistence[key] = {'value': value, 'timestamp': timestamp}
        return True

    def get(self, key):
        """ Get key's value """
        return self._persistence[key]['value'], self._persistence[key]['timestamp']

    def delete(self, key):
        """ Delete key value pair """
        del self._persistence[key]
        return True

Remove use of timestamped value.

Response:
"""
    persistence_engine.py
    ~~~~~~~~~~~~
    Implements put, get, delete methods for PersistenceStage.  Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
    """

class PersistenceEngine(object):
    """ Basic persistence engine implemented as a regular Python dict."""

    def __init__(self):
        self._persistence = dict()

    def keys():
        return self._persistence.keys()

    def put(self, key, value, timestamp):
        """ Put key value pair into storage"""
        self._persistence[key] = {'value': value, 'timestamp': timestamp}
        return True

    def get(self, key):
        """ Get key's value """
        return self._persistence[key]['value'], self._persistence[key]['timestamp']

    def delete(self, key):
        """ Delete key value pair """
        del self._persistence[key]
        return True

Prompt:
Remove use of timestamped value.

Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp .  Instead, now all messages are sent around
as json dicts.

The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client.

"""
    persistence_engine.py
    ~~~~~~~~~~~~
    Implements put, get, delete methods for PersistenceStage.  Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
    """

class PersistenceEngine(object):
    """ Basic persistence engine implemented as a regular Python dict."""

    def __init__(self):
        self._persistence = dict()

    def keys():
        return self._persistence.keys()

    def put(self, key, value):
        """ Put key value pair into storage"""
        self._persistence[key] = value

    def get(self, key):
        """ Get key's value """
        return self._persistence[key]

    def delete(self, key):
        """ Delete key value pair """
        del self._persistence[key]


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

from supybot.test import *
from supybot.i18n import PluginInternationalization, internationalizeDocstring
import supybot.conf as conf
import supybot.i18n as i18n

msg_en = 'The operation succeeded.'
msg_fr = 'Opération effectuée avec succès.'

_ = PluginInternationalization()

@internationalizeDocstring
def foo():
    'The operation succeeded.'
    pass

class I18nTestCase(SupyTestCase):
    def testPluginInternationalization(self):
        self.assertEqual(_(msg_en), msg_en)
        with conf.supybot.language.context('fr'):
            self.assertEqual(_(msg_en), msg_fr)
        conf.supybot.language.setValue('en')
        self.assertEqual(_(msg_en), msg_en)

    def testDocstring(self):
        self.assertEqual(foo.__doc__, msg_en)
        with conf.supybot.language.context('fr'):
            self.assertEqual(foo.__doc__, msg_fr)
        i18n.reloadLocales()
        self.assertEqual(foo.__doc__, msg_en)

Add unit tests for i18n.

Add unit tests for i18n.

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

from supybot.test import *
from supybot.i18n import PluginInternationalization, internationalizeDocstring
import supybot.conf as conf
import supybot.i18n as i18n

msg_en = 'The operation succeeded.'
msg_fr = 'Opération effectuée avec succès.'

_ = PluginInternationalization()

@internationalizeDocstring
def foo():
    'The operation succeeded.'
    pass

class I18nTestCase(SupyTestCase):
    def testPluginInternationalization(self):
        self.assertEqual(_(msg_en), msg_en)
        with conf.supybot.language.context('fr'):
            self.assertEqual(_(msg_en), msg_fr)
        conf.supybot.language.setValue('en')
        self.assertEqual(_(msg_en), msg_en)

    def testDocstring(self):
        self.assertEqual(foo.__doc__, msg_en)
        with conf.supybot.language.context('fr'):
            self.assertEqual(foo.__doc__, msg_fr)
        i18n.reloadLocales()
        self.assertEqual(foo.__doc__, msg_en)

Prompt: Add unit tests for i18n.


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

import argparse
import cPickle as pickle
import gzip
import sys

import cv2
from imagesift import get_sift_keypoints
import numpy as np
from sklearn.datasets import load_files
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import normalize

parser = argparse.ArgumentParser()
parser.add_argument('container_path')
parser.add_argument('bof_path')
parser.add_argument('clf_path')
args = parser.parse_args()

container_path = args.container_path
bof_path = args.bof_path
clf_path = args.clf_path

bunch_files = load_files(container_path=container_path,
                         description='images',
                         shuffle=False,
                         load_content=False)

with gzip.open(bof_path, 'rb') as f:
    bof = pickle.load(f)

with gzip.open(clf_path, 'rb') as f:
    clf = pickle.load(f)

descs = []
for fname in bunch_files.filenames:
    img = cv2.imread(fname, 0)
    _, desc = get_sift_keypoints(img)
    descs.append(desc)
X = bof.transform(descs)
normalize(X, copy=False)
y_pred = clf.predict(X)

y = bunch_files.target
print accuracy_score(y, y_pred)
print classification_report(y, y_pred, target_names=clf.target_names_)

Add bof object recognition test script

[jsk_2015_apc_common] Add bof object recognition test script

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

import argparse
import cPickle as pickle
import gzip
import sys

import cv2
from imagesift import get_sift_keypoints
import numpy as np
from sklearn.datasets import load_files
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import normalize

parser = argparse.ArgumentParser()
parser.add_argument('container_path')
parser.add_argument('bof_path')
parser.add_argument('clf_path')
args = parser.parse_args()

container_path = args.container_path
bof_path = args.bof_path
clf_path = args.clf_path

bunch_files = load_files(container_path=container_path,
                         description='images',
                         shuffle=False,
                         load_content=False)

with gzip.open(bof_path, 'rb') as f:
    bof = pickle.load(f)

with gzip.open(clf_path, 'rb') as f:
    clf = pickle.load(f)

descs = []
for fname in bunch_files.filenames:
    img = cv2.imread(fname, 0)
    _, desc = get_sift_keypoints(img)
    descs.append(desc)
X = bof.transform(descs)
normalize(X, copy=False)
y_pred = clf.predict(X)

y = bunch_files.target
print accuracy_score(y, y_pred)
print classification_report(y, y_pred, target_names=clf.target_names_)

Prompt: [jsk_2015_apc_common] Add bof object recognition test script


from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token

class DynamicSplitActivation(AbstractGateActivation):
    def calculate_next(self):
        self._split_count = self.flow_task._task_count_callback(self.process)

    def activate_next(self):
        if self._split_count:
            token_source = Token.split_token_source(self.task.token, self.task.pk)
            for _ in range(self._split_count):
                self.flow_task._next.activate(prev_activation=self, token=next(token_source))

class DynamicSplit(base.NextNodeMixin,
                   base.UndoViewMixin,
                   base.CancelViewMixin,
                   base.PerformViewMixin,
                   base.DetailsViewMixin,
                   base.Gateway):
    """
    Activates several outgoing task instances depends on callback value

    Example::

        spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
            .Next(this.make_decision)

        make_decision = flow.View(MyView) \\
            .Next(this.join_on_decision)

        join_on_decision = flow.Join() \\
            .Next(this.end)
    """
    task_type = 'SPLIT'
    activation_cls = DynamicSplitActivation

    def __init__(self, callback):
        super(DynamicSplit, self).__init__()
        self._task_count_callback = callback

Add undo to custom node sample

Add undo to custom node sample

Response:
from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token

class DynamicSplitActivation(AbstractGateActivation):
    def calculate_next(self):
        self._split_count = self.flow_task._task_count_callback(self.process)

    def activate_next(self):
        if self._split_count:
            token_source = Token.split_token_source(self.task.token, self.task.pk)
            for _ in range(self._split_count):
                self.flow_task._next.activate(prev_activation=self, token=next(token_source))

class DynamicSplit(base.NextNodeMixin,
                   base.UndoViewMixin,
                   base.CancelViewMixin,
                   base.PerformViewMixin,
                   base.DetailsViewMixin,
                   base.Gateway):
    """
    Activates several outgoing task instances depends on callback value

    Example::

        spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
            .Next(this.make_decision)

        make_decision = flow.View(MyView) \\
            .Next(this.join_on_decision)

        join_on_decision = flow.Join() \\
            .Next(this.end)
    """
    task_type = 'SPLIT'
    activation_cls = DynamicSplitActivation

    def __init__(self, callback):
        super(DynamicSplit, self).__init__()
        self._task_count_callback = callback

Prompt:
Add undo to custom node sample

from viewflow.activation import AbstractGateActivation, Activation
from viewflow.flow import base
from viewflow.token import Token

class DynamicSplitActivation(AbstractGateActivation):
    def calculate_next(self):
        self._split_count = self.flow_task._task_count_callback(self.process)

    @Activation.status.super()
    def activate_next(self):
        if self._split_count:
            token_source = Token.split_token_source(self.task.token, self.task.pk)
            for _ in range(self._split_count):
                self.flow_task._next.activate(prev_activation=self, token=next(token_source))

class DynamicSplit(base.NextNodeMixin, base.DetailsViewMixin, base.Gateway):
    """
    Activates several outgoing task instances depends on callback value

    Example::

        spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
            .Next(this.make_decision)

        make_decision = flow.View(MyView) \\
            .Next(this.join_on_decision)

        join_on_decision = flow.Join() \\
            .Next(this.end)
    """
    task_type = 'SPLIT'
    activation_cls = DynamicSplitActivation

    def __init__(self, callback):
        super(DynamicSplit, self).__init__()
        self._task_count_callback = callback


#!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages

install_requires = [
    "Jinja2",
    "boto>=2.36.0",
    "flask",
    "httpretty==0.8.10",
    "requests",
    "xmltodict",
    "six",
    "werkzeug",
    "sure",
    "freezegun"
]

extras_require = {
    # No builtin OrderedDict before 2.7
    ':python_version=="2.6"': ['ordereddict'],
}

setup(
    name='moto',
    version='0.4.27',
    description='A library that allows your python tests to easily'
                ' mock out the boto library',
    author='Steve Pulec',
    author_email='spulec@gmail.com',
    url='https://github.com/spulec/moto',
    entry_points={
        'console_scripts': [
            'moto_server = moto.server:main',
        ],
    },
    packages=find_packages(exclude=("tests", "tests.*")),
    install_requires=install_requires,
    extras_require=extras_require,
    license="Apache",
    test_suite="tests",
    classifiers=[
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "License :: OSI Approved :: Apache Software License",
        "Topic :: Software Development :: Testing",
    ],
)

Response:
#!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages

install_requires = [
    "Jinja2",
    "boto>=2.36.0",
    "flask",
    "httpretty==0.8.10",
    "requests",
    "xmltodict",
    "six",
    "werkzeug",
    "sure",
    "freezegun"
]

extras_require = {
    # No builtin OrderedDict before 2.7
    ':python_version=="2.6"': ['ordereddict'],
}

setup(
    name='moto',
    version='0.4.27',
    description='A library that allows your python tests to easily'
                ' mock out the boto library',
    author='Steve Pulec',
    author_email='spulec@gmail.com',
    url='https://github.com/spulec/moto',
    entry_points={
        'console_scripts': [
            'moto_server = moto.server:main',
        ],
    },
    packages=find_packages(exclude=("tests", "tests.*")),
    install_requires=install_requires,
    extras_require=extras_require,
    license="Apache",
    test_suite="tests",
    classifiers=[
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "License :: OSI Approved :: Apache Software License",
        "Topic :: Software Development :: Testing",
    ],
)

Prompt:
Revert "Bumping the version reflecting the bugfix"

This reverts commit 7f3daf4755aff19d04acf865df39f7d188655b15.

#!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages

install_requires = [
    "Jinja2",
    "boto>=2.36.0",
    "flask",
    "httpretty==0.8.10",
    "requests",
    "xmltodict",
    "six",
    "werkzeug",
    "sure",
    "freezegun"
]

extras_require = {
    # No builtin OrderedDict before 2.7
    ':python_version=="2.6"': ['ordereddict'],
}

setup(
    name='moto',
    version='0.4.28',
    description='A library that allows your python tests to easily'
                ' mock out the boto library',
    author='Steve Pulec',
    author_email='spulec@gmail.com',
    url='https://github.com/spulec/moto',
    entry_points={
        'console_scripts': [
            'moto_server = moto.server:main',
        ],
    },
    packages=find_packages(exclude=("tests", "tests.*")),
    install_requires=install_requires,
    extras_require=extras_require,
    license="Apache",
    test_suite="tests",
    classifiers=[
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "License :: OSI Approved :: Apache Software License",
        "Topic :: Software Development :: Testing",
    ],
)


import requests
import re

url = raw_input("Enter URL with http or https prefix : " )
print url
website= requests.get(url)

html = website.text
print html
linklist = re.findall('"((http|ftp)s?://.*?)"',html)
print linklist
for link in linklist:
    print link[0]

Print out all links on a page

Print out all links on a page

Response:
import requests
import re

url = raw_input("Enter URL with http or https prefix : " )
print url
website= requests.get(url)

html = website.text
print html
linklist = re.findall('"((http|ftp)s?://.*?)"',html)
print linklist
for link in linklist:
    print link[0]

Prompt: Print out all links on a page


from django import forms

class CampaignGeneralForm(forms.Form):

    TYPE_CHOICES = (
        ('', 'Select campaign type'),
        ('B', 'Bulk Message'),
        ('D', 'Dialogue'),
    )

    name = forms.CharField(label="Campaign name", max_length=100)
    type = forms.ChoiceField(label="Which kind of campaign would you like?",
                             widget=forms.Select(), choices=TYPE_CHOICES)

class CampaignConfigurationForm(forms.Form):

    COUNTRY_CHOICES = (
        ('.za', 'South Africa'),
    )

    CHANNEL_CHOICES = (
        ('ussd', 'USSD'),
    )

    # more than likely a many to many field, or something similair in the riak
    # world. Whom I kidding, this is probably just a modelform?
    countries = forms.MultipleChoiceField(label="Destinations",
                                          widget=forms.Select(),
                                          choices=COUNTRY_CHOICES)

    channels = forms.MultipleChoiceField(label="Channels",
                                         widget=forms.Select(),
                                         choices=CHANNEL_CHOICES)

    keyword = forms.CharField(label="Keyword", max_length=100)

class CampaignBulkMessageForm(forms.Form):
    message = forms.CharField(label="Bulk message text", widget=forms.Textarea)

Use dialogue terminology in menu

Use dialogue terminology in menu

Response:
from django import forms

class CampaignGeneralForm(forms.Form):

    TYPE_CHOICES = (
        ('', 'Select campaign type'),
        ('B', 'Bulk Message'),
        ('D', 'Dialogue'),
    )

    name = forms.CharField(label="Campaign name", max_length=100)
    type = forms.ChoiceField(label="Which kind of campaign would you like?",
                             widget=forms.Select(), choices=TYPE_CHOICES)

class CampaignConfigurationForm(forms.Form):

    COUNTRY_CHOICES = (
        ('.za', 'South Africa'),
    )

    CHANNEL_CHOICES = (
        ('ussd', 'USSD'),
    )

    # more than likely a many to many field, or something similair in the riak
    # world. Whom I kidding, this is probably just a modelform?
    countries = forms.MultipleChoiceField(label="Destinations",
                                          widget=forms.Select(),
                                          choices=COUNTRY_CHOICES)

    channels = forms.MultipleChoiceField(label="Channels",
                                         widget=forms.Select(),
                                         choices=CHANNEL_CHOICES)

    keyword = forms.CharField(label="Keyword", max_length=100)

class CampaignBulkMessageForm(forms.Form):
    message = forms.CharField(label="Bulk message text", widget=forms.Textarea)

Prompt:
Use dialogue terminology in menu

from django import forms

class CampaignGeneralForm(forms.Form):

    TYPE_CHOICES = (
        ('', 'Select campaign type'),
        ('B', 'Bulk Message'),
        ('C', 'Conversation'),
    )

    name = forms.CharField(label="Campaign name", max_length=100)
    type = forms.ChoiceField(label="Which kind of campaign would you like?",
                             widget=forms.Select(), choices=TYPE_CHOICES)

class CampaignConfigurationForm(forms.Form):

    COUNTRY_CHOICES = (
        ('.za', 'South Africa'),
    )

    CHANNEL_CHOICES = (
        ('ussd', 'USSD'),
    )

    # more than likely a many to many field, or something similair in the riak
    # world. Whom I kidding, this is probably just a modelform?
    countries = forms.MultipleChoiceField(label="Destinations",
                                          widget=forms.Select(),
                                          choices=COUNTRY_CHOICES)

    channels = forms.MultipleChoiceField(label="Channels",
                                         widget=forms.Select(),
                                         choices=CHANNEL_CHOICES)

    keyword = forms.CharField(label="Keyword", max_length=100)

class CampaignBulkMessageForm(forms.Form):
    message = forms.CharField(label="Bulk message text", widget=forms.Textarea)


import Xdmf
from Xdmf import *

if __name__ == '__main__':
    array = Xdmf.XdmfArray()
    array.SetNumberType(Xdmf.XDMF_INT64_TYPE)
    assert(array.GetNumberType() == Xdmf.XDMF_INT64_TYPE)
    array.SetShapeFromString("3 3")
    assert(array.GetShapeAsString() == "3 3")
    assert(array.GetNumberOfElements() == 9)
    toWrite = [0,1,2,3,4,500,5000,500000,1000000000000]
    i = 0;
    for element in toWrite:
        array.SetValueFromInt64(i,element)
        i += 1

    i=0
    for element in toWrite:
        assert(array.GetValueAsInt64(i) == element)
        i += 1

    assert (array.GetMaxAsInt64() == 1000000000000)
    assert (array.GetMinAsInt64() == 0)

ENH: Add Xdmf Python Test that writes values to an XdmfArray

Response:
import Xdmf
from Xdmf import *

if __name__ == '__main__':
    array = Xdmf.XdmfArray()
    array.SetNumberType(Xdmf.XDMF_INT64_TYPE)
    assert(array.GetNumberType() == Xdmf.XDMF_INT64_TYPE)
    array.SetShapeFromString("3 3")
    assert(array.GetShapeAsString() == "3 3")
    assert(array.GetNumberOfElements() == 9)
    toWrite = [0,1,2,3,4,500,5000,500000,1000000000000]
    i = 0;
    for element in toWrite:
        array.SetValueFromInt64(i,element)
        i += 1

    i=0
    for element in toWrite:
        assert(array.GetValueAsInt64(i) == element)
        i += 1

    assert (array.GetMaxAsInt64() == 1000000000000)
    assert (array.GetMinAsInt64() == 0)

Prompt: ENH: Add Xdmf Python Test that writes values to an XdmfArray


from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim

Remove double import of find contours.

Response:
from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim

Prompt:
BUG: Remove double import of find contours.

from .find_contours import find_contours
from ._regionprops import regionprops
from .find_contours import find_contours
from ._structural_similarity import ssim


from providers.popularity.provider import PopularityProvider
from utils.torrent_util import remove_bad_torrent_matches, torrent_to_movie

IDENTIFIER = "netflix"

class Provider(PopularityProvider):
    def get_popular(self):
        country = "se"
        url = f"https://www.finder.com/{country}/netflix-movies"
        data = self.parse_html(url, 'tbody td[data-title="Title"] b, tbody td[data-title="Year of release"]', cache=False)
        movies = [
            {
                "name": movie,
                "is_bad": False,
                "year": year,
            }
            for movie, year in zip(data[::2], data[1::2])
        ]

        return movies

Add provider for (Swedish) Netflix.

Add provider for (Swedish) Netflix.

Change "country" inside the provider for the movies available in a different country.

Response:
from providers.popularity.provider import PopularityProvider
from utils.torrent_util import remove_bad_torrent_matches, torrent_to_movie

IDENTIFIER = "netflix"

class Provider(PopularityProvider):
    def get_popular(self):
        country = "se"
        url = f"https://www.finder.com/{country}/netflix-movies"
        data = self.parse_html(url, 'tbody td[data-title="Title"] b, tbody td[data-title="Year of release"]', cache=False)
        movies = [
            {
                "name": movie,
                "is_bad": False,
                "year": year,
            }
            for movie, year in zip(data[::2], data[1::2])
        ]

        return movies

Prompt:
Add provider for (Swedish) Netflix.

Change "country" inside the provider for the movies available in a different country.


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0029_populate_run_modified_on'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='modified_on',
            field=models.DateTimeField(help_text='When this flow run was last updated', auto_now=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='flowrun',
            name='org',
            field=models.ForeignKey(related_name='runs', to='orgs.Org', db_index=False),
            preserve_default=True,
        ),
    ]

Make modified_on and org no longer be nullable

Response:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0029_populate_run_modified_on'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='modified_on',
            field=models.DateTimeField(help_text='When this flow run was last updated', auto_now=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='flowrun',
            name='org',
            field=models.ForeignKey(related_name='runs', to='orgs.Org', db_index=False),
            preserve_default=True,
        ),
    ]

Prompt: Make modified_on and org no longer be nullable


# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .disk import Disk

all = [
  '__version__', 'Disk'
]

Response:
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .disk import Disk

all = [
  '__version__', 'Disk'
]

Prompt:
[Disk] Allow Agent to properly pull version info
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .disk import Disk

__all__ = ['Disk']


"""Unit tests for events models."""
import datetime

from app.events.factories import EventFactory
from app.events.models import Event

def test_event_factory(db):  # noqa: D103
    # GIVEN an empty database
    assert Event.objects.count() == 0

    # WHEN saving a new event instance to the database
    EventFactory.create(title='five')

    # THEN it's there
    assert Event.objects.count() == 1

def test_event_has_all_the_attributes():  # noqa: D103
    # GIVEN an event
    e = EventFactory.build()

    # THEN it has …
    assert e.title
    assert e.date
    assert e.venue
    assert e.description
    assert e.fb_event_url

def test_event_has_slug(db):  # noqa: D103
    # GIVEN an event
    e = EventFactory.build(
        title='One Happy Family',
        date=datetime.date(2018, 1, 1),
        venue=None,
        )
    assert e.slug == ''

    # WHEN saving the event
    e.save()

    # THEN it gets a slug generated from its date and title
    assert e.slug == '2018-01-01-one-happy-family'

def test_event_slug_gets_updated_on_date_change(db):  # noqa: D103
    # GIVEN an event
    e = EventFactory.create(
        date=datetime.date(2018, 1, 1),
        venue=None,
        )

    # WHEN changing the date
    assert e.slug.startswith('2018-01-01')
    e.date = datetime.date(2018, 1, 2)
    e.save()

    # THEN the slug changes to reflect the new date
    assert e.slug.startswith('2018-01-02')

Response:
"""Unit tests for events models."""
import datetime

from app.events.factories import EventFactory
from app.events.models import Event

def test_event_factory(db):  # noqa: D103
    # GIVEN an empty database
    assert Event.objects.count() == 0

    # WHEN saving a new event instance to the database
    EventFactory.create(title='five')

    # THEN it's there
    assert Event.objects.count() == 1

def test_event_has_all_the_attributes():  # noqa: D103
    # GIVEN an event
    e = EventFactory.build()

    # THEN it has …
    assert e.title
    assert e.date
    assert e.venue
    assert e.description
    assert e.fb_event_url

def test_event_has_slug(db):  # noqa: D103
    # GIVEN an event
    e = EventFactory.build(
        title='One Happy Family',
        date=datetime.date(2018, 1, 1),
        venue=None,
        )
    assert e.slug == ''

    # WHEN saving the event
    e.save()

    # THEN it gets a slug generated from its date and title
    assert e.slug == '2018-01-01-one-happy-family'

def test_event_slug_gets_updated_on_date_change(db):  # noqa: D103
    # GIVEN an event
    e = EventFactory.create(
        date=datetime.date(2018, 1, 1),
        venue=None,
        )

    # WHEN changing the date
    assert e.slug.startswith('2018-01-01')
    e.date = datetime.date(2018, 1, 2)
    e.save()

    # THEN the slug changes to reflect the new date
    assert e.slug.startswith('2018-01-02')

Prompt:
Make sure slug gets updated on date change

"""Unit tests for events models."""
import datetime

from app.events.factories import EventFactory
from app.events.models import Event

def test_event_factory(db):  # noqa: D103
    # GIVEN an empty database
    assert Event.objects.count() == 0

    # WHEN saving a new event instance to the database
    EventFactory.create(title='five')

    # THEN it's there
    assert Event.objects.count() == 1

def test_event_has_all_the_attributes():  # noqa: D103
    # GIVEN an event
    e = EventFactory.build()

    # THEN it has …
    assert e.title
    assert e.date
    assert e.venue
    assert e.description
    assert e.fb_event_url

def test_event_has_slug(db):  # noqa: D103
    # GIVEN an event
    e = EventFactory.build(
        title='One Happy Family',
        date=datetime.date(2018, 1, 1),
        venue=None,
        )
    assert e.slug == ''

    # WHEN saving the event
    e.save()

    # THEN it gets a slug generated from its date and title
    assert e.slug == '2018-01-01-one-happy-family'


import pytest

import salt.modules.influxdbmod as influx_mod
import salt.states.influxdb_continuous_query as influx
from tests.support.mock import create_autospec, patch

@pytest.fixture
def configure_loader_modules():
    return {influx: {"__salt__": {}, "__opts__": {"test": False}}}

@pytest.mark.xfail
@pytest.mark.parametrize(
    "expected_kwargs",
    (
        {},
        {"something": "extra"},
        {"something": "extra", "even": "more"},
        {"something": "extra", "still": "more and more and more", "and": "more"},
        {
            "something": "extra",
            "what": "in tarnation",
            "do": "you want",
            "to": "add here?",
        },
    ),
)
def test_when_present_is_called_it_should_pass_client_args_to_create_module(
    expected_kwargs,
):
    influx_module = create_autospec(influx_mod)
    influx_module.continuous_query_exists.return_value = False
    with patch.dict(
        influx.__salt__,
        {
            "influxdb.continuous_query_exists": influx_module.continuous_query_exists,
            "influxdb.create_continuous_query": influx_module.create_continuous_query,
        },
    ):
        influx.present(
            name="foo",
            database="fnord",
            query="fnord",
            resample_time="whatever",
            coverage_period="fnord",
            **expected_kwargs
        )

    actual_kwargs = influx_module.create_continuous_query.mock_calls[0].kwargs

    assert actual_kwargs == expected_kwargs

Add tests for influxdb create_continuous_query

Currently marked as xfail, since we'll pull the existing changes into
here.

Response:
import pytest

import salt.modules.influxdbmod as influx_mod
import salt.states.influxdb_continuous_query as influx
from tests.support.mock import create_autospec, patch

@pytest.fixture
def configure_loader_modules():
    return {influx: {"__salt__": {}, "__opts__": {"test": False}}}

@pytest.mark.xfail
@pytest.mark.parametrize(
    "expected_kwargs",
    (
        {},
        {"something": "extra"},
        {"something": "extra", "even": "more"},
        {"something": "extra", "still": "more and more and more", "and": "more"},
        {
            "something": "extra",
            "what": "in tarnation",
            "do": "you want",
            "to": "add here?",
        },
    ),
)
def test_when_present_is_called_it_should_pass_client_args_to_create_module(
    expected_kwargs,
):
    influx_module = create_autospec(influx_mod)
    influx_module.continuous_query_exists.return_value = False
    with patch.dict(
        influx.__salt__,
        {
            "influxdb.continuous_query_exists": influx_module.continuous_query_exists,
            "influxdb.create_continuous_query": influx_module.create_continuous_query,
        },
    ):
        influx.present(
            name="foo",
            database="fnord",
            query="fnord",
            resample_time="whatever",
            coverage_period="fnord",
            **expected_kwargs
        )

    actual_kwargs = influx_module.create_continuous_query.mock_calls[0].kwargs

    assert actual_kwargs == expected_kwargs

Prompt:
Add tests for influxdb create_continuous_query

Currently marked as xfail, since we'll pull the existing changes into
here.


# Gevent needed for sockets
from gevent import monkey
monkey.patch_all()

# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3

# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])

import nltk
nltk.download("punkt")

# DB
db = boto3.resource("dynamodb",
                    region_name=app.config["DYNAMO_REGION"],
                    endpoint_url=app.config["DYNAMO_DATABASE_URI"])
s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"])

from app import models
models.initialize()

# Initialize the controllers
from app import controllers

# Initialize app w/SocketIO
socketio.init_app(app)

# HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404

Fix stupid nltk data download thing

Fix stupid nltk data download thing

Response:
# Gevent needed for sockets
from gevent import monkey
monkey.patch_all()

# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3

# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])

import nltk
nltk.download("punkt")

# DB
db = boto3.resource("dynamodb",
                    region_name=app.config["DYNAMO_REGION"],
                    endpoint_url=app.config["DYNAMO_DATABASE_URI"])
s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"])

from app import models
models.initialize()

# Initialize the controllers
from app import controllers

# Initialize app w/SocketIO
socketio.init_app(app)

# HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404

Prompt:
Fix stupid nltk data download thing

# Gevent needed for sockets
from gevent import monkey
monkey.patch_all()

# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3

# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])

import nltk
try:
    nltk.data.find('tokenizers/punkt')
except LookupError:
    nltk.download("punkt")

# DB
db = boto3.resource("dynamodb",
                    region_name=app.config["DYNAMO_REGION"],
                    endpoint_url=app.config["DYNAMO_DATABASE_URI"])
s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"])

from app import models
models.initialize()

# Initialize the controllers
from app import controllers

# Initialize app w/SocketIO
socketio.init_app(app)

# HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404


import re
try:
    import urllib.request as urllib
except:
    import urllib # Python 2

def title(source):
    gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
    link = 'https://gfycat.com/cajax/get/' + gfyId
    respond = urllib.urlopen(link).read().decode("utf8")
    username = re.findall(r'\"userName\":\"(.+?)\",' ,respond)[0]
    return username if username != "anonymous" else "gfycat " + gfyId

def redirect(source):
    gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
    respond = urllib.urlopen('https://gfycat.com/cajax/get/' + gfyId).read().decode("utf8")
    webmurl = re.findall(r'\"webmUrl\":\"(.+?)\",' ,respond)[0]
    # delete escape characters
    webmurl = webmurl.replace("\\","")
    # for some reason we can not connect via https
    webmurl = webmurl.replace("https", "http")
    return webmurl
same_filename = True

Response:
import re
try:
    import urllib.request as urllib
except:
    import urllib # Python 2

def title(source):
    gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
    link = 'https://gfycat.com/cajax/get/' + gfyId
    respond = urllib.urlopen(link).read().decode("utf8")
    username = re.findall(r'\"userName\":\"(.+?)\",' ,respond)[0]
    return username if username != "anonymous" else "gfycat " + gfyId

def redirect(source):
    gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
    respond = urllib.urlopen('https://gfycat.com/cajax/get/' + gfyId).read().decode("utf8")
    webmurl = re.findall(r'\"webmUrl\":\"(.+?)\",' ,respond)[0]
    # delete escape characters
    webmurl = webmurl.replace("\\","")
    # for some reason we can not connect via https
    webmurl = webmurl.replace("https", "http")
    return webmurl
same_filename = True

Prompt:
Update gfycat plugin for python3 support

import re
try:
    import urllib.request as urllib
except:
    import urllib # Python 2

def title(source):
    gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
    link = 'https://gfycat.com/cajax/get/' + gfyId
    respond = urllib.urlopen(link).read()
    username = re.findall(r'\"userName\":\"(.+?)\",' ,respond)[0]
    return username if username != "anonymous" else "gfycat " + gfyId

def redirect(source):
    gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
    respond = urllib.urlopen('https://gfycat.com/cajax/get/' + gfyId).read()
    webmurl = re.findall(r'\"webmUrl\":\"(.+?)\",' ,respond)[0]
    # delete escape characters
    webmurl = webmurl.replace("\\","")
    # for some reason we can not connect via https
    webmurl = webmurl.replace("https", "http")
    return webmurl
same_filename = True


from .base_executor import CompiledExecutor

class Executor(CompiledExecutor):
    ext = '.i'
    name = 'ICK'
    command = 'ick'
    test_program = '''\
        PLEASE DO ,1 <- #1
        DO .4 <- #0
        DO .5 <- #0
        DO COME FROM (30)
        DO WRITE IN ,1
        DO .1 <- ,1SUB#1
        DO (10) NEXT
        PLEASE GIVE UP
(20)    PLEASE RESUME '?.1$#256'~'#256$#256'
(10)    DO (20) NEXT
        DO FORGET #1
        PLEASE DO .2 <- .4
        DO (1000) NEXT
        DO .4 <- .3~#255
        PLEASE DO .3 <- !3~#15'$!3~#240'
        DO .3 <- !3~#15'$!3~#240'
        DO .2 <- !3~#15'$!3~#240'
        PLEASE DO .1 <- .5
        DO (1010) NEXT
        DO .5 <- .2
        DO ,1SUB#1 <- .3
(30)    PLEASE READ OUT ,1
'''

    def get_compile_args(self):
        flags = [self.get_command(), '-O', self._code]
        if self.problem == self.test_name:
            # Do not fail self-test to random compiler bug.
            flags.insert(1, '-b')
        return flags

Response:
from .base_executor import CompiledExecutor

class Executor(CompiledExecutor):
    ext = '.i'
    name = 'ICK'
    command = 'ick'
    test_program = '''\
        PLEASE DO ,1 <- #1
        DO .4 <- #0
        DO .5 <- #0
        DO COME FROM (30)
        DO WRITE IN ,1
        DO .1 <- ,1SUB#1
        DO (10) NEXT
        PLEASE GIVE UP
(20)    PLEASE RESUME '?.1$#256'~'#256$#256'
(10)    DO (20) NEXT
        DO FORGET #1
        PLEASE DO .2 <- .4
        DO (1000) NEXT
        DO .4 <- .3~#255
        PLEASE DO .3 <- !3~#15'$!3~#240'
        DO .3 <- !3~#15'$!3~#240'
        DO .2 <- !3~#15'$!3~#240'
        PLEASE DO .1 <- .5
        DO (1010) NEXT
        DO .5 <- .2
        DO ,1SUB#1 <- .3
(30)    PLEASE READ OUT ,1
'''

    def get_compile_args(self):
        flags = [self.get_command(), '-O', self._code]
        if self.problem == self.test_name:
            # Do not fail self-test to random compiler bug.
            flags.insert(1, '-b')
        return flags

Prompt:
Make Intercal executor not fail to start at times.

from .base_executor import CompiledExecutor

class Executor(CompiledExecutor):
    ext = '.i'
    name = 'ICK'
    command = 'ick'
    test_program = '''\
        PLEASE DO ,1 <- #1
        DO .4 <- #0
        DO .5 <- #0
        DO COME FROM (30)
        DO WRITE IN ,1
        DO .1 <- ,1SUB#1
        DO (10) NEXT
        PLEASE GIVE UP
(20)    PLEASE RESUME '?.1$#256'~'#256$#256'
(10)    DO (20) NEXT
        DO FORGET #1
        PLEASE DO .2 <- .4
        DO (1000) NEXT
        DO .4 <- .3~#255
        PLEASE DO .3 <- !3~#15'$!3~#240'
        DO .3 <- !3~#15'$!3~#240'
        DO .2 <- !3~#15'$!3~#240'
        PLEASE DO .1 <- .5
        DO (1010) NEXT
        DO .5 <- .2
        DO ,1SUB#1 <- .3
(30)    PLEASE READ OUT ,1
'''

    def get_compile_args(self):
        return [self.get_command(), '-O', self._code]


from uliweb.core.template import BaseBlockNode
from uliweb import functions

class PermissionNode(BaseBlockNode):
    def __init__(self, name='', content=None):
        super(PermissionNode, self).__init__(name, content)
        self.nodes = ['if functions.has_permission(request.user, %s):\n' % self.name]

    def end(self):
        self.nodes.append('pass\n')

class RoleNode(PermissionNode):
    def __init__(self, name='', content=None):
        super(RoleNode, self).__init__(name, content)
        self.nodes = ['if functions.has_role(request.user, %s):\n' % self.name]

Response:
from uliweb.core.template import BaseBlockNode
from uliweb import functions

class PermissionNode(BaseBlockNode):
    def __init__(self, name='', content=None):
        super(PermissionNode, self).__init__(name, content)
        self.nodes = ['if functions.has_permission(request.user, %s):\n' % self.name]

    def end(self):
        self.nodes.append('pass\n')

class RoleNode(PermissionNode):
    def __init__(self, name='', content=None):
        super(RoleNode, self).__init__(name, content)
        self.nodes = ['if functions.has_role(request.user, %s):\n' % self.name]

Prompt:
Change role and permission tag parameter format, no need ""

from uliweb.core.template import BaseBlockNode
from uliweb import functions

class PermissionNode(BaseBlockNode):
    def __init__(self, name='', content=None):
        super(PermissionNode, self).__init__(name, content)
        self.nodes = ['if functions.has_permission(request.user, "%s"):\n' % self.name]

    def end(self):
        self.nodes.append('pass\n')

class RoleNode(PermissionNode):
    def __init__(self, name='', content=None):
        super(RoleNode, self).__init__(name, content)
        self.nodes = ['if functions.has_role(request.user, "%s"):\n' % self.name]


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

bind = '127.0.0.1:8002'
workers = 6
proc_name = 'lastuser'

Use a different port for lastuser

Use a different port for lastuser

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

bind = '127.0.0.1:8002'
workers = 6
proc_name = 'lastuser'

Prompt:
Use a different port for lastuser

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

bind = '127.0.0.1:8001'
workers = 6
proc_name = 'lastuser'


#!/usr/bin/env python

import pywapi

weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')

print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York."

print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.")

print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")

Fix error in example script

Fix error in example script

Response:
#!/usr/bin/env python

import pywapi

weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')

print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York."

print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.")

print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")

Prompt:
Fix error in example script
#!/usr/bin/env python

import pywapi

weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')

print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n"

print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.")

print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")