IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1)

Add some needed IRC numerics

Add some needed IRC numerics

Response:
<INSERT> "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", <INSERT_END> <REPLACE_OLD> chr(1) <REPLACE_NEW> chr(1)
 <REPLACE_END> <|endoftext|> IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1)

Prompt:
Add some needed IRC numerics

IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1)


import itertools

from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation

@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
    yield element.id, copy_named_element(element)
    for feature in itertools.chain(
        element.ownedAttribute,
        element.ownedOperation,
    ):
        yield from copy(feature)

@copy.register
def copy_enumeration(element: Enumeration):
    yield element.id, copy_named_element(element)
    for literal in element.ownedLiteral:
        yield from copy(literal)

@copy.register
def copy_operation(element: Operation):
    yield element.id, copy_named_element(element)
    for feature in element.ownedParameter:
        yield from copy(feature)

@copy.register
def copy_association(element: Association):
    yield element.id, copy_named_element(element)
    for end in element.memberEnd:
        yield from copy(end)

Response:
<INSERT> Enumeration, <INSERT_END> <INSERT> copy_enumeration(element: Enumeration):
    yield element.id, copy_named_element(element)
    for literal in element.ownedLiteral:
        yield from copy(literal)

@copy.register
def <INSERT_END> <|endoftext|> import itertools

from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation

@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
    yield element.id, copy_named_element(element)
    for feature in itertools.chain(
        element.ownedAttribute,
        element.ownedOperation,
    ):
        yield from copy(feature)

@copy.register
def copy_enumeration(element: Enumeration):
    yield element.id, copy_named_element(element)
    for literal in element.ownedLiteral:
        yield from copy(literal)

@copy.register
def copy_operation(element: Operation):
    yield element.id, copy_named_element(element)
    for feature in element.ownedParameter:
        yield from copy(feature)

@copy.register
def copy_association(element: Association):
    yield element.id, copy_named_element(element)
    for end in element.memberEnd:
        yield from copy(end)

Prompt:
Copy enumeration literals when pasting an Enumeration

Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>

import itertools

from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Interface, Operation

@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
    yield element.id, copy_named_element(element)
    for feature in itertools.chain(
        element.ownedAttribute,
        element.ownedOperation,
    ):
        yield from copy(feature)

@copy.register
def copy_operation(element: Operation):
    yield element.id, copy_named_element(element)
    for feature in element.ownedParameter:
        yield from copy(feature)

@copy.register
def copy_association(element: Association):
    yield element.id, copy_named_element(element)
    for end in element.memberEnd:
        yield from copy(end)


from __future__ import absolute_import

from celery import Celery

app = Celery('aubergine')
app.config_from_object('aubergine.settings.celeryconfig')
app.autodiscover_tasks(['aubergine'], related_name='tasks')

# For message signing
# app.setup_security()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

@app.task()
def tadd(x, y):
    return x + y

@app.task()
def tsum(numbers):
    return sum(numbers)

Disable message signing for now

Disable message signing for now

Response:
<REPLACE_OLD> related_name='tasks')
app.setup_security()

@app.task(bind=True)
def <REPLACE_NEW> related_name='tasks')

# For message signing
# app.setup_security()

@app.task(bind=True)
def <REPLACE_END> <|endoftext|> from __future__ import absolute_import

from celery import Celery

app = Celery('aubergine')
app.config_from_object('aubergine.settings.celeryconfig')
app.autodiscover_tasks(['aubergine'], related_name='tasks')

# For message signing
# app.setup_security()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

@app.task()
def tadd(x, y):
    return x + y

@app.task()
def tsum(numbers):
    return sum(numbers)

Prompt:
Disable message signing for now

from __future__ import absolute_import

from celery import Celery

app = Celery('aubergine')
app.config_from_object('aubergine.settings.celeryconfig')
app.autodiscover_tasks(['aubergine'], related_name='tasks')
app.setup_security()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

@app.task()
def tadd(x, y):
    return x + y

@app.task()
def tsum(numbers):
    return sum(numbers)


from rest_framework import serializers
from .models import Runner, RunnerVersion

class RunnerVersionSerializer(serializers.ModelSerializer):
    class Meta(object):
        model = RunnerVersion
        fields = ('version', 'url')

class RunnerSerializer(serializers.ModelSerializer):
    versions = RunnerVersionSerializer(many=True)

    class Meta(object):
        model = Runner
        fields = ('name', 'slug', 'icon', 'website', 'versions')

Response:
<REPLACE_OLD> 'path')

class <REPLACE_NEW> 'url')

class <REPLACE_END> <|endoftext|> from rest_framework import serializers
from .models import Runner, RunnerVersion

class RunnerVersionSerializer(serializers.ModelSerializer):
    class Meta(object):
        model = RunnerVersion
        fields = ('version', 'url')

class RunnerSerializer(serializers.ModelSerializer):
    versions = RunnerVersionSerializer(many=True)

    class Meta(object):
        model = Runner
        fields = ('name', 'slug', 'icon', 'website', 'versions')

Prompt:
Fix url field for runner version serializer

from rest_framework import serializers
from .models import Runner, RunnerVersion

class RunnerVersionSerializer(serializers.ModelSerializer):
    class Meta(object):
        model = RunnerVersion
        fields = ('version', 'path')

class RunnerSerializer(serializers.ModelSerializer):
    versions = RunnerVersionSerializer(many=True)

    class Meta(object):
        model = Runner
        fields = ('name', 'slug', 'icon', 'website', 'versions')


import base64
import json
import Queue
import time
import logging

from boto import sns
from boto import sqs
from boto.sqs.message import Message, RawMessage

from nanomon.utils import yaml_includes
from nanomon.message import NanoMessage
from nanomon.queue import QueueWorker
from nanomon.queue.backends.sns_sqs import SQSQueue, SNSTopic

logger = logging.getLogger(__name__)

class YamlNodeBackend(object):
    def __init__(self, path):
        self.path = path

    def get_nodes(self):
        logger.debug("Loading node config from %s" % (self.path))
        return yaml_includes.load_config(self.path)

class Scheduler(QueueWorker):
    def __init__(self, node_backend, topic, queue):
        self.node_backend = node_backend
        super(Scheduler, self).__init__(topic, queue)

    def run(self, sleep=300):
        while True:
            start = time.time()
            sleep = float(sleep)
            nodes = self.node_backend.get_nodes()
            for node in nodes:
                task = json.dumps(node)
                logger.debug("Sending task for node '%s'." % (node['name']))
                self.send_task(task)
            real_sleep = sleep - (time.time() - start)
            if real_sleep <= 0:
                continue
            logger.debug("Sleeping for %.02f." % (real_sleep))
            time.sleep(real_sleep)

Update for new node definition syntax

Update for new node definition syntax

Response:
<REPLACE_OLD> node, settings <REPLACE_NEW> node <REPLACE_END> <REPLACE_OLD> nodes.iteritems():
 <REPLACE_NEW> nodes:
 <REPLACE_END> <REPLACE_OLD> json.dumps({node: settings})
 <REPLACE_NEW> json.dumps(node)
 <REPLACE_END> <REPLACE_OLD> (node))
 <REPLACE_NEW> (node['name']))
 <REPLACE_END> <|endoftext|> import base64
import json
import Queue
import time
import logging

from boto import sns
from boto import sqs
from boto.sqs.message import Message, RawMessage

from nanomon.utils import yaml_includes
from nanomon.message import NanoMessage
from nanomon.queue import QueueWorker
from nanomon.queue.backends.sns_sqs import SQSQueue, SNSTopic

logger = logging.getLogger(__name__)

class YamlNodeBackend(object):
    def __init__(self, path):
        self.path = path

    def get_nodes(self):
        logger.debug("Loading node config from %s" % (self.path))
        return yaml_includes.load_config(self.path)

class Scheduler(QueueWorker):
    def __init__(self, node_backend, topic, queue):
        self.node_backend = node_backend
        super(Scheduler, self).__init__(topic, queue)

    def run(self, sleep=300):
        while True:
            start = time.time()
            sleep = float(sleep)
            nodes = self.node_backend.get_nodes()
            for node in nodes:
                task = json.dumps(node)
                logger.debug("Sending task for node '%s'." % (node['name']))
                self.send_task(task)
            real_sleep = sleep - (time.time() - start)
            if real_sleep <= 0:
                continue
            logger.debug("Sleeping for %.02f." % (real_sleep))
            time.sleep(real_sleep)

Prompt:
Update for new node definition syntax

import base64
import json
import Queue
import time
import logging

from boto import sns
from boto import sqs
from boto.sqs.message import Message, RawMessage

from nanomon.utils import yaml_includes
from nanomon.message import NanoMessage
from nanomon.queue import QueueWorker
from nanomon.queue.backends.sns_sqs import SQSQueue, SNSTopic

logger = logging.getLogger(__name__)

class YamlNodeBackend(object):
    def __init__(self, path):
        self.path = path

    def get_nodes(self):
        logger.debug("Loading node config from %s" % (self.path))
        return yaml_includes.load_config(self.path)

class Scheduler(QueueWorker):
    def __init__(self, node_backend, topic, queue):
        self.node_backend = node_backend
        super(Scheduler, self).__init__(topic, queue)

    def run(self, sleep=300):
        while True:
            start = time.time()
            sleep = float(sleep)
            nodes = self.node_backend.get_nodes()
            for node, settings in nodes.iteritems():
                task = json.dumps({node: settings})
                logger.debug("Sending task for node '%s'." % (node))
                self.send_task(task)
            real_sleep = sleep - (time.time() - start)
            if real_sleep <= 0:
                continue
            logger.debug("Sleeping for %.02f." % (real_sleep))
            time.sleep(real_sleep)


import os
# Generates validation/input definitions as if they were created by splunk for tests
class MockDefinitions(object):
    def __init__(self, session_key=None):
        self.session_key = session_key if session_key is not None else '123456789'

    @property
    def metadata(self):
        host = os.getenv('SPLUNK_API_HOST', '127.0.0.1')
        return {'server_uri': 'https://{host}:8089/'.format(host=host), 'session_key': self.session_key,
                'name': 'amp4e_events_test_input'}

Change mock to be env dependant

Change mock to be env dependant

Response:
<REPLACE_OLD> # <REPLACE_NEW> import os
# <REPLACE_END> <REPLACE_OLD> 'localhost')
        port = os.getenv('SPLUNK_API_PORT', 8089),
 <REPLACE_NEW> '127.0.0.1')
 <REPLACE_END> <REPLACE_OLD> 'https://{host}:{port}/', <REPLACE_NEW> 'https://{host}:8089/'.format(host=host), <REPLACE_END> <|endoftext|> import os
# Generates validation/input definitions as if they were created by splunk for tests
class MockDefinitions(object):
    def __init__(self, session_key=None):
        self.session_key = session_key if session_key is not None else '123456789'

    @property
    def metadata(self):
        host = os.getenv('SPLUNK_API_HOST', '127.0.0.1')
        return {'server_uri': 'https://{host}:8089/'.format(host=host), 'session_key': self.session_key,
                'name': 'amp4e_events_test_input'}

Prompt:
Change mock to be env dependant

# Generates validation/input definitions as if they were created by splunk for tests
class MockDefinitions(object):
    def __init__(self, session_key=None):
        self.session_key = session_key if session_key is not None else '123456789'

    @property
    def metadata(self):
        host = os.getenv('SPLUNK_API_HOST', 'localhost')
        port = os.getenv('SPLUNK_API_PORT', 8089),
        return {'server_uri': 'https://{host}:{port}/', 'session_key': self.session_key,
                'name': 'amp4e_events_test_input'}


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

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

from django.conf.urls import url
from django.contrib.auth.decorators import login_required

from .views import GuidesView

urlpatterns = [
    url(r'^$', login_required(GuidesView.as_view()), name='index'),
]

Fix patterns for Django > 1.10

Response:
<DELETE> patterns, <DELETE_END> <REPLACE_OLD> patterns('',
 <REPLACE_NEW> [
 <REPLACE_END> <REPLACE_OLD> name='index'))
 <REPLACE_NEW> name='index'),
]
 <REPLACE_END> <|endoftext|> # vim: tabstop=4 shiftwidth=4 softtabstop=4

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

from django.conf.urls import url
from django.contrib.auth.decorators import login_required

from .views import GuidesView

urlpatterns = [
    url(r'^$', login_required(GuidesView.as_view()), name='index'),
]

Prompt:
Fix patterns for Django > 1.10

Pike requires Django 1.11 so fix the template pattern import which was
not compatible with that version. This fixes:

File
"/srv/www/openstack-dashboard/openstack_dashboard/dashboards/help/guides/\
    urls.py", line 15, in <module>
from django.conf.urls import patterns, url
ImportError: cannot import name patterns

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

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

from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required

from .views import GuidesView

urlpatterns = patterns('',
    url(r'^$', login_required(GuidesView.as_view()), name='index'))


from imhotep.tools import Tool
from collections import defaultdict
import re

class JSL(Tool):
    regex = re.compile(
        r'^(?P<type>[WE]) '
        r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')

    def invoke(self, dirname, filenames=set(), linter_configs=set()):
        retval = defaultdict(lambda: defaultdict(list))
        if len(filenames) == 0:
            cmd = 'find %s -name "*.js" | xargs jsl' % dirname
        else:
            js_files = []
            for filename in filenames:
                if '.js' in filename:
                    js_files.append("%s/%s" % (dirname, filename))
            cmd = 'jsl %s' % ' '.join(js_files)
        output = self.executor(cmd)
        for line in output.split('\n'):
            match = self.regex.search(line)
            if match is None:
                continue
            message = '%s: %s' % (match.group('type'), match.group('message'))
            filename = match.group('filename')[len(dirname) + 1:]
            retval[filename][match.group('line_number')].append(message)
        return retval

Response:
<REPLACE_OLD> filenames=set()):
 <REPLACE_NEW> filenames=set(), linter_configs=set()):
 <REPLACE_END> <|endoftext|> from imhotep.tools import Tool
from collections import defaultdict
import re

class JSL(Tool):
    regex = re.compile(
        r'^(?P<type>[WE]) '
        r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')

    def invoke(self, dirname, filenames=set(), linter_configs=set()):
        retval = defaultdict(lambda: defaultdict(list))
        if len(filenames) == 0:
            cmd = 'find %s -name "*.js" | xargs jsl' % dirname
        else:
            js_files = []
            for filename in filenames:
                if '.js' in filename:
                    js_files.append("%s/%s" % (dirname, filename))
            cmd = 'jsl %s' % ' '.join(js_files)
        output = self.executor(cmd)
        for line in output.split('\n'):
            match = self.regex.search(line)
            if match is None:
                continue
            message = '%s: %s' % (match.group('type'), match.group('message'))
            filename = match.group('filename')[len(dirname) + 1:]
            retval[filename][match.group('line_number')].append(message)
        return retval

Prompt:
Update for api change with linter_configs.

from imhotep.tools import Tool
from collections import defaultdict
import re

class JSL(Tool):
    regex = re.compile(
        r'^(?P<type>[WE]) '
        r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')

    def invoke(self, dirname, filenames=set()):
        retval = defaultdict(lambda: defaultdict(list))
        if len(filenames) == 0:
            cmd = 'find %s -name "*.js" | xargs jsl' % dirname
        else:
            js_files = []
            for filename in filenames:
                if '.js' in filename:
                    js_files.append("%s/%s" % (dirname, filename))
            cmd = 'jsl %s' % ' '.join(js_files)
        output = self.executor(cmd)
        for line in output.split('\n'):
            match = self.regex.search(line)
            if match is None:
                continue
            message = '%s: %s' % (match.group('type'), match.group('message'))
            filename = match.group('filename')[len(dirname) + 1:]
            retval[filename][match.group('line_number')].append(message)
        return retval


# Copyright (C) 2001,2002 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)

"""Various types of useful iterators and generators.
"""

import sys

try:
    from email._compat22 import body_line_iterator, typed_subpart_iterator
except SyntaxError:
    # Python 2.1 doesn't have generators
    from email._compat21 import body_line_iterator, typed_subpart_iterator

def _structure(msg, fp=None, level=0):
    """A handy debugging aid"""
    if fp is None:
        fp = sys.stdout
    tab = ' ' * (level * 4)
    print >> fp, tab + msg.get_content_type()
    if msg.is_multipart():
        for subpart in msg.get_payload():
            _structure(subpart, fp, level+1)

Swap fp and level arguments.

Response:
<REPLACE_OLD> level=0, fp=None):
 <REPLACE_NEW> fp=None, level=0):
 <REPLACE_END> <REPLACE_OLD> level+1, fp)
 <REPLACE_NEW> fp, level+1)
 <REPLACE_END> <|endoftext|> # Copyright (C) 2001,2002 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)

"""Various types of useful iterators and generators.
"""

import sys

try:
    from email._compat22 import body_line_iterator, typed_subpart_iterator
except SyntaxError:
    # Python 2.1 doesn't have generators
    from email._compat21 import body_line_iterator, typed_subpart_iterator

def _structure(msg, fp=None, level=0):
    """A handy debugging aid"""
    if fp is None:
        fp = sys.stdout
    tab = ' ' * (level * 4)
    print >> fp, tab + msg.get_content_type()
    if msg.is_multipart():
        for subpart in msg.get_payload():
            _structure(subpart, fp, level+1)

Prompt:
_structure(): Swap fp and level arguments.

# Copyright (C) 2001,2002 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)

"""Various types of useful iterators and generators.
"""

import sys

try:
    from email._compat22 import body_line_iterator, typed_subpart_iterator
except SyntaxError:
    # Python 2.1 doesn't have generators
    from email._compat21 import body_line_iterator, typed_subpart_iterator

def _structure(msg, level=0, fp=None):
    """A handy debugging aid"""
    if fp is None:
        fp = sys.stdout
    tab = ' ' * (level * 4)
    print >> fp, tab + msg.get_content_type()
    if msg.is_multipart():
        for subpart in msg.get_payload():
            _structure(subpart, level+1, fp)


from setuptools import setup,find_packages

setup (
  name = 'pymatgen',
  version = '1.0.3',
  packages = find_packages(),

  # Declare your packages' dependencies here, for eg:

  install_requires = ['numpy','scipy','matplotlib','PyCIFRW'],

  author = 'Shyue Ping Ong, Anubhav Jain, Michael Kocher, Dan Gunter',
  author_email = 'shyue@mit.edu, anubhavj@mit.edu, mpkocher@lbnl.gov, dkgunter@lbl.gov',

  summary = 'The Materials Project Python Library',
  url = 'www.materialsproject.org',
  license = '',
  long_description= 'pymatgen is a Python library for the Materials Project. It includes core structure definition and utilities, electronic structure objects, and convenient IO from VASP and CIF files.',

  # could also include long_description, download_url, classifiers, etc.
)

Response:
<REPLACE_OLD> '1.0.2',
 <REPLACE_NEW> '1.0.3',
 <REPLACE_END> <|endoftext|> from setuptools import setup,find_packages

setup (
  name = 'pymatgen',
  version = '1.0.3',
  packages = find_packages(),

  # Declare your packages' dependencies here, for eg:

  install_requires = ['numpy','scipy','matplotlib','PyCIFRW'],

  author = 'Shyue Ping Ong, Anubhav Jain, Michael Kocher, Dan Gunter',
  author_email = 'shyue@mit.edu, anubhavj@mit.edu, mpkocher@lbnl.gov, dkgunter@lbl.gov',

  summary = 'The Materials Project Python Library',
  url = 'www.materialsproject.org',
  license = '',
  long_description= 'pymatgen is a Python library for the Materials Project. It includes core structure definition and utilities, electronic structure objects, and convenient IO from VASP and CIF files.',

  # could also include long_description, download_url, classifiers, etc.
)

Prompt:
Update to v1.0.3 given all the bug fixes.

Former-commit-id: 0aebb52391a2dea2aabf08879335df01775d02ab [formerly 65ccbe5c10f2c1b54e1736caf7d8d88c7345610f]
Former-commit-id: 1e823ba824b20ed7641ff7360c6b50184562b3bd
from setuptools import setup,find_packages

setup (
  name = 'pymatgen',
  version = '1.0.2',
  packages = find_packages(),

  # Declare your packages' dependencies here, for eg:

  install_requires = ['numpy','scipy','matplotlib','PyCIFRW'],

  author = 'Shyue Ping Ong, Anubhav Jain, Michael Kocher, Dan Gunter',
  author_email = 'shyue@mit.edu, anubhavj@mit.edu, mpkocher@lbnl.gov, dkgunter@lbl.gov',

  summary = 'The Materials Project Python Library',
  url = 'www.materialsproject.org',
  license = '',
  long_description= 'pymatgen is a Python library for the Materials Project. It includes core structure definition and utilities, electronic structure objects, and convenient IO from VASP and CIF files.',

  # could also include long_description, download_url, classifiers, etc.
)


from ckan.plugins import toolkit as tk
import model

_ = tk._

def service_permission_application_create(context, data_dict):
    tk.check_access('service_permission_application_create', context, data_dict)

    errors = {}
    error_summary = {}

    organization = data_dict.get('organization')
    if organization is None:
        errors['organization'] = _('Missing value')
    vat_id = data_dict.get('vat_id')
    if vat_id is None:
        errors['vat_id'] = _('Missing value')
    contact_person_name = data_dict.get('contact_person_name')
    if contact_person_name is None:
        errors['contact_person_name'] = _('Missing value')
    contact_person_email = data_dict.get('contact_person_email')
    if contact_person_email is None:
        errors['contact_person_email'] = _('Missing value')
    ip_address_list = data_dict.get('ip_address_list')
    if ip_address_list is None:
        errors['ip_address_list'] = _('Missing value')
    subsystem_code = data_dict.get('subsystem_code')
    if subsystem_code is None:
        errors['subsystem_code'] = _('Missing value')
    api_id = data_dict.get('api_id')
    if api_id is None:
        errors['api_id'] = _('Missing value')

    if errors:
        raise tk.ValidationError(errors)

    request_description = data_dict.get('api_id')

    model.ApplyPermission.create(organization=organization, vat_id=vat_id,
                          contact_person_name=contact_person_name,
                          contact_person_email=contact_person_email,
                          ip_address_list=ip_address_list,
                          subsystem_code=subsystem_code,
                          api_id=api_id,
                          request_description=request_description)

Response:
<REPLACE_OLD> model
import ckan.model as ckan_model

def <REPLACE_NEW> model

_ = tk._

def <REPLACE_END> <INSERT> errors = {}
    error_summary = {}

    <INSERT_END> <INSERT> if organization is None:
        errors['organization'] = _('Missing value')
    <INSERT_END> <INSERT> if vat_id is None:
        errors['vat_id'] = _('Missing value')
    <INSERT_END> <INSERT> if contact_person_name is None:
        errors['contact_person_name'] = _('Missing value')
    <INSERT_END> <INSERT> if contact_person_email is None:
        errors['contact_person_email'] = _('Missing value')
    <INSERT_END> <INSERT> if ip_address_list is None:
        errors['ip_address_list'] = _('Missing value')
    <INSERT_END> <REPLACE_OLD> data_dict.get('subsystem_code')

 <REPLACE_NEW> data_dict.get('subsystem_code')
    if subsystem_code is None:
        errors['subsystem_code'] = _('Missing value')
 <REPLACE_END> <INSERT> if api_id is None:
        errors['api_id'] = _('Missing value')

    if errors:
        raise tk.ValidationError(errors)

    <INSERT_END> <REPLACE_OLD> data_dict.get('api_id')

 <REPLACE_NEW> data_dict.get('api_id')

 <REPLACE_END> <|endoftext|> from ckan.plugins import toolkit as tk
import model

_ = tk._

def service_permission_application_create(context, data_dict):
    tk.check_access('service_permission_application_create', context, data_dict)

    errors = {}
    error_summary = {}

    organization = data_dict.get('organization')
    if organization is None:
        errors['organization'] = _('Missing value')
    vat_id = data_dict.get('vat_id')
    if vat_id is None:
        errors['vat_id'] = _('Missing value')
    contact_person_name = data_dict.get('contact_person_name')
    if contact_person_name is None:
        errors['contact_person_name'] = _('Missing value')
    contact_person_email = data_dict.get('contact_person_email')
    if contact_person_email is None:
        errors['contact_person_email'] = _('Missing value')
    ip_address_list = data_dict.get('ip_address_list')
    if ip_address_list is None:
        errors['ip_address_list'] = _('Missing value')
    subsystem_code = data_dict.get('subsystem_code')
    if subsystem_code is None:
        errors['subsystem_code'] = _('Missing value')
    api_id = data_dict.get('api_id')
    if api_id is None:
        errors['api_id'] = _('Missing value')

    if errors:
        raise tk.ValidationError(errors)

    request_description = data_dict.get('api_id')

    model.ApplyPermission.create(organization=organization, vat_id=vat_id,
                          contact_person_name=contact_person_name,
                          contact_person_email=contact_person_email,
                          ip_address_list=ip_address_list,
                          subsystem_code=subsystem_code,
                          api_id=api_id,
                          request_description=request_description)

Prompt:
LIKA-106: Add validation to api for missing required values

from ckan.plugins import toolkit as tk
import model
import ckan.model as ckan_model

def service_permission_application_create(context, data_dict):
    tk.check_access('service_permission_application_create', context, data_dict)

    organization = data_dict.get('organization')
    vat_id = data_dict.get('vat_id')
    contact_person_name = data_dict.get('contact_person_name')
    contact_person_email = data_dict.get('contact_person_email')
    ip_address_list = data_dict.get('ip_address_list')
    subsystem_code = data_dict.get('subsystem_code')

    api_id = data_dict.get('api_id')
    request_description = data_dict.get('api_id')

    model.ApplyPermission.create(organization=organization, vat_id=vat_id,
                          contact_person_name=contact_person_name,
                          contact_person_email=contact_person_email,
                          ip_address_list=ip_address_list,
                          subsystem_code=subsystem_code,
                          api_id=api_id,
                          request_description=request_description)


from ansiblelint import AnsibleLintRule
try:
    from types import StringTypes
except ImportError:
    # Python3 removed types.StringTypes
    StringTypes = str,

class NoFormattingInWhenRule(AnsibleLintRule):
    id = 'CINCH0001'
    shortdesc = 'No Jinja2 in when'
    description = '"when" lines should not include Jinja2 variables'
    tags = ['deprecated']

    def _is_valid(self, when):
        if not isinstance(when, StringTypes):
            return True
        return when.find('{{') == -1 and when.find('}}') == -1

    def matchplay(self, file, play):
        errors = []
        if isinstance(play, dict):
            if 'roles' not in play:
                return errors
            for role in play['roles']:
                if self.matchtask(file, role):
                    errors.append(({'when': role},
                                   'role "when" clause has Jinja2 templates'))
        if isinstance(play, list):
            for play_item in play:
                sub_errors = self.matchplay(file, play_item)
                if sub_errors:
                    errors = errors + sub_errors
        return errors

    def matchtask(self, file, task):
        return 'when' in task and not self._is_valid(task['when'])

Fix Python3 unicode test error

Fix Python3 unicode test error

Response:
<REPLACE_OLD> AnsibleLintRule

class <REPLACE_NEW> AnsibleLintRule
try:
    from types import StringTypes
except ImportError:
    # Python3 removed types.StringTypes
    StringTypes = str,

class <REPLACE_END> <REPLACE_OLD> (str, unicode)):
 <REPLACE_NEW> StringTypes):
 <REPLACE_END> <|endoftext|> from ansiblelint import AnsibleLintRule
try:
    from types import StringTypes
except ImportError:
    # Python3 removed types.StringTypes
    StringTypes = str,

class NoFormattingInWhenRule(AnsibleLintRule):
    id = 'CINCH0001'
    shortdesc = 'No Jinja2 in when'
    description = '"when" lines should not include Jinja2 variables'
    tags = ['deprecated']

    def _is_valid(self, when):
        if not isinstance(when, StringTypes):
            return True
        return when.find('{{') == -1 and when.find('}}') == -1

    def matchplay(self, file, play):
        errors = []
        if isinstance(play, dict):
            if 'roles' not in play:
                return errors
            for role in play['roles']:
                if self.matchtask(file, role):
                    errors.append(({'when': role},
                                   'role "when" clause has Jinja2 templates'))
        if isinstance(play, list):
            for play_item in play:
                sub_errors = self.matchplay(file, play_item)
                if sub_errors:
                    errors = errors + sub_errors
        return errors

    def matchtask(self, file, task):
        return 'when' in task and not self._is_valid(task['when'])

Prompt:
Fix Python3 unicode test error

from ansiblelint import AnsibleLintRule

class NoFormattingInWhenRule(AnsibleLintRule):
    id = 'CINCH0001'
    shortdesc = 'No Jinja2 in when'
    description = '"when" lines should not include Jinja2 variables'
    tags = ['deprecated']

    def _is_valid(self, when):
        if not isinstance(when, (str, unicode)):
            return True
        return when.find('{{') == -1 and when.find('}}') == -1

    def matchplay(self, file, play):
        errors = []
        if isinstance(play, dict):
            if 'roles' not in play:
                return errors
            for role in play['roles']:
                if self.matchtask(file, role):
                    errors.append(({'when': role},
                                   'role "when" clause has Jinja2 templates'))
        if isinstance(play, list):
            for play_item in play:
                sub_errors = self.matchplay(file, play_item)
                if sub_errors:
                    errors = errors + sub_errors
        return errors

    def matchtask(self, file, task):
        return 'when' in task and not self._is_valid(task['when'])


import changes
import urlparse

from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView

class IndexView(MethodView):
    def get(self, path=''):
        # require auth
        if not session.get('email'):
            return redirect(url_for('login'))

        if current_app.config['SENTRY_DSN'] and False:
            parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
            dsn = '%s://%s@%s/%s' % (
                parsed.scheme,
                parsed.username,
                parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
                parsed.path,
            )
        else:
            dsn = None

        return render_template('index.html', **{
            'SENTRY_PUBLIC_DSN': dsn,
            'VERSION': changes.get_version(),
        })

Disable Sentry due to sync behavior

Disable Sentry due to sync behavior

Response:
<REPLACE_OLD> current_app.config['SENTRY_DSN']:
 <REPLACE_NEW> current_app.config['SENTRY_DSN'] and False:
 <REPLACE_END> <|endoftext|> import changes
import urlparse

from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView

class IndexView(MethodView):
    def get(self, path=''):
        # require auth
        if not session.get('email'):
            return redirect(url_for('login'))

        if current_app.config['SENTRY_DSN'] and False:
            parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
            dsn = '%s://%s@%s/%s' % (
                parsed.scheme,
                parsed.username,
                parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
                parsed.path,
            )
        else:
            dsn = None

        return render_template('index.html', **{
            'SENTRY_PUBLIC_DSN': dsn,
            'VERSION': changes.get_version(),
        })

Prompt:
Disable Sentry due to sync behavior

import changes
import urlparse

from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView

class IndexView(MethodView):
    def get(self, path=''):
        # require auth
        if not session.get('email'):
            return redirect(url_for('login'))

        if current_app.config['SENTRY_DSN']:
            parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
            dsn = '%s://%s@%s/%s' % (
                parsed.scheme,
                parsed.username,
                parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
                parsed.path,
            )
        else:
            dsn = None

        return render_template('index.html', **{
            'SENTRY_PUBLIC_DSN': dsn,
            'VERSION': changes.get_version(),
        })


from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from oidc_provider.views import *

urlpatterns = [

    url(r'^authorize/?$', AuthorizeView.as_view(), name='authorize'),
    url(r'^token/?$', csrf_exempt(TokenView.as_view()), name='token'),
    url(r'^userinfo/?$', csrf_exempt(userinfo), name='userinfo'),
    url(r'^logout/?$', LogoutView.as_view(), name='logout'),

    url(r'^\.well-known/openid-configuration/?$', ProviderInfoView.as_view(), name='provider_info'),
    url(r'^jwks/?$', JwksView.as_view(), name='jwks'),

]

Response:
<REPLACE_OLD> patterns('',

 <REPLACE_NEW> [

 <REPLACE_END> <REPLACE_OLD> name='jwks'),

)
 <REPLACE_NEW> name='jwks'),

]
 <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from oidc_provider.views import *

urlpatterns = [

    url(r'^authorize/?$', AuthorizeView.as_view(), name='authorize'),
    url(r'^token/?$', csrf_exempt(TokenView.as_view()), name='token'),
    url(r'^userinfo/?$', csrf_exempt(userinfo), name='userinfo'),
    url(r'^logout/?$', LogoutView.as_view(), name='logout'),

    url(r'^\.well-known/openid-configuration/?$', ProviderInfoView.as_view(), name='provider_info'),
    url(r'^jwks/?$', JwksView.as_view(), name='jwks'),

]

Prompt:
Remove patterns which will be deprecated in 1.10

from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from oidc_provider.views import *

urlpatterns = patterns('',

    url(r'^authorize/?$', AuthorizeView.as_view(), name='authorize'),
    url(r'^token/?$', csrf_exempt(TokenView.as_view()), name='token'),
    url(r'^userinfo/?$', csrf_exempt(userinfo), name='userinfo'),
    url(r'^logout/?$', LogoutView.as_view(), name='logout'),

    url(r'^\.well-known/openid-configuration/?$', ProviderInfoView.as_view(), name='provider_info'),
    url(r'^jwks/?$', JwksView.as_view(), name='jwks'),

)


#!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree

class SetArtistStreamable:

	def __init__(self):
		self.conn = ordbms.connect ("dbname='librefm'")
                self.cursor = self.conn.cursor()

	def updateAll(self):
		"""Sets artists streamable property if they have streamable tracks already in the database"""
		self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1")
		for artist in self.cursor.fetchall():
			name = artist[0]
			print "marking %s as streamable... " % name
			self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,))
			self.conn.commit()

if __name__ == '__main__':
	sas = SetArtistStreamable()
	sas.updateAll()

Response:
<REPLACE_OLD> (name,))
		print "Applying changes... ",
		self.conn.commit()
		print "done."

if <REPLACE_NEW> (name,))
			self.conn.commit()

if <REPLACE_END> <|endoftext|> #!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree

class SetArtistStreamable:

	def __init__(self):
		self.conn = ordbms.connect ("dbname='librefm'")
                self.cursor = self.conn.cursor()

	def updateAll(self):
		"""Sets artists streamable property if they have streamable tracks already in the database"""
		self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1")
		for artist in self.cursor.fetchall():
			name = artist[0]
			print "marking %s as streamable... " % name
			self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,))
			self.conn.commit()

if __name__ == '__main__':
	sas = SetArtistStreamable()
	sas.updateAll()

Prompt:
Make streamable artist updates as they happen, rather than commiting at the end of all artists

#!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree

class SetArtistStreamable:

	def __init__(self):
		self.conn = ordbms.connect ("dbname='librefm'")
                self.cursor = self.conn.cursor()

	def updateAll(self):
		"""Sets artists streamable property if they have streamable tracks already in the database"""
		self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1")
		for artist in self.cursor.fetchall():
			name = artist[0]
			print "marking %s as streamable... " % name
			self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,))
		print "Applying changes... ",
		self.conn.commit()
		print "done."

if __name__ == '__main__':
	sas = SetArtistStreamable()
	sas.updateAll()


from __future__ import print_function
from enum import IntEnum

import yaml

MemberFlag = IntEnum('MemberFlag', [
    'digest',
    'digest2',
    'modPost',
    'preapprove',
    'noPost',
    'diagnostic',
    'moderator',
    'myopic',
    'superadmin',
    'admin',
    'protected',
    'ccErrors',
    'reports',
    'vacation',
    'ackPost',
    'echoPost',
    'hidden',
    ])

def member_flag_representer(dumper, data):
    return dumper.represent_scalar(u'!flag', data.name)
yaml.add_representer(MemberFlag, member_flag_representer)
def member_flag_constructor(loader, node):
    value = loader.construct_scalar(node)
    return MemberFlag[value]
yaml.SafeLoader.add_constructor(u'!flag', member_flag_constructor)

class ListMember(yaml.YAMLObject):
    yaml_tag = u'!Member'
    yaml_loader = yaml.SafeLoader
    def __init__(self, address, *args, **kwargs):
        if isinstance(address, unicode):
            # Attempt to down-convert unicode-string addresses to plain strings
            try:
                address = str(address)
            except UnicodeEncodeError:
                pass
        self.address = address
        self.flags = set(a for a in args if isinstance(a, MemberFlag))
    def __repr__(self):
        return u'{}({}, flags: {})'.format(
                self.__class__.__name__,
                self.address,
                ', '.join(
                    map(lambda f: f.name,
                        self.flags)
                    ),
                )

Response:
<INSERT> if isinstance(address, unicode):
            # Attempt to down-convert unicode-string addresses to plain strings
            try:
                address = str(address)
            except UnicodeEncodeError:
                pass
        <INSERT_END> <|endoftext|> from __future__ import print_function
from enum import IntEnum

import yaml

MemberFlag = IntEnum('MemberFlag', [
    'digest',
    'digest2',
    'modPost',
    'preapprove',
    'noPost',
    'diagnostic',
    'moderator',
    'myopic',
    'superadmin',
    'admin',
    'protected',
    'ccErrors',
    'reports',
    'vacation',
    'ackPost',
    'echoPost',
    'hidden',
    ])

def member_flag_representer(dumper, data):
    return dumper.represent_scalar(u'!flag', data.name)
yaml.add_representer(MemberFlag, member_flag_representer)
def member_flag_constructor(loader, node):
    value = loader.construct_scalar(node)
    return MemberFlag[value]
yaml.SafeLoader.add_constructor(u'!flag', member_flag_constructor)

class ListMember(yaml.YAMLObject):
    yaml_tag = u'!Member'
    yaml_loader = yaml.SafeLoader
    def __init__(self, address, *args, **kwargs):
        if isinstance(address, unicode):
            # Attempt to down-convert unicode-string addresses to plain strings
            try:
                address = str(address)
            except UnicodeEncodeError:
                pass
        self.address = address
        self.flags = set(a for a in args if isinstance(a, MemberFlag))
    def __repr__(self):
        return u'{}({}, flags: {})'.format(
                self.__class__.__name__,
                self.address,
                ', '.join(
                    map(lambda f: f.name,
                        self.flags)
                    ),
                )

Prompt:
Convert list member addresses to non-unicode strings when possible.

from __future__ import print_function
from enum import IntEnum

import yaml

MemberFlag = IntEnum('MemberFlag', [
    'digest',
    'digest2',
    'modPost',
    'preapprove',
    'noPost',
    'diagnostic',
    'moderator',
    'myopic',
    'superadmin',
    'admin',
    'protected',
    'ccErrors',
    'reports',
    'vacation',
    'ackPost',
    'echoPost',
    'hidden',
    ])

def member_flag_representer(dumper, data):
    return dumper.represent_scalar(u'!flag', data.name)
yaml.add_representer(MemberFlag, member_flag_representer)
def member_flag_constructor(loader, node):
    value = loader.construct_scalar(node)
    return MemberFlag[value]
yaml.SafeLoader.add_constructor(u'!flag', member_flag_constructor)

class ListMember(yaml.YAMLObject):
    yaml_tag = u'!Member'
    yaml_loader = yaml.SafeLoader
    def __init__(self, address, *args, **kwargs):
        self.address = address
        self.flags = set(a for a in args if isinstance(a, MemberFlag))
    def __repr__(self):
        return u'{}({}, flags: {})'.format(
                self.__class__.__name__,
                self.address,
                ', '.join(
                    map(lambda f: f.name,
                        self.flags)
                    ),
                )


from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)

import io
import struct
import unittest
import threading
import time

import serial

try:
    import unittest2 as unittest
except ImportError:
    import unittest

class TestIsCorrectVariant(unittest.TestCase):

  def test_isMbVariant(self):
   self.assertTrue (serial.__version__.index('mb2') > 0 )

  def test_hasScanEndpoints(self):
    import serial.tools.list_ports as lp
    scan = lp.list_ports_by_vid_pid

  '''
  # This test is commented out because it requires an actual serial port.
  def test_variantDoesBlocking(self):
    #grab a port
    #try to grab it again
    import serial.tools.list_ports as lp
    scan = lp.list_ports_by_vid_pid
    print('autograbbing a port')
    comports = lp.comports()
    if( len(list(comports)) < 1):
        print('no comport availabe')
        self.assertFalse(True, "no comports, cannot execute test")
    portname = comports[-1][0] #item 0 in last comport as the port to test
    print("Connecting to serial" +  portname)
    s = serial.Serial(portname)
    with self.assertRaises(serial.SerialException) as ex:
        s = serial.Serial(portname)
   '''

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

Response:
<REPLACE_OLD> lp.list_ports_by_vid_pid

 <REPLACE_NEW> lp.list_ports_by_vid_pid

  '''
  # This test is commented out because it requires an actual serial port.
 <REPLACE_END> <REPLACE_OLD> serial.Serial(portname)

 <REPLACE_NEW> serial.Serial(portname)
   '''

 <REPLACE_END> <|endoftext|> from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)

import io
import struct
import unittest
import threading
import time

import serial

try:
    import unittest2 as unittest
except ImportError:
    import unittest

class TestIsCorrectVariant(unittest.TestCase):

  def test_isMbVariant(self):
   self.assertTrue (serial.__version__.index('mb2') > 0 )

  def test_hasScanEndpoints(self):
    import serial.tools.list_ports as lp
    scan = lp.list_ports_by_vid_pid

  '''
  # This test is commented out because it requires an actual serial port.
  def test_variantDoesBlocking(self):
    #grab a port
    #try to grab it again
    import serial.tools.list_ports as lp
    scan = lp.list_ports_by_vid_pid
    print('autograbbing a port')
    comports = lp.comports()
    if( len(list(comports)) < 1):
        print('no comport availabe')
        self.assertFalse(True, "no comports, cannot execute test")
    portname = comports[-1][0] #item 0 in last comport as the port to test
    print("Connecting to serial" +  portname)
    s = serial.Serial(portname)
    with self.assertRaises(serial.SerialException) as ex:
        s = serial.Serial(portname)
   '''

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

Prompt:
Comment out the pyserial TestIsCorrectVariant test.

from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)

import io
import struct
import unittest
import threading
import time

import serial

try:
    import unittest2 as unittest
except ImportError:
    import unittest

class TestIsCorrectVariant(unittest.TestCase):

  def test_isMbVariant(self):
   self.assertTrue (serial.__version__.index('mb2') > 0 )

  def test_hasScanEndpoints(self):
    import serial.tools.list_ports as lp
    scan = lp.list_ports_by_vid_pid

  def test_variantDoesBlocking(self):
    #grab a port
    #try to grab it again
    import serial.tools.list_ports as lp
    scan = lp.list_ports_by_vid_pid
    print('autograbbing a port')
    comports = lp.comports()
    if( len(list(comports)) < 1):
        print('no comport availabe')
        self.assertFalse(True, "no comports, cannot execute test")
    portname = comports[-1][0] #item 0 in last comport as the port to test
    print("Connecting to serial" +  portname)
    s = serial.Serial(portname)
    with self.assertRaises(serial.SerialException) as ex:
        s = serial.Serial(portname)

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


""" Plugin manager is Checker's main module.
    Plugin Manager is using Yapsy to find and load plugins from
    a directory and loads them via PluginRunner.
"""
from yapsy.PluginManager import PluginManager

from pluginRunner import PluginRunner
from configLoader import ConfigLoader
from down import Scraper

import logging
import sys

def main():
    """ Load configuration, find plugins, run plugin runner.
    """
    if len(sys.argv) == 2:
        # load configuration
        cl = ConfigLoader()
        cl.load(sys.argv[1])

        # download initial transactions
        s = Scraper(cl.getDbconf())
        s.scrap(cl.getEntryPoints())

        logging.getLogger("yapsy").addHandler(logging.StreamHandler())

        # load plugins
        manager = PluginManager()
        manager.setPluginPlaces(["checker/plugin"])
        manager.collectPlugins()

        plugins = []
        for pluginInfo in manager.getAllPlugins():
            print(pluginInfo.name)
            plugins.append(pluginInfo.plugin_object)

        if len(plugins) == 0:
            print("No plugins found")
        runner = PluginRunner(cl.getDbconf(), cl.getUriAcceptor(),
                              cl.getTypeAcceptor(), cl.getMaxDepth())

        # verify
        runner.run(plugins)
    else:
        print("Usage: "+sys.argv[0]+" <configuration YAML file>")

if __name__ == "__main__":
    main()

Fix typo - XML<->YAML configuration

Fix typo - XML<->YAML configuration

Response:
<REPLACE_OLD> XML <REPLACE_NEW> YAML <REPLACE_END> <|endoftext|> """ Plugin manager is Checker's main module.
    Plugin Manager is using Yapsy to find and load plugins from
    a directory and loads them via PluginRunner.
"""
from yapsy.PluginManager import PluginManager

from pluginRunner import PluginRunner
from configLoader import ConfigLoader
from down import Scraper

import logging
import sys

def main():
    """ Load configuration, find plugins, run plugin runner.
    """
    if len(sys.argv) == 2:
        # load configuration
        cl = ConfigLoader()
        cl.load(sys.argv[1])

        # download initial transactions
        s = Scraper(cl.getDbconf())
        s.scrap(cl.getEntryPoints())

        logging.getLogger("yapsy").addHandler(logging.StreamHandler())

        # load plugins
        manager = PluginManager()
        manager.setPluginPlaces(["checker/plugin"])
        manager.collectPlugins()

        plugins = []
        for pluginInfo in manager.getAllPlugins():
            print(pluginInfo.name)
            plugins.append(pluginInfo.plugin_object)

        if len(plugins) == 0:
            print("No plugins found")
        runner = PluginRunner(cl.getDbconf(), cl.getUriAcceptor(),
                              cl.getTypeAcceptor(), cl.getMaxDepth())

        # verify
        runner.run(plugins)
    else:
        print("Usage: "+sys.argv[0]+" <configuration YAML file>")

if __name__ == "__main__":
    main()

Prompt:
Fix typo - XML<->YAML configuration

""" Plugin manager is Checker's main module.
    Plugin Manager is using Yapsy to find and load plugins from
    a directory and loads them via PluginRunner.
"""
from yapsy.PluginManager import PluginManager

from pluginRunner import PluginRunner
from configLoader import ConfigLoader
from down import Scraper

import logging
import sys

def main():
    """ Load configuration, find plugins, run plugin runner.
    """
    if len(sys.argv) == 2:
        # load configuration
        cl = ConfigLoader()
        cl.load(sys.argv[1])

        # download initial transactions
        s = Scraper(cl.getDbconf())
        s.scrap(cl.getEntryPoints())

        logging.getLogger("yapsy").addHandler(logging.StreamHandler())

        # load plugins
        manager = PluginManager()
        manager.setPluginPlaces(["checker/plugin"])
        manager.collectPlugins()

        plugins = []
        for pluginInfo in manager.getAllPlugins():
            print(pluginInfo.name)
            plugins.append(pluginInfo.plugin_object)

        if len(plugins) == 0:
            print("No plugins found")
        runner = PluginRunner(cl.getDbconf(), cl.getUriAcceptor(),
                              cl.getTypeAcceptor(), cl.getMaxDepth())

        # verify
        runner.run(plugins)
    else:
        print("Usage: "+sys.argv[0]+" <configuration XML file>")

if __name__ == "__main__":
    main()


"""

Very basic implementation of an event loop
==========================================

The eventloop is a singleton to schedule and run events.

Exports
-------

- ``EventLoop``: the basic eventloop

"""

import queue
import sys
import threading
import time
import traceback

from .singleton import Singleton

def exception_message():
    """Create a message with details on the exception."""
    exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
    return {'exception': {'type': exc_type,
                          'value': exc_value,
                          'traceback': exc_tb},
            'traceback': traceback.format_exception(*exc_info)}

class EventLoop(object, metaclass=Singleton):
    """A generic event loop object."""

    def __init__(self):
        self.queue = queue.Queue()

    def schedule(self, event):
        """Schedule an event.

        The events have the form::

            (event, error)

        where `event` is a thunk and `error` is called with an
        exception message (output of `exception_message`) if there is
        an error when executing `event`.

        """
        self.queue.put(event)

    def stop(self):
        """Stop the loop."""
        pass

    def run_step(self, block=True):
        """Process one event."""
        ev, error = self.queue.get(block=block)
        try:
            ev()
        except Exception as exc:
            error(exception_message())

    def run(self):
        """Process all events in the queue."""
        try:
            while True:
                self.run_step(block=False)
        except queue.Empty:
            return

Response:
<REPLACE_OLD> _format_exception(exc_info):
 <REPLACE_NEW> exception_message():
 <REPLACE_END> <REPLACE_OLD> exc_info
 <REPLACE_NEW> exc_info = sys.exc_info()
 <REPLACE_END> <REPLACE_OLD> `_format_exception`) <REPLACE_NEW> `exception_message`) <REPLACE_END> <REPLACE_OLD> error(_format_exception(sys.exc_info()))

 <REPLACE_NEW> error(exception_message())

 <REPLACE_END> <|endoftext|> """

Very basic implementation of an event loop
==========================================

The eventloop is a singleton to schedule and run events.

Exports
-------

- ``EventLoop``: the basic eventloop

"""

import queue
import sys
import threading
import time
import traceback

from .singleton import Singleton

def exception_message():
    """Create a message with details on the exception."""
    exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
    return {'exception': {'type': exc_type,
                          'value': exc_value,
                          'traceback': exc_tb},
            'traceback': traceback.format_exception(*exc_info)}

class EventLoop(object, metaclass=Singleton):
    """A generic event loop object."""

    def __init__(self):
        self.queue = queue.Queue()

    def schedule(self, event):
        """Schedule an event.

        The events have the form::

            (event, error)

        where `event` is a thunk and `error` is called with an
        exception message (output of `exception_message`) if there is
        an error when executing `event`.

        """
        self.queue.put(event)

    def stop(self):
        """Stop the loop."""
        pass

    def run_step(self, block=True):
        """Process one event."""
        ev, error = self.queue.get(block=block)
        try:
            ev()
        except Exception as exc:
            error(exception_message())

    def run(self):
        """Process all events in the queue."""
        try:
            while True:
                self.run_step(block=False)
        except queue.Empty:
            return

Prompt:
Make exception message builder a nicer function

It is used by clients in other modules.
"""

Very basic implementation of an event loop
==========================================

The eventloop is a singleton to schedule and run events.

Exports
-------

- ``EventLoop``: the basic eventloop

"""

import queue
import sys
import threading
import time
import traceback

from .singleton import Singleton

def _format_exception(exc_info):
    """Create a message with details on the exception."""
    exc_type, exc_value, exc_tb = exc_info
    return {'exception': {'type': exc_type,
                          'value': exc_value,
                          'traceback': exc_tb},
            'traceback': traceback.format_exception(*exc_info)}

class EventLoop(object, metaclass=Singleton):
    """A generic event loop object."""

    def __init__(self):
        self.queue = queue.Queue()

    def schedule(self, event):
        """Schedule an event.

        The events have the form::

            (event, error)

        where `event` is a thunk and `error` is called with an
        exception message (output of `_format_exception`) if there is
        an error when executing `event`.

        """
        self.queue.put(event)

    def stop(self):
        """Stop the loop."""
        pass

    def run_step(self, block=True):
        """Process one event."""
        ev, error = self.queue.get(block=block)
        try:
            ev()
        except Exception as exc:
            error(_format_exception(sys.exc_info()))

    def run(self):
        """Process all events in the queue."""
        try:
            while True:
                self.run_step(block=False)
        except queue.Empty:
            return


import io

import eccodes

class Message:
    def __init__(self, handle):
        self.handle = handle

    def __del__(self):
        eccodes.codes_release(self.handle)

    def get(self, name):
        return eccodes.codes_get(self.handle, name)

    def set(self, name, value):
        return eccodes.codes_set(self.handle, name, value)

    def get_array(self, name):
        return eccodes.codes_get_array(self.handle, name)

    def set_array(self, name, value):
        return eccodes.codes_set_array(self.handle, name, value)

    def write_to(self, fileobj):
        assert isinstance(fileobj, io.IOBase)
        eccodes.codes_write(self.handle, fileobj)

    def get_buffer(self):
        return eccodes.codes_get_message(self.handle)

Response:
<INSERT>    def get(self, name):
        return eccodes.codes_get(self.handle, name)

    def set(self, name, value):
        return eccodes.codes_set(self.handle, name, value)

 <INSERT_END> <|endoftext|>
import io

import eccodes

class Message:
    def __init__(self, handle):
        self.handle = handle

    def __del__(self):
        eccodes.codes_release(self.handle)

    def get(self, name):
        return eccodes.codes_get(self.handle, name)

    def set(self, name, value):
        return eccodes.codes_set(self.handle, name, value)

    def get_array(self, name):
        return eccodes.codes_get_array(self.handle, name)

    def set_array(self, name, value):
        return eccodes.codes_set_array(self.handle, name, value)

    def write_to(self, fileobj):
        assert isinstance(fileobj, io.IOBase)
        eccodes.codes_write(self.handle, fileobj)

    def get_buffer(self):
        return eccodes.codes_get_message(self.handle)

Prompt:
Add get/set methods to the Message class

import io

import eccodes

class Message:
    def __init__(self, handle):
        self.handle = handle

    def __del__(self):
        eccodes.codes_release(self.handle)

    def get_array(self, name):
        return eccodes.codes_get_array(self.handle, name)

    def set_array(self, name, value):
        return eccodes.codes_set_array(self.handle, name, value)

    def write_to(self, fileobj):
        assert isinstance(fileobj, io.IOBase)
        eccodes.codes_write(self.handle, fileobj)

    def get_buffer(self):
        return eccodes.codes_get_message(self.handle)


{
    PDBConst.Name: "config",
    PDBConst.Columns: [
    {
        PDBConst.Name: "Name",
        PDBConst.Attributes: ["varchar(128)", "not null", "primary key"]
    },
    {
        PDBConst.Name: "Value",
        PDBConst.Attributes: ["varchar(128)"]
    }],
    PDBConst.Initials: [
        {"Name": "'version'", "Value": "'4.2'"}
    ]
}

Update DB to v4.2 on note pdf support

Update DB to v4.2 on note pdf support

Response:
<REPLACE_OLD> "'4.1'"}
 <REPLACE_NEW> "'4.2'"}
 <REPLACE_END> <|endoftext|> {
    PDBConst.Name: "config",
    PDBConst.Columns: [
    {
        PDBConst.Name: "Name",
        PDBConst.Attributes: ["varchar(128)", "not null", "primary key"]
    },
    {
        PDBConst.Name: "Value",
        PDBConst.Attributes: ["varchar(128)"]
    }],
    PDBConst.Initials: [
        {"Name": "'version'", "Value": "'4.2'"}
    ]
}

Prompt:
Update DB to v4.2 on note pdf support

{
    PDBConst.Name: "config",
    PDBConst.Columns: [
    {
        PDBConst.Name: "Name",
        PDBConst.Attributes: ["varchar(128)", "not null", "primary key"]
    },
    {
        PDBConst.Name: "Value",
        PDBConst.Attributes: ["varchar(128)"]
    }],
    PDBConst.Initials: [
        {"Name": "'version'", "Value": "'4.1'"}
    ]
}


import asyncio

def require_request_model(cls, *args, validate=True, **kwargs):
    """
    Makes a handler require that a request body that map towards the given model
    is provided. Unless the ``validate`` option is set to ``False`` the data will
    be validated against the model's fields.

    The model will be passed to the handler as the last positional argument. ::

        @require_request_model(Model)
        async def handle_model(request, model):
            return 200, model
    """
    def decorator(handler):
        async def new_handler(request):
            body = await request.json()
            model = cls(**body)

            if validate:
                model.validate()

            return await handler(request, *args, model, **kwargs)
        return new_handler
    return decorator

def use_ws_subhandlers(handler):
    """
    Allows the handler to return any number of **subhandlers** that will be
    run in parallel. This makes it much cleaner and easier to write a handler
    that both listens for incoming messages on the socket connection, while
    also watching a changefeed from RethinkDB.

    Example usage ::

        @use_ws_subhandlers
        async def handle_feed(request, ws):
            async def handle_incoming(_, ws):
                async for msg in ws:
                    await Item(value=msg.data).save()

            async def handle_change(_, ws):
                async for item in await Item.changes():
                    ws.send_json(item)

            return [handle_incoming, handle_change]
    """
    async def new_handler(request, ws):
        handlers = await handler(request, ws)
        tasks = [request.app.loop.create_task(h(request, ws))
                 for h in handlers]

        try:
            await asyncio.gather(*tasks)
        finally:
            for task in tasks:
                task.cancel()

            await ws.close()
    return new_handler

Response:
<REPLACE_OLD> def <REPLACE_NEW> import asyncio

def <REPLACE_END> <REPLACE_OLD> decorator
 <REPLACE_NEW> decorator

def use_ws_subhandlers(handler):
    """
    Allows the handler to return any number of **subhandlers** that will be
    run in parallel. This makes it much cleaner and easier to write a handler
    that both listens for incoming messages on the socket connection, while
    also watching a changefeed from RethinkDB.

    Example usage ::

        @use_ws_subhandlers
        async def handle_feed(request, ws):
            async def handle_incoming(_, ws):
                async for msg in ws:
                    await Item(value=msg.data).save()

            async def handle_change(_, ws):
                async for item in await Item.changes():
                    ws.send_json(item)

            return [handle_incoming, handle_change]
    """
    async def new_handler(request, ws):
        handlers = await handler(request, ws)
        tasks = [request.app.loop.create_task(h(request, ws))
                 for h in handlers]

        try:
            await asyncio.gather(*tasks)
        finally:
            for task in tasks:
                task.cancel()

            await ws.close()
    return new_handler
 <REPLACE_END> <|endoftext|> import asyncio

def require_request_model(cls, *args, validate=True, **kwargs):
    """
    Makes a handler require that a request body that map towards the given model
    is provided. Unless the ``validate`` option is set to ``False`` the data will
    be validated against the model's fields.

    The model will be passed to the handler as the last positional argument. ::

        @require_request_model(Model)
        async def handle_model(request, model):
            return 200, model
    """
    def decorator(handler):
        async def new_handler(request):
            body = await request.json()
            model = cls(**body)

            if validate:
                model.validate()

            return await handler(request, *args, model, **kwargs)
        return new_handler
    return decorator

def use_ws_subhandlers(handler):
    """
    Allows the handler to return any number of **subhandlers** that will be
    run in parallel. This makes it much cleaner and easier to write a handler
    that both listens for incoming messages on the socket connection, while
    also watching a changefeed from RethinkDB.

    Example usage ::

        @use_ws_subhandlers
        async def handle_feed(request, ws):
            async def handle_incoming(_, ws):
                async for msg in ws:
                    await Item(value=msg.data).save()

            async def handle_change(_, ws):
                async for item in await Item.changes():
                    ws.send_json(item)

            return [handle_incoming, handle_change]
    """
    async def new_handler(request, ws):
        handlers = await handler(request, ws)
        tasks = [request.app.loop.create_task(h(request, ws))
                 for h in handlers]

        try:
            await asyncio.gather(*tasks)
        finally:
            for task in tasks:
                task.cancel()

            await ws.close()
    return new_handler

Prompt:
Add decorator for using websocket subhandlers

def require_request_model(cls, *args, validate=True, **kwargs):
    """
    Makes a handler require that a request body that map towards the given model
    is provided. Unless the ``validate`` option is set to ``False`` the data will
    be validated against the model's fields.

    The model will be passed to the handler as the last positional argument. ::

        @require_request_model(Model)
        async def handle_model(request, model):
            return 200, model
    """
    def decorator(handler):
        async def new_handler(request):
            body = await request.json()
            model = cls(**body)

            if validate:
                model.validate()

            return await handler(request, *args, model, **kwargs)
        return new_handler
    return decorator


#!/usr/bin/env python
"""
Created on Fri Mar 14 15:25:36 2014

@author: ibackus
"""

import time

t0 = time.time()
import matplotlib.pyplot as plt
import numpy as np
import datetime
import sys

t1 = time.time()
print 'Importing took {} s'.format(t1-t0)

if len(sys.argv) < 2:

    print 'USAGE:     walltime filename'

else:

    fname = sys.argv[-1]
    log_file = np.genfromtxt(fname, comments='#', delimiter=' ')
    walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum())
    walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean())

    print 'Total walltime: '
    print str(walltime_total)
    print 'Average walltime per step:'
    print str(walltime_avg)

    plt.plot(log_file[:,-1],'x')

    t2 = time.time()
    print 'Running took an extra {} s'.format(t2-t1)
    print 'For a total of {} s'.format(t2 - t0)

    plt.show()

Print statements added for profiling

Print statements added for profiling

Response:
<INSERT> time

t0 = time.time()
import <INSERT_END> <REPLACE_OLD> sys

if <REPLACE_NEW> sys

t1 = time.time()
print 'Importing took {} s'.format(t1-t0)

if <REPLACE_END> <REPLACE_OLD> plt.plot(log_file[:,-1],'x')
 <REPLACE_NEW> plt.plot(log_file[:,-1],'x')

    t2 = time.time()
    print 'Running took an extra {} s'.format(t2-t1)
    print 'For a total of {} s'.format(t2 - t0)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""
Created on Fri Mar 14 15:25:36 2014

@author: ibackus
"""

import time

t0 = time.time()
import matplotlib.pyplot as plt
import numpy as np
import datetime
import sys

t1 = time.time()
print 'Importing took {} s'.format(t1-t0)

if len(sys.argv) < 2:

    print 'USAGE:     walltime filename'

else:

    fname = sys.argv[-1]
    log_file = np.genfromtxt(fname, comments='#', delimiter=' ')
    walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum())
    walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean())

    print 'Total walltime: '
    print str(walltime_total)
    print 'Average walltime per step:'
    print str(walltime_avg)

    plt.plot(log_file[:,-1],'x')

    t2 = time.time()
    print 'Running took an extra {} s'.format(t2-t1)
    print 'For a total of {} s'.format(t2 - t0)

    plt.show()

Prompt:
Print statements added for profiling

#!/usr/bin/env python
"""
Created on Fri Mar 14 15:25:36 2014

@author: ibackus
"""

import matplotlib.pyplot as plt
import numpy as np
import datetime
import sys

if len(sys.argv) < 2:

    print 'USAGE:     walltime filename'

else:

    fname = sys.argv[-1]
    log_file = np.genfromtxt(fname, comments='#', delimiter=' ')
    walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum())
    walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean())

    print 'Total walltime: '
    print str(walltime_total)
    print 'Average walltime per step:'
    print str(walltime_avg)

    plt.plot(log_file[:,-1],'x')
    plt.show()


from genes import apt
import platform

class Config:
    OS = platform.system()
    (DIST, _, CODE) = platform.linux_distribution()
    REPO = DIST.lower() + '-' + CODE

def main():
    if Config.OS == 'Linux':
        if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
            apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
            apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
            apt.update()
            apt.install('docker-engine')
            #FIXME: add compose, machine, etc
        else:
            #FIXME: print failure case
            pass
    elif Config.OS = 'Darwin':
        #brew_cask.install('dockertoolbox')
        pass
    else:
        #FIXME: print failure, handle osx/windows
        pass

Add todos and stubs for osx

Add todos and stubs for osx

Response:
<REPLACE_OLD>
 <REPLACE_NEW> #FIXME: add compose, machine, etc
 <REPLACE_END> <REPLACE_OLD>
 <REPLACE_NEW> elif Config.OS = 'Darwin':
        #brew_cask.install('dockertoolbox')
        pass
 <REPLACE_END> <|endoftext|> from genes import apt
import platform

class Config:
    OS = platform.system()
    (DIST, _, CODE) = platform.linux_distribution()
    REPO = DIST.lower() + '-' + CODE

def main():
    if Config.OS == 'Linux':
        if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
            apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
            apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
            apt.update()
            apt.install('docker-engine')
            #FIXME: add compose, machine, etc
        else:
            #FIXME: print failure case
            pass
    elif Config.OS = 'Darwin':
        #brew_cask.install('dockertoolbox')
        pass
    else:
        #FIXME: print failure, handle osx/windows
        pass

Prompt:
Add todos and stubs for osx
from genes import apt
import platform

class Config:
    OS = platform.system()
    (DIST, _, CODE) = platform.linux_distribution()
    REPO = DIST.lower() + '-' + CODE

def main():
    if Config.OS == 'Linux':
        if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
            apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
            apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
            apt.update()
            apt.install('docker-engine')

        else:
            #FIXME: print failure case
            pass

    else:
        #FIXME: print failure, handle osx/windows
        pass


from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score

def test_proper_noun_in_sentance():
    assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])

def test_proper_noun_begins_sentance():
    assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])

def test_munroe_with_proper_nouns():
    result = munroe_score("Eilis is a small girl")
    assert result["score"] == 1.0

Update test now 'is' is a common word

Update test now 'is' is a common word

Response:
<REPLACE_OLD> 0.75
 <REPLACE_NEW> 1.0
 <REPLACE_END> <|endoftext|>
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score

def test_proper_noun_in_sentance():
    assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])

def test_proper_noun_begins_sentance():
    assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])

def test_munroe_with_proper_nouns():
    result = munroe_score("Eilis is a small girl")
    assert result["score"] == 1.0

Prompt:
Update test now 'is' is a common word

from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score

def test_proper_noun_in_sentance():
    assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])

def test_proper_noun_begins_sentance():
    assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])

def test_munroe_with_proper_nouns():
    result = munroe_score("Eilis is a small girl")
    assert result["score"] == 0.75


from django.db import models
from django.utils.translation import gettext_lazy as _

from fluent_contents.models import ContentItem

class {{ model }}(ContentItem):
    """
    CMS plugin data model to ...
    """
    title = models.CharField(_("Title"), max_length=200)

    class Meta:
        verbose_name = _("{{ model|title }}")
        verbose_name_plural = _("{{ model|title }}s")

    def __str__(self):
        return self.title

Response:
<DELETE> django.utils.six import python_2_unicode_compatible
from <DELETE_END> <REPLACE_OLD> ugettext_lazy <REPLACE_NEW> gettext_lazy <REPLACE_END> <REPLACE_OLD> ContentItem

@python_2_unicode_compatible
class <REPLACE_NEW> ContentItem

class <REPLACE_END> <|endoftext|> from django.db import models
from django.utils.translation import gettext_lazy as _

from fluent_contents.models import ContentItem

class {{ model }}(ContentItem):
    """
    CMS plugin data model to ...
    """
    title = models.CharField(_("Title"), max_length=200)

    class Meta:
        verbose_name = _("{{ model|title }}")
        verbose_name_plural = _("{{ model|title }}s")

    def __str__(self):
        return self.title

Prompt:
Update plugin_template to Python 3-only standards

from django.db import models
from django.utils.six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from fluent_contents.models import ContentItem

@python_2_unicode_compatible
class {{ model }}(ContentItem):
    """
    CMS plugin data model to ...
    """
    title = models.CharField(_("Title"), max_length=200)

    class Meta:
        verbose_name = _("{{ model|title }}")
        verbose_name_plural = _("{{ model|title }}s")

    def __str__(self):
        return self.title


from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404

from comics.models import (
    Comic,
    Post,
    Contributor
)

class ProfileView(DetailView):
    template_name="profile.html"
    model = User

    def dispatch(self, *args, **kwargs):
        if kwargs.get('username'):
            self.user = get_object_or_404(User, username=kwargs.get('username'))
        elif self.request.user:
            self.user = self.request.user
        else:
            raise Http404()
        return super(ProfileView, self).dispatch(*args, **kwargs)

    def get_object(self):
        return self.user

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)

        contributions = Contributor.objects.filter(contributor=self.user)

        comics = Comic.published_comics.filter(
            post__contributor__in=contributions
        ).order_by('-published')

        posts = Post.published_posts.filter(
            contributor__in=contributions
        ).exclude(
            id__in=comics.values_list('post')
        ).order_by('-published')

        context['posts'] = posts
        context['comics'] = comics

        return context

Response:
<REPLACE_OLD> Comic.published_comics.filter(post__contributor__in=contributions)

 <REPLACE_NEW> Comic.published_comics.filter(
            post__contributor__in=contributions
        ).order_by('-published')

 <REPLACE_END> <REPLACE_OLD> Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))

 <REPLACE_NEW> Post.published_posts.filter(
            contributor__in=contributions
        ).exclude(
            id__in=comics.values_list('post')
        ).order_by('-published')

 <REPLACE_END> <|endoftext|> from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404

from comics.models import (
    Comic,
    Post,
    Contributor
)

class ProfileView(DetailView):
    template_name="profile.html"
    model = User

    def dispatch(self, *args, **kwargs):
        if kwargs.get('username'):
            self.user = get_object_or_404(User, username=kwargs.get('username'))
        elif self.request.user:
            self.user = self.request.user
        else:
            raise Http404()
        return super(ProfileView, self).dispatch(*args, **kwargs)

    def get_object(self):
        return self.user

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)

        contributions = Contributor.objects.filter(contributor=self.user)

        comics = Comic.published_comics.filter(
            post__contributor__in=contributions
        ).order_by('-published')

        posts = Post.published_posts.filter(
            contributor__in=contributions
        ).exclude(
            id__in=comics.values_list('post')
        ).order_by('-published')

        context['posts'] = posts
        context['comics'] = comics

        return context

Prompt:
Order content on profile by most recent.

from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404

from comics.models import (
    Comic,
    Post,
    Contributor
)

class ProfileView(DetailView):
    template_name="profile.html"
    model = User

    def dispatch(self, *args, **kwargs):
        if kwargs.get('username'):
            self.user = get_object_or_404(User, username=kwargs.get('username'))
        elif self.request.user:
            self.user = self.request.user
        else:
            raise Http404()
        return super(ProfileView, self).dispatch(*args, **kwargs)

    def get_object(self):
        return self.user

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)

        contributions = Contributor.objects.filter(contributor=self.user)

        comics = Comic.published_comics.filter(post__contributor__in=contributions)

        posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))

        context['posts'] = posts
        context['comics'] = comics

        return context


"""Adhocracy extension."""
from pyramid.config import Configurator

from adhocracy_core import root_factory

def includeme(config):
    """Setup adhocracy extension.

    The kit package should be exactly like the spd package but with different
    root permissions and default translations for the emails.
    """
    # copied from adhocracy_spd (without resources and translations)
    config.include('adhocracy_core')
    config.commit()
    config.include('adhocracy_spd.sheets')
    config.include('adhocracy_spd.workflows')
    config.include('adhocracy_spd.evolution')

    # add translations
    config.add_translation_dirs('adhocracy_core:locale/')

    # copoied from adhocracy_spd.resources resources
    config.include('adhocracy_spd.resources.digital_leben')

    # include kit resource types
    config.include('.resources')

def main(global_config, **settings):
    """ Return a Pyramid WSGI application. """
    config = Configurator(settings=settings, root_factory=root_factory)
    includeme(config)
    return config.make_wsgi_app()

Response:
<REPLACE_OLD> config.include('.sheets')
 <REPLACE_NEW> config.include('adhocracy_spd.sheets')
 <REPLACE_END> <REPLACE_OLD> config.include('.workflows')
 <REPLACE_NEW> config.include('adhocracy_spd.workflows')
 <REPLACE_END> <REPLACE_OLD> config.include('.evolution')

 <REPLACE_NEW> config.include('adhocracy_spd.evolution')

 <REPLACE_END> <REPLACE_OLD> config.include('adhocracy-spd.resources.digital_leben')

 <REPLACE_NEW> config.include('adhocracy_spd.resources.digital_leben')

 <REPLACE_END> <|endoftext|> """Adhocracy extension."""
from pyramid.config import Configurator

from adhocracy_core import root_factory

def includeme(config):
    """Setup adhocracy extension.

    The kit package should be exactly like the spd package but with different
    root permissions and default translations for the emails.
    """
    # copied from adhocracy_spd (without resources and translations)
    config.include('adhocracy_core')
    config.commit()
    config.include('adhocracy_spd.sheets')
    config.include('adhocracy_spd.workflows')
    config.include('adhocracy_spd.evolution')

    # add translations
    config.add_translation_dirs('adhocracy_core:locale/')

    # copoied from adhocracy_spd.resources resources
    config.include('adhocracy_spd.resources.digital_leben')

    # include kit resource types
    config.include('.resources')

def main(global_config, **settings):
    """ Return a Pyramid WSGI application. """
    config = Configurator(settings=settings, root_factory=root_factory)
    includeme(config)
    return config.make_wsgi_app()

Prompt:
Fix wrong config includes in kit package

"""Adhocracy extension."""
from pyramid.config import Configurator

from adhocracy_core import root_factory

def includeme(config):
    """Setup adhocracy extension.

    The kit package should be exactly like the spd package but with different
    root permissions and default translations for the emails.
    """
    # copied from adhocracy_spd (without resources and translations)
    config.include('adhocracy_core')
    config.commit()
    config.include('.sheets')
    config.include('.workflows')
    config.include('.evolution')

    # add translations
    config.add_translation_dirs('adhocracy_core:locale/')

    # copoied from adhocracy_spd.resources resources
    config.include('adhocracy-spd.resources.digital_leben')

    # include kit resource types
    config.include('.resources')

def main(global_config, **settings):
    """ Return a Pyramid WSGI application. """
    config = Configurator(settings=settings, root_factory=root_factory)
    includeme(config)
    return config.make_wsgi_app()


import os
from os.path import dirname, join
import uuid

import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf

QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')

qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY

QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)

def test_put_file():
    ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
    with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
        text = assset_file.read()
    text = text[:len(text)/10]

    print "Test text: %s" % text
    token = QINIU_PUT_POLICY.token()
    ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
    if err:
        raise IOError(
            "Error message: %s" % err)

Test with even smaller files

Test with even smaller files

Response:
<REPLACE_OLD> assset_file.read()

 <REPLACE_NEW> assset_file.read()
    text = text[:len(text)/10]

 <REPLACE_END> <|endoftext|> import os
from os.path import dirname, join
import uuid

import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf

QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')

qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY

QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)

def test_put_file():
    ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
    with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
        text = assset_file.read()
    text = text[:len(text)/10]

    print "Test text: %s" % text
    token = QINIU_PUT_POLICY.token()
    ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
    if err:
        raise IOError(
            "Error message: %s" % err)

Prompt:
Test with even smaller files

import os
from os.path import dirname, join
import uuid

import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf

QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')

qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY

QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)

def test_put_file():
    ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
    with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
        text = assset_file.read()

    print "Test text: %s" % text
    token = QINIU_PUT_POLICY.token()
    ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
    if err:
        raise IOError(
            "Error message: %s" % err)


""" A bunch of helper functions that, when fixed up, will return the things we
need to make this website work! These functions use the weather and twitter APIs!!!
"""

## Import python libraries we need up here.

###############################################
###             Problem One!                ###
###############################################

def get_city_coordinates():
    """Find the GPS coordinates for Charlottesville,
    and fill in the information below
    """
    lattitude = ???
    longitude = ???

    return lattitude, longitude

###############################################
###             Problem Two!                ###
###############################################

def get_icon_size():
    """ Modify this function to return a number of instagram photos
    you want to appear on the site at a time! Because of how the instagram API works,
    it won't return more than 20 photos at once.
    """
    size = ???
    return size

###############################################
###             Problem Three!              ###
###############################################

def choose_number_of_tweets():
    """ Modify this function to return the max number of tweets
    you want to appear on the site at a time!
    """
    number = 30
    return number

###############################################
###             Problem Four!              ###
###############################################

def choose_hashtag():
    """ Modify this function to use return the hashtah #sparkhackathon
    """
    return hashtag

Set tweet limit to 30 tweets

Set tweet limit to 30 tweets

Response:
<INSERT> number = 30
    <INSERT_END> <|endoftext|> """ A bunch of helper functions that, when fixed up, will return the things we
need to make this website work! These functions use the weather and twitter APIs!!!
"""

## Import python libraries we need up here.

###############################################
###             Problem One!                ###
###############################################

def get_city_coordinates():
    """Find the GPS coordinates for Charlottesville,
    and fill in the information below
    """
    lattitude = ???
    longitude = ???

    return lattitude, longitude

###############################################
###             Problem Two!                ###
###############################################

def get_icon_size():
    """ Modify this function to return a number of instagram photos
    you want to appear on the site at a time! Because of how the instagram API works,
    it won't return more than 20 photos at once.
    """
    size = ???
    return size

###############################################
###             Problem Three!              ###
###############################################

def choose_number_of_tweets():
    """ Modify this function to return the max number of tweets
    you want to appear on the site at a time!
    """
    number = 30
    return number

###############################################
###             Problem Four!              ###
###############################################

def choose_hashtag():
    """ Modify this function to use return the hashtah #sparkhackathon
    """
    return hashtag

Prompt:
Set tweet limit to 30 tweets

""" A bunch of helper functions that, when fixed up, will return the things we
need to make this website work! These functions use the weather and twitter APIs!!!
"""

## Import python libraries we need up here.

###############################################
###             Problem One!                ###
###############################################

def get_city_coordinates():
    """Find the GPS coordinates for Charlottesville,
    and fill in the information below
    """
    lattitude = ???
    longitude = ???

    return lattitude, longitude

###############################################
###             Problem Two!                ###
###############################################

def get_icon_size():
    """ Modify this function to return a number of instagram photos
    you want to appear on the site at a time! Because of how the instagram API works,
    it won't return more than 20 photos at once.
    """
    size = ???
    return size

###############################################
###             Problem Three!              ###
###############################################

def choose_number_of_tweets():
    """ Modify this function to return the max number of tweets
    you want to appear on the site at a time!
    """
    return number

###############################################
###             Problem Four!              ###
###############################################

def choose_hashtag():
    """ Modify this function to use return the hashtah #sparkhackathon
    """
    return hashtag


"""
Track the modification date for pages.
"""

from datetime import datetime

from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

def register(cls, admin_cls):
    cls.add_to_class('creation_date', models.DateTimeField(_('creation date'), editable=False))
    cls.add_to_class('modification_date', models.DateTimeField(_('modification date'), editable=False))

    orig_save = cls.save
    def save(page):
        now = datetime.now()
        if page.id is None:
            page.creation_date = now
        page.modification_date = now
        orig_save(page)

    cls.save = save

Add page extension for tracking page creation and modification dates.

This can be used in conjunction with a response processor to set the "last-modified" or "etag" response headers.

Response:
<INSERT> """
Track the modification date for pages.
"""

from datetime import datetime

from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

def register(cls, admin_cls):
 <INSERT_END> <INSERT>   cls.add_to_class('creation_date', models.DateTimeField(_('creation date'), editable=False))
    cls.add_to_class('modification_date', models.DateTimeField(_('modification date'), editable=False))

    orig_save = cls.save
    def save(page):
        now = datetime.now()
        if page.id is None:
            page.creation_date = now
        page.modification_date = now
        orig_save(page)

    cls.save = save <INSERT_END> <|endoftext|> """
Track the modification date for pages.
"""

from datetime import datetime

from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

def register(cls, admin_cls):
    cls.add_to_class('creation_date', models.DateTimeField(_('creation date'), editable=False))
    cls.add_to_class('modification_date', models.DateTimeField(_('modification date'), editable=False))

    orig_save = cls.save
    def save(page):
        now = datetime.now()
        if page.id is None:
            page.creation_date = now
        page.modification_date = now
        orig_save(page)

    cls.save = save

Prompt:
Add page extension for tracking page creation and modification dates.

This can be used in conjunction with a response processor to set the "last-modified" or "etag" response headers.