"""Cartesian product of same numbers with repeated times."""

class CartesianProduct(object):
    def _product_two(self, nums1, nums2):
        two_products = []

        for i in range(len(nums1)):
            for j in range(len(nums2)):
                if isinstance(nums1[0], list):
                    # nums1[i] is a list.
                    two_products.append(nums1[i] + [nums2[j]])
                else:
                    # nums1[0] is not a list, i.e. nums1 is a list.
                    two_products.append([nums1[i]] + [nums2[j]])

        return two_products

    def repeated_product(self, nums, repeat):
        # Created repeated numbers as pool for Cartesian product.
        repeated_nums = [nums for _ in range(repeat)]

        result = repeated_nums[0]
        for r in range(1, repeat):
            result = self._product_two(result, repeated_nums[r])
        return result

def main():
    nums = [1, 2, 3]
    repeat = 2
    print CartesianProduct().repeated_product(nums, repeat)

if __name__ == '__main__':
    main()

Complete cartesian product for repeated

Complete cartesian product for repeated

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Cartesian product of same numbers with repeated times."""

class CartesianProduct(object):
    def _product_two(self, nums1, nums2):
        two_products = []

        for i in range(len(nums1)):
            for j in range(len(nums2)):
                if isinstance(nums1[0], list):
                    # nums1[i] is a list.
                    two_products.append(nums1[i] + [nums2[j]])
                else:
                    # nums1[0] is not a list, i.e. nums1 is a list.
                    two_products.append([nums1[i]] + [nums2[j]])

        return two_products

    def repeated_product(self, nums, repeat):
        # Created repeated numbers as pool for Cartesian product.
        repeated_nums = [nums for _ in range(repeat)]

        result = repeated_nums[0]
        for r in range(1, repeat):
            result = self._product_two(result, repeated_nums[r])
        return result

def main():
    nums = [1, 2, 3]
    repeat = 2
    print CartesianProduct().repeated_product(nums, repeat)

if __name__ == '__main__':
    main()
 <REPLACE_END> <|endoftext|> """Cartesian product of same numbers with repeated times."""

class CartesianProduct(object):
    def _product_two(self, nums1, nums2):
        two_products = []

        for i in range(len(nums1)):
            for j in range(len(nums2)):
                if isinstance(nums1[0], list):
                    # nums1[i] is a list.
                    two_products.append(nums1[i] + [nums2[j]])
                else:
                    # nums1[0] is not a list, i.e. nums1 is a list.
                    two_products.append([nums1[i]] + [nums2[j]])

        return two_products

    def repeated_product(self, nums, repeat):
        # Created repeated numbers as pool for Cartesian product.
        repeated_nums = [nums for _ in range(repeat)]

        result = repeated_nums[0]
        for r in range(1, repeat):
            result = self._product_two(result, repeated_nums[r])
        return result

def main():
    nums = [1, 2, 3]
    repeat = 2
    print CartesianProduct().repeated_product(nums, repeat)

if __name__ == '__main__':
    main()

Prompt: Complete cartesian product for repeated


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

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

from oslo_utils import eventletutils as _eventletutils

# Give a nice warning that if eventlet is being used these modules
# are highly recommended to be patched (or otherwise bad things could
# happen).
_eventletutils.warn_eventlet_not_patched(
    expected_patched_modules=['time', 'thread'])

# Promote helpers to this module namespace (for easy access).
from taskflow.engines.helpers import flow_from_detail   # noqa
from taskflow.engines.helpers import load               # noqa
from taskflow.engines.helpers import load_from_detail   # noqa
from taskflow.engines.helpers import load_from_factory  # noqa
from taskflow.engines.helpers import run                # noqa
from taskflow.engines.helpers import save_factory_details  # noqa

Response:
<REPLACE_OLD> License.

# promote <REPLACE_NEW> License.

from oslo_utils import eventletutils as _eventletutils

# Give a nice warning that if eventlet is being used these modules
# are highly recommended to be patched (or otherwise bad things could
# happen).
_eventletutils.warn_eventlet_not_patched(
    expected_patched_modules=['time', 'thread'])

# Promote <REPLACE_END> <REPLACE_OLD> namespace
from <REPLACE_NEW> namespace (for easy access).
from <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

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

from oslo_utils import eventletutils as _eventletutils

# Give a nice warning that if eventlet is being used these modules
# are highly recommended to be patched (or otherwise bad things could
# happen).
_eventletutils.warn_eventlet_not_patched(
    expected_patched_modules=['time', 'thread'])

# Promote helpers to this module namespace (for easy access).
from taskflow.engines.helpers import flow_from_detail   # noqa
from taskflow.engines.helpers import load               # noqa
from taskflow.engines.helpers import load_from_detail   # noqa
from taskflow.engines.helpers import load_from_factory  # noqa
from taskflow.engines.helpers import run                # noqa
from taskflow.engines.helpers import save_factory_details  # noqa

Prompt:
Use oslo_utils eventletutils to warn about eventlet patching

Change-Id: I86ba0de51b5c5789efae187ebc1c46ae32ff8b8b

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

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

# promote helpers to this module namespace
from taskflow.engines.helpers import flow_from_detail   # noqa
from taskflow.engines.helpers import load               # noqa
from taskflow.engines.helpers import load_from_detail   # noqa
from taskflow.engines.helpers import load_from_factory  # noqa
from taskflow.engines.helpers import run                # noqa
from taskflow.engines.helpers import save_factory_details  # noqa


import sys
import socket
import threading

def server_loop(local_host, local_port, remote_host, remote_port,
                receive_first):
    """
    The proxy is represented by the local host and port. The remote host and
    port represent the service's server.
    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((local_host, local_port))  # argument is a tuple
    except:
        # I recomment using port 3000 or greater
        print "[!!] Failed to listen on %s:%d" % (local_host, local_port)
        print "[!!] Check for other listening sockets or correct permissions."
        sys.exit(0)

    print "[*] Listening on %s:%d" % (local_host, local_port)
    server.listen(5)

    while(True):
        client_socket, addr = server.accept()
        # print out info of the local socket assigned
        print "[==>] Received incoming connection from %s:%d" % (
            addr[0], addr[1])

        # start a thread to talk to the remote host
        proxy_thread = threading.Thread(
            target=proxy_handler,
            args=(client_socket, remote_host, remote_port, receive_first))
        # check above that proxy_handler is a function defined before this call
        # to threading.Thread
        proxy_thread.start()

Add the main server loop

Add the main server loop

Response:
<REPLACE_OLD>  <REPLACE_NEW> import sys
import socket
import threading

def server_loop(local_host, local_port, remote_host, remote_port,
                receive_first):
    """
    The proxy is represented by the local host and port. The remote host and
    port represent the service's server.
    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((local_host, local_port))  # argument is a tuple
    except:
        # I recomment using port 3000 or greater
        print "[!!] Failed to listen on %s:%d" % (local_host, local_port)
        print "[!!] Check for other listening sockets or correct permissions."
        sys.exit(0)

    print "[*] Listening on %s:%d" % (local_host, local_port)
    server.listen(5)

    while(True):
        client_socket, addr = server.accept()
        # print out info of the local socket assigned
        print "[==>] Received incoming connection from %s:%d" % (
            addr[0], addr[1])

        # start a thread to talk to the remote host
        proxy_thread = threading.Thread(
            target=proxy_handler,
            args=(client_socket, remote_host, remote_port, receive_first))
        # check above that proxy_handler is a function defined before this call
        # to threading.Thread
        proxy_thread.start()
 <REPLACE_END> <|endoftext|> import sys
import socket
import threading

def server_loop(local_host, local_port, remote_host, remote_port,
                receive_first):
    """
    The proxy is represented by the local host and port. The remote host and
    port represent the service's server.
    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((local_host, local_port))  # argument is a tuple
    except:
        # I recomment using port 3000 or greater
        print "[!!] Failed to listen on %s:%d" % (local_host, local_port)
        print "[!!] Check for other listening sockets or correct permissions."
        sys.exit(0)

    print "[*] Listening on %s:%d" % (local_host, local_port)
    server.listen(5)

    while(True):
        client_socket, addr = server.accept()
        # print out info of the local socket assigned
        print "[==>] Received incoming connection from %s:%d" % (
            addr[0], addr[1])

        # start a thread to talk to the remote host
        proxy_thread = threading.Thread(
            target=proxy_handler,
            args=(client_socket, remote_host, remote_port, receive_first))
        # check above that proxy_handler is a function defined before this call
        # to threading.Thread
        proxy_thread.start()

Prompt: Add the main server loop


import importlib
import pkgutil

ignore_packages = set(['test'])

def import_submodules(package, recursive=True):
    """ Import all submodules of a module, recursively, including subpackages

    :param package: package (name or actual module)
    :type package: str | module
    :rtype: dict[str, types.ModuleType]
    """
    if isinstance(package, str):
        package = importlib.import_module(package)
    results = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        # test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
        if name.split('.')[1] not in ignore_packages:
            full_name = package.__name__ + '.' + name
            results[full_name] = importlib.import_module(full_name)
            if recursive and is_pkg:
                results.update(import_submodules(full_name))
    return results

# import submodules recursively
import_submodules(__name__)

Response:
<REPLACE_OLD> if(name <REPLACE_NEW> # test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
        if name.split('.')[1] <REPLACE_END> <REPLACE_OLD> ignore_packages):
 <REPLACE_NEW> ignore_packages:
 <REPLACE_END> <|endoftext|> import importlib
import pkgutil

ignore_packages = set(['test'])

def import_submodules(package, recursive=True):
    """ Import all submodules of a module, recursively, including subpackages

    :param package: package (name or actual module)
    :type package: str | module
    :rtype: dict[str, types.ModuleType]
    """
    if isinstance(package, str):
        package = importlib.import_module(package)
    results = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        # test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
        if name.split('.')[1] not in ignore_packages:
            full_name = package.__name__ + '.' + name
            results[full_name] = importlib.import_module(full_name)
            if recursive and is_pkg:
                results.update(import_submodules(full_name))
    return results

# import submodules recursively
import_submodules(__name__)

Prompt:
Check for the name of the submodule we'd like to ignore in a more general way.

import importlib
import pkgutil

ignore_packages = set(['test'])

def import_submodules(package, recursive=True):
    """ Import all submodules of a module, recursively, including subpackages

    :param package: package (name or actual module)
    :type package: str | module
    :rtype: dict[str, types.ModuleType]
    """
    if isinstance(package, str):
        package = importlib.import_module(package)
    results = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        if(name not in ignore_packages):
            full_name = package.__name__ + '.' + name
            results[full_name] = importlib.import_module(full_name)
            if recursive and is_pkg:
                results.update(import_submodules(full_name))
    return results

# import submodules recursively
import_submodules(__name__)


from rest_framework import serializers

class StringListSerializer(serializers.ListField):
    child = serializers.CharField()

FIELD_CLASSES = {
    'integer': serializers.IntegerField,
    'date': serializers.DateField,
    'time': serializers.TimeField,
    'money': serializers.IntegerField,
    'boolean': serializers.BooleanField,
    'select_string': serializers.ChoiceField,
    'select_string_multi': serializers.MultipleChoiceField,
    'select_openstack_tenant': serializers.CharField,
    'select_multiple_openstack_tenants': StringListSerializer,
    'select_openstack_instance': serializers.CharField,
    'select_multiple_openstack_instances': StringListSerializer,
}

def validate_options(options, attributes):
    fields = {}

    for name, option in options.items():
        params = {}
        field_type = option.get('type', '')
        field_class = FIELD_CLASSES.get(field_type, serializers.CharField)

        default_value = option.get('default')
        if default_value:
            params['default'] = default_value
        else:
            params['required'] = option.get('required', False)

        if field_class == serializers.IntegerField:
            if 'min' in option:
                params['min_value'] = option.get('min')

            if 'max' in option:
                params['max_value'] = option.get('max')

        if 'choices' in option:
            params['choices'] = option['choices']

        fields[name] = field_class(**params)

    serializer_class = type('AttributesSerializer', (serializers.Serializer,), fields)
    serializer = serializer_class(data=attributes)
    serializer.is_valid(raise_exception=True)

Response:
<REPLACE_OLD> serializers

def <REPLACE_NEW> serializers

class StringListSerializer(serializers.ListField):
    child = serializers.CharField()

FIELD_CLASSES = {
    'integer': serializers.IntegerField,
    'date': serializers.DateField,
    'time': serializers.TimeField,
    'money': serializers.IntegerField,
    'boolean': serializers.BooleanField,
    'select_string': serializers.ChoiceField,
    'select_string_multi': serializers.MultipleChoiceField,
    'select_openstack_tenant': serializers.CharField,
    'select_multiple_openstack_tenants': StringListSerializer,
    'select_openstack_instance': serializers.CharField,
    'select_multiple_openstack_instances': StringListSerializer,
}

def <REPLACE_END> <REPLACE_OLD> serializers.CharField

        if field_type == 'integer':
            field_class = serializers.IntegerField

        elif field_type == 'money':
            field_class = serializers.IntegerField

        elif field_type == 'boolean':
            field_class = serializers.BooleanField

 <REPLACE_NEW> FIELD_CLASSES.get(field_type, serializers.CharField)

 <REPLACE_END> <DELETE> field_class = serializers.ChoiceField
            <DELETE_END> <REPLACE_OLD> option.get('choices')

        if field_type == 'select_string_multi':
            field_class = serializers.MultipleChoiceField
            params['choices'] = option.get('choices')

 <REPLACE_NEW> option['choices']

 <REPLACE_END> <|endoftext|> from rest_framework import serializers

class StringListSerializer(serializers.ListField):
    child = serializers.CharField()

FIELD_CLASSES = {
    'integer': serializers.IntegerField,
    'date': serializers.DateField,
    'time': serializers.TimeField,
    'money': serializers.IntegerField,
    'boolean': serializers.BooleanField,
    'select_string': serializers.ChoiceField,
    'select_string_multi': serializers.MultipleChoiceField,
    'select_openstack_tenant': serializers.CharField,
    'select_multiple_openstack_tenants': StringListSerializer,
    'select_openstack_instance': serializers.CharField,
    'select_multiple_openstack_instances': StringListSerializer,
}

def validate_options(options, attributes):
    fields = {}

    for name, option in options.items():
        params = {}
        field_type = option.get('type', '')
        field_class = FIELD_CLASSES.get(field_type, serializers.CharField)

        default_value = option.get('default')
        if default_value:
            params['default'] = default_value
        else:
            params['required'] = option.get('required', False)

        if field_class == serializers.IntegerField:
            if 'min' in option:
                params['min_value'] = option.get('min')

            if 'max' in option:
                params['max_value'] = option.get('max')

        if 'choices' in option:
            params['choices'] = option['choices']

        fields[name] = field_class(**params)

    serializer_class = type('AttributesSerializer', (serializers.Serializer,), fields)
    serializer = serializer_class(data=attributes)
    serializer.is_valid(raise_exception=True)

Prompt:
Fix validation of OpenStack select fields in request-based item form [WAL-4035]

from rest_framework import serializers

def validate_options(options, attributes):
    fields = {}

    for name, option in options.items():
        params = {}
        field_type = option.get('type', '')
        field_class = serializers.CharField

        if field_type == 'integer':
            field_class = serializers.IntegerField

        elif field_type == 'money':
            field_class = serializers.IntegerField

        elif field_type == 'boolean':
            field_class = serializers.BooleanField

        default_value = option.get('default')
        if default_value:
            params['default'] = default_value
        else:
            params['required'] = option.get('required', False)

        if field_class == serializers.IntegerField:
            if 'min' in option:
                params['min_value'] = option.get('min')

            if 'max' in option:
                params['max_value'] = option.get('max')

        if 'choices' in option:
            field_class = serializers.ChoiceField
            params['choices'] = option.get('choices')

        if field_type == 'select_string_multi':
            field_class = serializers.MultipleChoiceField
            params['choices'] = option.get('choices')

        fields[name] = field_class(**params)

    serializer_class = type('AttributesSerializer', (serializers.Serializer,), fields)
    serializer = serializer_class(data=attributes)
    serializer.is_valid(raise_exception=True)


from django.conf.urls.defaults import *
from .feed import blogFeed

urlpatterns = patterns('copywriting',
    (r'^feed\.rss$', blogFeed()),
    (r'^feed/$', blogFeed()),
    (r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
    # (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
    (r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
    (r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
    (r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
    (r'^$', 'views.listArticles'),
)

Allow slugs in url patterns

Allow slugs in url patterns

Response:
<DELETE>                                    <DELETE_END> <DELETE>                                        <DELETE_END> <REPLACE_OLD> (r'^tag/(?P<in_tag>\w+)/$',	                        <REPLACE_NEW> (r'^tag/(?P<in_tag>\w[\w-]+)/$', <REPLACE_END> <REPLACE_OLD> (r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$',	'views.listArticlesByYearMonth'),
 <REPLACE_NEW> (r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
 <REPLACE_END> <DELETE>                        <DELETE_END> <DELETE>                            <DELETE_END> <DELETE>                                             <DELETE_END> <|endoftext|> from django.conf.urls.defaults import *
from .feed import blogFeed

urlpatterns = patterns('copywriting',
    (r'^feed\.rss$', blogFeed()),
    (r'^feed/$', blogFeed()),
    (r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
    # (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
    (r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$', 'views.listArticlesByYearMonth'),
    (r'^(?P<requestYear>\d+)/$', 'views.listArticlesByYear'),
    (r'^(?P<slug>[^\.]+)/$', 'views.showArticle'),
    (r'^$', 'views.listArticles'),
)

Prompt:
Allow slugs in url patterns

from django.conf.urls.defaults import *
from .feed import blogFeed

urlpatterns = patterns('copywriting',
    (r'^feed\.rss$',                                    blogFeed()),
    (r'^feed/$',                                        blogFeed()),
    (r'^tag/(?P<in_tag>\w+)/$',	                        'views.withTag'),
    # (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),
    (r'^(?P<requestYear>\d+)/(?P<requestMonth>\d+)/$',	'views.listArticlesByYearMonth'),
    (r'^(?P<requestYear>\d+)/$',                        'views.listArticlesByYear'),
    (r'^(?P<slug>[^\.]+)/$',                            'views.showArticle'),
    (r'^$',                                             'views.listArticles'),
)


from .base import *
import os.path

DATABASES = {
        'default':
                {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': os.path.join(SITE_ROOT, 'dev.db'),
                }
}

SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'

try:
    from local_settings import *
except:
    pass

Allow local settings override as well.

Allow local settings override as well.

Response:
<REPLACE_OLD> 'http://localhost:8983/solr'

 <REPLACE_NEW> 'http://localhost:8983/solr'

try:
    from local_settings import *
except:
    pass

 <REPLACE_END> <|endoftext|> from .base import *
import os.path

DATABASES = {
        'default':
                {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': os.path.join(SITE_ROOT, 'dev.db'),
                }
}

SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'

try:
    from local_settings import *
except:
    pass

Prompt:
Allow local settings override as well.

from .base import *
import os.path

DATABASES = {
        'default':
                {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': os.path.join(SITE_ROOT, 'dev.db'),
                }
}

SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'


# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-06-17 13:50
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('fellowms', '0022_event_report_url'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='lat',
            field=models.FloatField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='event',
            name='lon',
            field=models.FloatField(blank=True, null=True),
        ),
    ]

Add migration for latitute and longitude of event

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-06-17 13:50
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('fellowms', '0022_event_report_url'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='lat',
            field=models.FloatField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='event',
            name='lon',
            field=models.FloatField(blank=True, null=True),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-06-17 13:50
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('fellowms', '0022_event_report_url'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='lat',
            field=models.FloatField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='event',
            name='lon',
            field=models.FloatField(blank=True, null=True),
        ),
    ]

Prompt: Add migration for latitute and longitude of event


"""
Tests of neo.io.axonaio
"""

import unittest

from neo.io.axonaio import AxonaIO
from neo.test.iotest.common_io_test import BaseTestIO
from neo.io.proxyobjects import (AnalogSignalProxy,
                SpikeTrainProxy, EventProxy, EpochProxy)
from neo import (AnalogSignal, SpikeTrain)

import quantities as pq
import numpy as np

class TestAxonaIO(BaseTestIO, unittest.TestCase, ):
    ioclass = AxonaIO
    entities_to_download = [
        'axona'
    ]
    entities_to_test = [
        'axona/axona_raw.set',
        'axona/dataset_unit_spikes/20140815-180secs.set'
    ]

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

Add new files to common io tests

Add new files to common io tests

Response:
<REPLACE_OLD> 'axona/axona_raw.set'
 <REPLACE_NEW> 'axona/axona_raw.set',
        'axona/dataset_unit_spikes/20140815-180secs.set'
 <REPLACE_END> <|endoftext|> """
Tests of neo.io.axonaio
"""

import unittest

from neo.io.axonaio import AxonaIO
from neo.test.iotest.common_io_test import BaseTestIO
from neo.io.proxyobjects import (AnalogSignalProxy,
                SpikeTrainProxy, EventProxy, EpochProxy)
from neo import (AnalogSignal, SpikeTrain)

import quantities as pq
import numpy as np

class TestAxonaIO(BaseTestIO, unittest.TestCase, ):
    ioclass = AxonaIO
    entities_to_download = [
        'axona'
    ]
    entities_to_test = [
        'axona/axona_raw.set',
        'axona/dataset_unit_spikes/20140815-180secs.set'
    ]

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

Prompt:
Add new files to common io tests

"""
Tests of neo.io.axonaio
"""

import unittest

from neo.io.axonaio import AxonaIO
from neo.test.iotest.common_io_test import BaseTestIO
from neo.io.proxyobjects import (AnalogSignalProxy,
                SpikeTrainProxy, EventProxy, EpochProxy)
from neo import (AnalogSignal, SpikeTrain)

import quantities as pq
import numpy as np

class TestAxonaIO(BaseTestIO, unittest.TestCase, ):
    ioclass = AxonaIO
    entities_to_download = [
        'axona'
    ]
    entities_to_test = [
        'axona/axona_raw.set'
    ]

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


"""Test for the Clifford algebra drudge."""

from drudge import CliffordDrudge, Vec, inner_by_delta

def test_clifford_drudge_by_quaternions(spark_ctx):
    """Test basic functionality of Clifford drudge by quaternions.
    """

    dr = CliffordDrudge(
        spark_ctx, inner=lambda v1, v2: -inner_by_delta(v1, v2)
    )
    e_ = Vec('e')

    i_ = dr.sum(e_[2] * e_[3]).simplify()
    j_ = dr.sum(e_[3] * e_[1]).simplify()
    k_ = dr.sum(e_[1] * e_[2]).simplify()

    for i in [i_, j_, k_]:
        assert (i * i).simplify() == -1

    assert (i_ * j_ * k_).simplify() == -1

    assert (i_ * j_).simplify() == k_
    assert (j_ * k_).simplify() == i_
    assert (k_ * i_).simplify() == j_

Add test for Clifford drudge by quaternions

Response:
<INSERT> """Test for the Clifford algebra drudge."""

from drudge import CliffordDrudge, Vec, inner_by_delta

def test_clifford_drudge_by_quaternions(spark_ctx):
 <INSERT_END> <INSERT>   """Test basic functionality of Clifford drudge by quaternions.
    """

    dr = CliffordDrudge(
        spark_ctx, inner=lambda v1, v2: -inner_by_delta(v1, v2)
    )
    e_ = Vec('e')

    i_ = dr.sum(e_[2] * e_[3]).simplify()
    j_ = dr.sum(e_[3] * e_[1]).simplify()
    k_ = dr.sum(e_[1] * e_[2]).simplify()

    for i in [i_, j_, k_]:
        assert (i * i).simplify() == -1

    assert (i_ * j_ * k_).simplify() == -1

    assert (i_ * j_).simplify() == k_
    assert (j_ * k_).simplify() == i_
    assert (k_ * i_).simplify() == j_
 <INSERT_END> <|endoftext|> """Test for the Clifford algebra drudge."""

from drudge import CliffordDrudge, Vec, inner_by_delta

def test_clifford_drudge_by_quaternions(spark_ctx):
    """Test basic functionality of Clifford drudge by quaternions.
    """

    dr = CliffordDrudge(
        spark_ctx, inner=lambda v1, v2: -inner_by_delta(v1, v2)
    )
    e_ = Vec('e')

    i_ = dr.sum(e_[2] * e_[3]).simplify()
    j_ = dr.sum(e_[3] * e_[1]).simplify()
    k_ = dr.sum(e_[1] * e_[2]).simplify()

    for i in [i_, j_, k_]:
        assert (i * i).simplify() == -1

    assert (i_ * j_ * k_).simplify() == -1

    assert (i_ * j_).simplify() == k_
    assert (j_ * k_).simplify() == i_
    assert (k_ * i_).simplify() == j_

Prompt: Add test for Clifford drudge by quaternions


import event_model
from intake_bluesky.core import documents_to_xarray

def test_no_descriptors():
    run_bundle = event_model.compose_run()
    start_doc = run_bundle.start_doc
    stop_doc = run_bundle.compose_stop()
    documents_to_xarray(start_doc=start_doc, stop_doc=stop_doc,
        descriptor_docs=[],
        event_docs=[],
        filler=event_model.Filler({}),
        get_resource=None,
        get_datum=None,
        get_datum_cursor=None)

def test_no_events():
    run_bundle = event_model.compose_run()
    start_doc = run_bundle.start_doc
    desc_bundle = run_bundle.compose_descriptor(
        data_keys={'x': {'source': '...', 'shape': [], 'dtype': 'number'}},
        name='primary')
    descriptor_doc = desc_bundle.descriptor_doc
    stop_doc = run_bundle.compose_stop()
    documents_to_xarray(start_doc=start_doc, stop_doc=stop_doc,
        descriptor_docs=[descriptor_doc],
        event_docs=[],
        filler=event_model.Filler({}),
        get_resource=None,
        get_datum=None,
        get_datum_cursor=None)

TST: Test runs with no descriptors or no events.

Response:
<INSERT> import event_model
from intake_bluesky.core import documents_to_xarray

def test_no_descriptors():
 <INSERT_END> <INSERT>   run_bundle = event_model.compose_run()
    start_doc = run_bundle.start_doc
    stop_doc = run_bundle.compose_stop()
    documents_to_xarray(start_doc=start_doc, stop_doc=stop_doc,
        descriptor_docs=[],
        event_docs=[],
        filler=event_model.Filler({}),
        get_resource=None,
        get_datum=None,
        get_datum_cursor=None)

def test_no_events():
    run_bundle = event_model.compose_run()
    start_doc = run_bundle.start_doc
    desc_bundle = run_bundle.compose_descriptor(
        data_keys={'x': {'source': '...', 'shape': [], 'dtype': 'number'}},
        name='primary')
    descriptor_doc = desc_bundle.descriptor_doc
    stop_doc = run_bundle.compose_stop()
    documents_to_xarray(start_doc=start_doc, stop_doc=stop_doc,
        descriptor_docs=[descriptor_doc],
        event_docs=[],
        filler=event_model.Filler({}),
        get_resource=None,
        get_datum=None,
        get_datum_cursor=None)
 <INSERT_END> <|endoftext|> import event_model
from intake_bluesky.core import documents_to_xarray

def test_no_descriptors():
    run_bundle = event_model.compose_run()
    start_doc = run_bundle.start_doc
    stop_doc = run_bundle.compose_stop()
    documents_to_xarray(start_doc=start_doc, stop_doc=stop_doc,
        descriptor_docs=[],
        event_docs=[],
        filler=event_model.Filler({}),
        get_resource=None,
        get_datum=None,
        get_datum_cursor=None)

def test_no_events():
    run_bundle = event_model.compose_run()
    start_doc = run_bundle.start_doc
    desc_bundle = run_bundle.compose_descriptor(
        data_keys={'x': {'source': '...', 'shape': [], 'dtype': 'number'}},
        name='primary')
    descriptor_doc = desc_bundle.descriptor_doc
    stop_doc = run_bundle.compose_stop()
    documents_to_xarray(start_doc=start_doc, stop_doc=stop_doc,
        descriptor_docs=[descriptor_doc],
        event_docs=[],
        filler=event_model.Filler({}),
        get_resource=None,
        get_datum=None,
        get_datum_cursor=None)

Prompt: TST: Test runs with no descriptors or no events.


__author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith'

from BaseHandler import *
import logging
from XMLAnalyser import XMLAnalyser
from google.appengine.api import memcache

class StudentsListHandler(BaseHandler):
    def __init__(self, request=None, response=None):
        self.initialize(request, response)
        self.pageName = "students_list"

    def get(self):
        self.render("groupchoice.html")

    def post(self):
        group_to_find = self.request.get("group_name")
        groups = memcache.get("group_list")

        if groups is None:
            logging.error("CACHE MISS StudentsListHandler l. 24")
            parser = XMLAnalyser()
            groups = parser.get_members()
            memcache.set("group_list", groups, time=604800);

        to_display = dict()
        for key in groups:
            if group_to_find in key:
                to_display[key] = groups[key]

        if len(to_display) > 0:
            self.render("groupdisplay.html", group_name=group_to_find, groups=to_display)
        else:
            self.render("message.html", title="No such group", subtitle="", argument=group_to_find)

Response:
<REPLACE_OLD> time=7200);

 <REPLACE_NEW> time=604800);

 <REPLACE_END> <|endoftext|> __author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith'

from BaseHandler import *
import logging
from XMLAnalyser import XMLAnalyser
from google.appengine.api import memcache

class StudentsListHandler(BaseHandler):
    def __init__(self, request=None, response=None):
        self.initialize(request, response)
        self.pageName = "students_list"

    def get(self):
        self.render("groupchoice.html")

    def post(self):
        group_to_find = self.request.get("group_name")
        groups = memcache.get("group_list")

        if groups is None:
            logging.error("CACHE MISS StudentsListHandler l. 24")
            parser = XMLAnalyser()
            groups = parser.get_members()
            memcache.set("group_list", groups, time=604800);

        to_display = dict()
        for key in groups:
            if group_to_find in key:
                to_display[key] = groups[key]

        if len(to_display) > 0:
            self.render("groupdisplay.html", group_name=group_to_find, groups=to_display)
        else:
            self.render("message.html", title="No such group", subtitle="", argument=group_to_find)

Prompt:
Change memcache expiration timing to 1 week

__author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith'

from BaseHandler import *
import logging
from XMLAnalyser import XMLAnalyser
from google.appengine.api import memcache

class StudentsListHandler(BaseHandler):
    def __init__(self, request=None, response=None):
        self.initialize(request, response)
        self.pageName = "students_list"

    def get(self):
        self.render("groupchoice.html")

    def post(self):
        group_to_find = self.request.get("group_name")
        groups = memcache.get("group_list")

        if groups is None:
            logging.error("CACHE MISS StudentsListHandler l. 24")
            parser = XMLAnalyser()
            groups = parser.get_members()
            memcache.set("group_list", groups, time=7200);

        to_display = dict()
        for key in groups:
            if group_to_find in key:
                to_display[key] = groups[key]

        if len(to_display) > 0:
            self.render("groupdisplay.html", group_name=group_to_find, groups=to_display)
        else:
            self.render("message.html", title="No such group", subtitle="", argument=group_to_find)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.db.conf import settings

from redis import ConnectionPool
from redis import Redis as RedisClient

class Redis:
    def __init__(self, key_prefix, key_sufix):
        self.key_prefix = key_prefix
        self.key_sufix = key_sufix
        self.host = settings.OPPS_DB_HOST
        self.port = settings.OPPS_DB_PORT
        self.db = 0

        pool = ConnectionPool(host=self.host,
                              port=self.port,
                              db=self.db)
        self.conn = RedisClient(connection_pool=pool)

    def close(self):
        self.conn = None
        return True

    def key(self):
        return '{}_{}_{}'.format(settings.OPPS_DB_NAME,
                                 self.key_prefix,
                                 self.key_sufix)

    def save(self, document):
        return self.conn.set(self.key(), document)

Response:
<INSERT>    def save(self, document):
        return self.conn.set(self.key(), document)

 <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.db.conf import settings

from redis import ConnectionPool
from redis import Redis as RedisClient

class Redis:
    def __init__(self, key_prefix, key_sufix):
        self.key_prefix = key_prefix
        self.key_sufix = key_sufix
        self.host = settings.OPPS_DB_HOST
        self.port = settings.OPPS_DB_PORT
        self.db = 0

        pool = ConnectionPool(host=self.host,
                              port=self.port,
                              db=self.db)
        self.conn = RedisClient(connection_pool=pool)

    def close(self):
        self.conn = None
        return True

    def key(self):
        return '{}_{}_{}'.format(settings.OPPS_DB_NAME,
                                 self.key_prefix,
                                 self.key_sufix)

    def save(self, document):
        return self.conn.set(self.key(), document)

Prompt:
Add method save, manager create or update on opps db redis

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.db.conf import settings

from redis import ConnectionPool
from redis import Redis as RedisClient

class Redis:
    def __init__(self, key_prefix, key_sufix):
        self.key_prefix = key_prefix
        self.key_sufix = key_sufix
        self.host = settings.OPPS_DB_HOST
        self.port = settings.OPPS_DB_PORT
        self.db = 0

        pool = ConnectionPool(host=self.host,
                              port=self.port,
                              db=self.db)
        self.conn = RedisClient(connection_pool=pool)

    def close(self):
        self.conn = None
        return True

    def key(self):
        return '{}_{}_{}'.format(settings.OPPS_DB_NAME,
                                 self.key_prefix,
                                 self.key_sufix)


# encoding: utf-8
# ---------------------------------------------------------------------------
#  Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
#  Distributed under the terms of the BSD License.  See COPYING.rst.
# ---------------------------------------------------------------------------

"""
Functions for running DistArray tests.
"""

from __future__ import print_function

import os
import sys
import shlex
import subprocess

import distarray

def _run_shell_command(specific_cmd):
    """Run a command with subprocess and pass the results through to stdout.

    First, change directory to the project directory.
    """
    path = os.path.split(os.path.split(distarray.__file__)[0])[0]
    os.chdir(path)
    proc = subprocess.Popen(shlex.split(specific_cmd),
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    while True:
        char = proc.stdout.read(1).decode()
        if not char:
            return proc.wait()
        else:
            print(char, end="")
            sys.stdout.flush()

def test():
    """Run all DistArray tests."""
    cmd = "make test"
    return _run_shell_command(cmd)

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

Return returncode from shell command.

Return returncode from shell command.

Response:
<REPLACE_OLD> break
 <REPLACE_NEW> return proc.wait()
 <REPLACE_END> <INSERT> return <INSERT_END> <REPLACE_OLD> test()
 <REPLACE_NEW> sys.exit(test())
 <REPLACE_END> <|endoftext|> # encoding: utf-8
# ---------------------------------------------------------------------------
#  Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
#  Distributed under the terms of the BSD License.  See COPYING.rst.
# ---------------------------------------------------------------------------

"""
Functions for running DistArray tests.
"""

from __future__ import print_function

import os
import sys
import shlex
import subprocess

import distarray

def _run_shell_command(specific_cmd):
    """Run a command with subprocess and pass the results through to stdout.

    First, change directory to the project directory.
    """
    path = os.path.split(os.path.split(distarray.__file__)[0])[0]
    os.chdir(path)
    proc = subprocess.Popen(shlex.split(specific_cmd),
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    while True:
        char = proc.stdout.read(1).decode()
        if not char:
            return proc.wait()
        else:
            print(char, end="")
            sys.stdout.flush()

def test():
    """Run all DistArray tests."""
    cmd = "make test"
    return _run_shell_command(cmd)

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

Prompt:
Return returncode from shell command.
# encoding: utf-8
# ---------------------------------------------------------------------------
#  Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
#  Distributed under the terms of the BSD License.  See COPYING.rst.
# ---------------------------------------------------------------------------

"""
Functions for running DistArray tests.
"""

from __future__ import print_function

import os
import sys
import shlex
import subprocess

import distarray

def _run_shell_command(specific_cmd):
    """Run a command with subprocess and pass the results through to stdout.

    First, change directory to the project directory.
    """
    path = os.path.split(os.path.split(distarray.__file__)[0])[0]
    os.chdir(path)
    proc = subprocess.Popen(shlex.split(specific_cmd),
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    while True:
        char = proc.stdout.read(1).decode()
        if not char:
            break
        else:
            print(char, end="")
            sys.stdout.flush()

def test():
    """Run all DistArray tests."""
    cmd = "make test"
    _run_shell_command(cmd)

if __name__ == "__main__":
    test()


#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#

"""Simple streaming test"""

from sparktestingbase.streamingtestcase import StreamingTestCase
import unittest2

class SimpleStreamingTest(StreamingTestCase):
    """A simple test."""

    @classmethod
    def tokenize(cls, f):
        return f.flatMap(lambda line: line.split(" "))

    @classmethod
    def noop(cls, f):
        return f.map(lambda x: x)

    def test_simple_transformation(self):
        input = [["hi"], ["hi holden"], ["bye"]]
        expected = [["hi"], ["hi", "holden"], ["bye"]]
        self.run_func(input, SimpleStreamingTest.tokenize, expected)

    def test_noop_transformation(self):
        input = [["hi"], ["hi holden"], ["bye"]]
        self.run_func(input, SimpleStreamingTest.noop, input)

if __name__ == "__main__":
    unittest2.main()

Response:
<REPLACE_OLD> "))

 <REPLACE_NEW> "))

    @classmethod
    def noop(cls, f):
        return f.map(lambda x: x)

 <REPLACE_END> <REPLACE_OLD> expected)

if <REPLACE_NEW> expected)

    def test_noop_transformation(self):
        input = [["hi"], ["hi holden"], ["bye"]]
        self.run_func(input, SimpleStreamingTest.noop, input)

if <REPLACE_END> <|endoftext|> #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#

"""Simple streaming test"""

from sparktestingbase.streamingtestcase import StreamingTestCase
import unittest2

class SimpleStreamingTest(StreamingTestCase):
    """A simple test."""

    @classmethod
    def tokenize(cls, f):
        return f.flatMap(lambda line: line.split(" "))

    @classmethod
    def noop(cls, f):
        return f.map(lambda x: x)

    def test_simple_transformation(self):
        input = [["hi"], ["hi holden"], ["bye"]]
        expected = [["hi"], ["hi", "holden"], ["bye"]]
        self.run_func(input, SimpleStreamingTest.tokenize, expected)

    def test_noop_transformation(self):
        input = [["hi"], ["hi holden"], ["bye"]]
        self.run_func(input, SimpleStreamingTest.noop, input)

if __name__ == "__main__":
    unittest2.main()

Prompt:
Add a second trivial streaming test to make sure our re-useing the spark context is ok

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#

"""Simple streaming test"""

from sparktestingbase.streamingtestcase import StreamingTestCase
import unittest2

class SimpleStreamingTest(StreamingTestCase):
    """A simple test."""

    @classmethod
    def tokenize(cls, f):
        return f.flatMap(lambda line: line.split(" "))

    def test_simple_transformation(self):
        input = [["hi"], ["hi holden"], ["bye"]]
        expected = [["hi"], ["hi", "holden"], ["bye"]]
        self.run_func(input, SimpleStreamingTest.tokenize, expected)

if __name__ == "__main__":
    unittest2.main()


from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch

hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'

class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
    def query_tests(self):
        tests = {
            QueryStringMatch('summary: test'): [
                {'summary': 'test'},
            ],

            QueryStringMatch('summary: test conf'): [
                {'summary': 'test'},
                {'summary': 'conf'},
                {'summary': 'test conf'},
            ],

            QueryStringMatch(hostname_test_regex): [
                {'hostname': 'host1.sub.abc.company.com'},
                {'hostname': 'host1.sub.test.abc.company.com'},
                {'hostname': 'host1.sub.test.abc.domain.company.com'},
                {'hostname': 'host1.sub.abc.domain.company.com'},
                {'hostname': 'host2.bus.abc.domain.company.com'},
            ],
        }
        return tests

class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
    def query_tests(self):
        tests = {
            QueryStringMatch('summary: test'): [
                {'summary': 'example summary'},
                {'summary': 'example summary tes'},
                {'summary': 'testing'},
                {'note': 'test'},
            ],

            QueryStringMatch('summary: test conf'): [
                {'summary': 'testing'},
                {'summary': 'configuration'},
                {'summary': 'testing configuration'},
            ],

            QueryStringMatch(hostname_test_regex): [
                {'hostname': 'host1.sub.abcd.company.com'},
                {'hostname': 'host1.sub.dabc.company.com'},
                {'hostname': 'host1.suba.abc.company.com'},
                {'hostname': 'host1.asub.abc.company.com'},
                {'hostname': 'host1.sub.dabc.domain.companyabc.com'},
                {'hostname': 'host2.bus.abc.domain.abcompany.com'},
            ],
        }
        return tests

Response:
<REPLACE_OLD> QueryStringMatch

class <REPLACE_NEW> QueryStringMatch

hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'

class <REPLACE_END> <INSERT> ],

            QueryStringMatch(hostname_test_regex): [
                {'hostname': 'host1.sub.abc.company.com'},
                {'hostname': 'host1.sub.test.abc.company.com'},
                {'hostname': 'host1.sub.test.abc.domain.company.com'},
                {'hostname': 'host1.sub.abc.domain.company.com'},
                {'hostname': 'host2.bus.abc.domain.company.com'},
            <INSERT_END> <INSERT> ],

            QueryStringMatch(hostname_test_regex): [
                {'hostname': 'host1.sub.abcd.company.com'},
                {'hostname': 'host1.sub.dabc.company.com'},
                {'hostname': 'host1.suba.abc.company.com'},
                {'hostname': 'host1.asub.abc.company.com'},
                {'hostname': 'host1.sub.dabc.domain.companyabc.com'},
                {'hostname': 'host2.bus.abc.domain.abcompany.com'},
            <INSERT_END> <|endoftext|> from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch

hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'

class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
    def query_tests(self):
        tests = {
            QueryStringMatch('summary: test'): [
                {'summary': 'test'},
            ],

            QueryStringMatch('summary: test conf'): [
                {'summary': 'test'},
                {'summary': 'conf'},
                {'summary': 'test conf'},
            ],

            QueryStringMatch(hostname_test_regex): [
                {'hostname': 'host1.sub.abc.company.com'},
                {'hostname': 'host1.sub.test.abc.company.com'},
                {'hostname': 'host1.sub.test.abc.domain.company.com'},
                {'hostname': 'host1.sub.abc.domain.company.com'},
                {'hostname': 'host2.bus.abc.domain.company.com'},
            ],
        }
        return tests

class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
    def query_tests(self):
        tests = {
            QueryStringMatch('summary: test'): [
                {'summary': 'example summary'},
                {'summary': 'example summary tes'},
                {'summary': 'testing'},
                {'note': 'test'},
            ],

            QueryStringMatch('summary: test conf'): [
                {'summary': 'testing'},
                {'summary': 'configuration'},
                {'summary': 'testing configuration'},
            ],

            QueryStringMatch(hostname_test_regex): [
                {'hostname': 'host1.sub.abcd.company.com'},
                {'hostname': 'host1.sub.dabc.company.com'},
                {'hostname': 'host1.suba.abc.company.com'},
                {'hostname': 'host1.asub.abc.company.com'},
                {'hostname': 'host1.sub.dabc.domain.companyabc.com'},
                {'hostname': 'host2.bus.abc.domain.abcompany.com'},
            ],
        }
        return tests

Prompt:
Add extra tests to query string query model

from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch

class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
    def query_tests(self):
        tests = {
            QueryStringMatch('summary: test'): [
                {'summary': 'test'},
            ],

            QueryStringMatch('summary: test conf'): [
                {'summary': 'test'},
                {'summary': 'conf'},
                {'summary': 'test conf'},
            ],
        }
        return tests

class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
    def query_tests(self):
        tests = {
            QueryStringMatch('summary: test'): [
                {'summary': 'example summary'},
                {'summary': 'example summary tes'},
                {'summary': 'testing'},
                {'note': 'test'},
            ],

            QueryStringMatch('summary: test conf'): [
                {'summary': 'testing'},
                {'summary': 'configuration'},
                {'summary': 'testing configuration'},
            ],
        }
        return tests


DATABASES = {
    "default": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": "polling_stations",
        "USER": "postgres",
        "PASSWORD": "",
        "HOST": "",  # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        "PORT": "",  # Set to empty string for default.
    }
}

EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

Send email to console as local default

Send email to console as local default

Response:
<REPLACE_OLD> True}
 <REPLACE_NEW> True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
 <REPLACE_END> <|endoftext|> DATABASES = {
    "default": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": "polling_stations",
        "USER": "postgres",
        "PASSWORD": "",
        "HOST": "",  # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        "PORT": "",  # Set to empty string for default.
    }
}

EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

Prompt:
Send email to console as local default

DATABASES = {
    "default": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": "polling_stations",
        "USER": "postgres",
        "PASSWORD": "",
        "HOST": "",  # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        "PORT": "",  # Set to empty string for default.
    }
}

EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}


"""
Class for communicating with the GrovePi ultrasonic ranger.

Here we treat it as a binary sensor.
"""

import logging
logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.getLevelName('INFO'))
try:
    from grovepi import ultrasonicRead
except ImportError:
    LOGGER.warning("GrovePi lib unavailable. Using dummy.")
    from drivers.dummy_grovepi_interface import ultrasonicRead

class GrovePiUltrasonicRangerBinary:
    """A module to read from the GrovePi Ultrasonic as a binary sensor."""

    def __init__(self, port, binary_threshold):
        """Create a GrovePi Ultrasonic Ranger (Binary) driver module."""
        self.port = int(port)
        self.binary_threshold = binary_threshold
        print(f"Setting up GrovePi Ultrasonic Ranger (Binary) on port {port}")

    def is_high(self):
        """HIGH, meaning "not seeing something"."""
        # to match the old GPIO sensors, we'll make this sensor active low
        # False output means object detected
        # True output means no object detected
        return ultrasonicRead(self.port) > self.binary_threshold

Fix grovepi import in sensor driver

Fix grovepi import in sensor driver

Response:
<REPLACE_OLD> GrovePi.Software.Python.grovepi <REPLACE_NEW> grovepi <REPLACE_END> <|endoftext|> """
Class for communicating with the GrovePi ultrasonic ranger.

Here we treat it as a binary sensor.
"""

import logging
logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.getLevelName('INFO'))
try:
    from grovepi import ultrasonicRead
except ImportError:
    LOGGER.warning("GrovePi lib unavailable. Using dummy.")
    from drivers.dummy_grovepi_interface import ultrasonicRead

class GrovePiUltrasonicRangerBinary:
    """A module to read from the GrovePi Ultrasonic as a binary sensor."""

    def __init__(self, port, binary_threshold):
        """Create a GrovePi Ultrasonic Ranger (Binary) driver module."""
        self.port = int(port)
        self.binary_threshold = binary_threshold
        print(f"Setting up GrovePi Ultrasonic Ranger (Binary) on port {port}")

    def is_high(self):
        """HIGH, meaning "not seeing something"."""
        # to match the old GPIO sensors, we'll make this sensor active low
        # False output means object detected
        # True output means no object detected
        return ultrasonicRead(self.port) > self.binary_threshold

Prompt:
Fix grovepi import in sensor driver

"""
Class for communicating with the GrovePi ultrasonic ranger.

Here we treat it as a binary sensor.
"""

import logging
logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.getLevelName('INFO'))
try:
    from GrovePi.Software.Python.grovepi import ultrasonicRead
except ImportError:
    LOGGER.warning("GrovePi lib unavailable. Using dummy.")
    from drivers.dummy_grovepi_interface import ultrasonicRead

class GrovePiUltrasonicRangerBinary:
    """A module to read from the GrovePi Ultrasonic as a binary sensor."""

    def __init__(self, port, binary_threshold):
        """Create a GrovePi Ultrasonic Ranger (Binary) driver module."""
        self.port = int(port)
        self.binary_threshold = binary_threshold
        print(f"Setting up GrovePi Ultrasonic Ranger (Binary) on port {port}")

    def is_high(self):
        """HIGH, meaning "not seeing something"."""
        # to match the old GPIO sensors, we'll make this sensor active low
        # False output means object detected
        # True output means no object detected
        return ultrasonicRead(self.port) > self.binary_threshold


import os
from flask import Blueprint, Flask
from flask import Flask, g
from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage
from flask.ext.restful import Api
from client import Client

def create_app():
  api = Api(blueprint)
  api.add_resource(Resources, '/resources')
  api.add_resource(UnixTime, '/time')
  api.add_resource(PrintArg,'/print/<string:arg>')
  api.add_resource(ExampleApiUsage,'/search')

  app = Flask(__name__, static_folder=None)
  app.url_map.strict_slashes = False
  app.config.from_pyfile('config.py')
  try:
    app.config.from_pyfile('local_config.py')
  except IOError:
    pass
  app.register_blueprint(blueprint)
  app.client = Client(app.config['CLIENT'])
  return app

Response:
<REPLACE_OLD> app.config.from_object('sample_application.config')
 <REPLACE_NEW> app.config.from_pyfile('config.py')
 <REPLACE_END> <REPLACE_OLD> app.config.from_object('sample_application.local_config')
 <REPLACE_NEW> app.config.from_pyfile('local_config.py')
 <REPLACE_END> <REPLACE_OLD> ImportError:
 <REPLACE_NEW> IOError:
 <REPLACE_END> <|endoftext|> import os
from flask import Blueprint, Flask
from flask import Flask, g
from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage
from flask.ext.restful import Api
from client import Client

def create_app():
  api = Api(blueprint)
  api.add_resource(Resources, '/resources')
  api.add_resource(UnixTime, '/time')
  api.add_resource(PrintArg,'/print/<string:arg>')
  api.add_resource(ExampleApiUsage,'/search')

  app = Flask(__name__, static_folder=None)
  app.url_map.strict_slashes = False
  app.config.from_pyfile('config.py')
  try:
    app.config.from_pyfile('local_config.py')
  except IOError:
    pass
  app.register_blueprint(blueprint)
  app.client = Client(app.config['CLIENT'])
  return app

Prompt:
Change config import strategy to config.from_pyfile()

import os
from flask import Blueprint, Flask
from flask import Flask, g
from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage
from flask.ext.restful import Api
from client import Client

def create_app():
  api = Api(blueprint)
  api.add_resource(Resources, '/resources')
  api.add_resource(UnixTime, '/time')
  api.add_resource(PrintArg,'/print/<string:arg>')
  api.add_resource(ExampleApiUsage,'/search')

  app = Flask(__name__, static_folder=None)
  app.url_map.strict_slashes = False
  app.config.from_object('sample_application.config')
  try:
    app.config.from_object('sample_application.local_config')
  except ImportError:
    pass
  app.register_blueprint(blueprint)
  app.client = Client(app.config['CLIENT'])
  return app


class Console(object):
    def __init__(self, shell, stdout):
        self._shell = shell
        self._stdout = stdout

    def run(self, description, command, **kwargs):
        return self.run_all(description, [command], **kwargs)

    def run_all(self, description, commands, quiet=False, cwd=None):
        stdout = None if quiet else self._stdout
        # TODO: Test printing description
        # TODO: detect terminal
        self._stdout.write(b'\033[1m')
        self._stdout.write(description.encode("utf8"))
        self._stdout.write(b"\n")
        self._stdout.write(b'\033[0m')
        self._stdout.flush()
        for command in commands:
            # TODO: print command
            result = self._shell.run(
                command,
                stdout=stdout,
                stderr=stdout,
                cwd=cwd,
                allow_error=True
            )
            if result.return_code != 0:
                return Result(result.return_code)

        return Result(0)

class Result(object):
    def __init__(self, return_code):
        self.return_code = return_code

Response:
<REPLACE_OLD> self._stdout.write('\033[1m')
        self._stdout.write(description)
        self._stdout.write("\n")
        self._stdout.write('\033[0m')
 <REPLACE_NEW> self._stdout.write(b'\033[1m')
        self._stdout.write(description.encode("utf8"))
        self._stdout.write(b"\n")
        self._stdout.write(b'\033[0m')
 <REPLACE_END> <|endoftext|> class Console(object):
    def __init__(self, shell, stdout):
        self._shell = shell
        self._stdout = stdout

    def run(self, description, command, **kwargs):
        return self.run_all(description, [command], **kwargs)

    def run_all(self, description, commands, quiet=False, cwd=None):
        stdout = None if quiet else self._stdout
        # TODO: Test printing description
        # TODO: detect terminal
        self._stdout.write(b'\033[1m')
        self._stdout.write(description.encode("utf8"))
        self._stdout.write(b"\n")
        self._stdout.write(b'\033[0m')
        self._stdout.flush()
        for command in commands:
            # TODO: print command
            result = self._shell.run(
                command,
                stdout=stdout,
                stderr=stdout,
                cwd=cwd,
                allow_error=True
            )
            if result.return_code != 0:
                return Result(result.return_code)

        return Result(0)

class Result(object):
    def __init__(self, return_code):
        self.return_code = return_code

Prompt:
Use bytes instead of str where appropriate for Python 3

class Console(object):
    def __init__(self, shell, stdout):
        self._shell = shell
        self._stdout = stdout

    def run(self, description, command, **kwargs):
        return self.run_all(description, [command], **kwargs)

    def run_all(self, description, commands, quiet=False, cwd=None):
        stdout = None if quiet else self._stdout
        # TODO: Test printing description
        # TODO: detect terminal
        self._stdout.write('\033[1m')
        self._stdout.write(description)
        self._stdout.write("\n")
        self._stdout.write('\033[0m')
        self._stdout.flush()
        for command in commands:
            # TODO: print command
            result = self._shell.run(
                command,
                stdout=stdout,
                stderr=stdout,
                cwd=cwd,
                allow_error=True
            )
            if result.return_code != 0:
                return Result(result.return_code)

        return Result(0)

class Result(object):
    def __init__(self, return_code):
        self.return_code = return_code


def parse_app_page(response):
    # Should always be able to grab a title
    title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip()
    # Parse times into floats
    time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip()
    time_to_hundo = time_to_hundo.replace(',', '.')
    time_to_hundo = float(time_to_hundo)
    # Points may or may not be present, default to 0 if absent
    points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract()
    if not points:
        points = 0
    else:
        points = int(points[0].strip())

    yield {
        'title': title,
        'time to 100%': time_to_hundo,
        'points': points,
        }

def parse_search_result_for_apps(response):
    for href in response.xpath('//table//table//a/@href'):
        relative_url = href.extract()
        if relative_url.startswith('Steam_Game_Info.php?AppID='):
            yield {
                'app_id' : relative_url[len('Steam_Game_Info.php?AppID='):]
            }

Fix up bad last commit

Fix up bad last commit

Response:
<REPLACE_OLD> }

def <REPLACE_NEW> }

def <REPLACE_END> <REPLACE_OLD> relative_url[:len('Steam_Game_Info.php?AppID=')]
 <REPLACE_NEW> {
                'app_id' : relative_url[len('Steam_Game_Info.php?AppID='):]
            }
 <REPLACE_END> <|endoftext|> def parse_app_page(response):
    # Should always be able to grab a title
    title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip()
    # Parse times into floats
    time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip()
    time_to_hundo = time_to_hundo.replace(',', '.')
    time_to_hundo = float(time_to_hundo)
    # Points may or may not be present, default to 0 if absent
    points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract()
    if not points:
        points = 0
    else:
        points = int(points[0].strip())

    yield {
        'title': title,
        'time to 100%': time_to_hundo,
        'points': points,
        }

def parse_search_result_for_apps(response):
    for href in response.xpath('//table//table//a/@href'):
        relative_url = href.extract()
        if relative_url.startswith('Steam_Game_Info.php?AppID='):
            yield {
                'app_id' : relative_url[len('Steam_Game_Info.php?AppID='):]
            }

Prompt:
Fix up bad last commit

def parse_app_page(response):
    # Should always be able to grab a title
    title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip()
    # Parse times into floats
    time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip()
    time_to_hundo = time_to_hundo.replace(',', '.')
    time_to_hundo = float(time_to_hundo)
    # Points may or may not be present, default to 0 if absent
    points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract()
    if not points:
        points = 0
    else:
        points = int(points[0].strip())

    yield {
        'title': title,
        'time to 100%': time_to_hundo,
        'points': points,
        }

def parse_search_result_for_apps(response):
    for href in response.xpath('//table//table//a/@href'):
        relative_url = href.extract()
        if relative_url.startswith('Steam_Game_Info.php?AppID='):
            yield relative_url[:len('Steam_Game_Info.php?AppID=')]


# This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.

# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.

DEBUG = False

# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            },
    },

}

# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/test-derrida',
        'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
    }
}

# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS

# secret key added as a travis build step

Response:
<REPLACE_OLD> },

}

HAYSTACK_TEST_CONNECTIONS <REPLACE_NEW> },

}

# must be defined for initial setup
HAYSTACK_CONNECTIONS <REPLACE_END> <REPLACE_OLD> }
}

# <REPLACE_NEW> }
}

# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS

# <REPLACE_END> <|endoftext|> # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.

# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.

DEBUG = False

# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            },
    },

}

# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/test-derrida',
        'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
    }
}

# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS

# secret key added as a travis build step

Prompt:
Tweak travis-ci settings for haystack setup and test

# This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.

# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.

DEBUG = False

# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            },
    },

}

HAYSTACK_TEST_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/test-derrida',
        'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
    }
}

# secret key added as a travis build step


# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site

def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    import copy
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'admin'):
                raise

Response:
<INSERT> # ACTION_CHECKBOX_NAME is unused, but should stay since its import <INSERT_END> <INSERT> here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from <INSERT_END> <|endoftext|> # ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site

def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    import copy
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'admin'):
                raise

Prompt:
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37

--HG--
extra : convert_revision : e026073455a73c9fe9a9f026b76ac783b2a12d23

from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site

def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    import copy
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'admin'):
                raise


#!/usr/bin/env python

from __future__ import absolute_import, print_function

# Standard library
from os import walk
from os.path import exists, isdir, join

# Local library
from .util import is_py_file
from .diff import diff_files

def main():
    import sys

    if len(sys.argv) < 3:
        print('Usage: %s <package1/module1> <package2/module2>' % sys.argv[0])
        sys.exit(1)

    old, new = sys.argv[1:3]

    diff = set([])

    if isdir(old):
        assert isdir(new)
        for dirpath, dirnames, filenames in walk(new):
            for file_ in filenames:
                if is_py_file(file_):
                    new_file = join(dirpath, file_)
                    old_file = new_file.replace(new, old)
                    if exists(old_file):
                        mdiff = diff_files(old_file, new_file)
                        if mdiff is not None:
                            diff.add(mdiff)

    else:
        diff.add(diff_files(old, new))

    for module in diff:
        print(module)

if __name__ == '__main__':
    main()

Fix minor bug in length comparison.

Fix minor bug in length comparison.

Response:
<REPLACE_OLD> sys.argv <REPLACE_NEW> len(sys.argv) <REPLACE_END> <REPLACE_OLD> <module1> <module2>' <REPLACE_NEW> <package1/module1> <package2/module2>' <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from __future__ import absolute_import, print_function

# Standard library
from os import walk
from os.path import exists, isdir, join

# Local library
from .util import is_py_file
from .diff import diff_files

def main():
    import sys

    if len(sys.argv) < 3:
        print('Usage: %s <package1/module1> <package2/module2>' % sys.argv[0])
        sys.exit(1)

    old, new = sys.argv[1:3]

    diff = set([])

    if isdir(old):
        assert isdir(new)
        for dirpath, dirnames, filenames in walk(new):
            for file_ in filenames:
                if is_py_file(file_):
                    new_file = join(dirpath, file_)
                    old_file = new_file.replace(new, old)
                    if exists(old_file):
                        mdiff = diff_files(old_file, new_file)
                        if mdiff is not None:
                            diff.add(mdiff)

    else:
        diff.add(diff_files(old, new))

    for module in diff:
        print(module)

if __name__ == '__main__':
    main()

Prompt:
Fix minor bug in length comparison.

#!/usr/bin/env python

from __future__ import absolute_import, print_function

# Standard library
from os import walk
from os.path import exists, isdir, join

# Local library
from .util import is_py_file
from .diff import diff_files

def main():
    import sys

    if sys.argv < 3:
        print('Usage: %s <module1> <module2>' % sys.argv[0])
        sys.exit(1)

    old, new = sys.argv[1:3]

    diff = set([])

    if isdir(old):
        assert isdir(new)
        for dirpath, dirnames, filenames in walk(new):
            for file_ in filenames:
                if is_py_file(file_):
                    new_file = join(dirpath, file_)
                    old_file = new_file.replace(new, old)
                    if exists(old_file):
                        mdiff = diff_files(old_file, new_file)
                        if mdiff is not None:
                            diff.add(mdiff)

    else:
        diff.add(diff_files(old, new))

    for module in diff:
        print(module)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import datetime
from hashlib import sha256
from time import gmtime, strftime

import sqlalchemy
from flask import render_template, redirect, url_for
from flask_app import app, db_connection, dbTables
from forms import RegisterForm

@app.route('/', methods=('GET', 'POST'))
def index():
    return render_template('index.html', title=u"Главная")

@app.route('/success', methods=('GET', 'POST'))
def success():
    return render_template('success.html', title=u"Регистрация завершена!")

@app.route('/sign-up', methods=('GET', 'POST'))
def sign_up():
    form = RegisterForm()
    if form.validate_on_submit():
        # new catalog for user
        catalog_name = str(form.data['login'] + "_main")
        new_dir = dbTables.Catalog(catalog_name)
        db_connection.session.add(new_dir)
        db_connection.session.commit()
        # new filespace for user
        fs_name = str(form.data['login'] + "_fs")
        new_fs = dbTables.FileSpace(fs_name, new_dir)
        db_connection.session.add(new_fs)
        db_connection.session.commit()
        fs = db_connection.session.execute(sqlalchemy.select([dbTables.FileSpace]).where(dbTables.FileSpace.storage_name == fs_name))
        fs = fs.fetchone()
        time_is = datetime.datetime.strptime(strftime("%d.%m.%Y", gmtime()), "%d.%m.%Y").date()
        time_is = time_is + datetime.timedelta(days=365)
        date_max = time_is.strftime("%d.%m.%Y")
        id_new = db_connection.session.execute(sqlalchemy.func.count(dbTables.Users.id)).fetchone()[0] + 1
        password_hash = str(sha256(form.data['password']+str(id_new)).hexdigest())
        # create new user
        new_user = dbTables.Users(form.data['login'], form.data['fullname'], password_hash, form.data['email'], date_max, 1, 2, fs.id)
        db_connection.session.add(new_user)
        db_connection.session.commit()
        return redirect(url_for('success'))
    return render_template('sign-up.html', title=u"Регистрация", form=form)

@app.route('/sign-in', methods=('GET', 'POST'))
def sign_in():
    return render_template('sign-in.html', title=u"Аутентификация")

@app.route('/forgot-password', methods=('GET', 'POST'))
def forgot_password():
    return render_template('forgot-password.html', title=u"Восстановление доступа")

Add routes for other pages

Add routes for other pages

Response:
<REPLACE_OLD> from <REPLACE_NEW> # -*- coding: utf-8 -*-
import datetime
from hashlib import sha256
from time import gmtime, strftime

import sqlalchemy
from <REPLACE_END> <REPLACE_OLD> render_template
from <REPLACE_NEW> render_template, redirect, url_for
from <REPLACE_END> <REPLACE_OLD> app

@app.route('/')
def <REPLACE_NEW> app, db_connection, dbTables
from forms import RegisterForm

@app.route('/', methods=('GET', 'POST'))
def <REPLACE_END> <REPLACE_OLD> render_template('index.html')

 <REPLACE_NEW> render_template('index.html', title=u"Главная")

@app.route('/success', methods=('GET', 'POST'))
def success():
    return render_template('success.html', title=u"Регистрация завершена!")

@app.route('/sign-up', methods=('GET', 'POST'))
def sign_up():
    form = RegisterForm()
    if form.validate_on_submit():
        # new catalog for user
        catalog_name = str(form.data['login'] + "_main")
        new_dir = dbTables.Catalog(catalog_name)
        db_connection.session.add(new_dir)
        db_connection.session.commit()
        # new filespace for user
        fs_name = str(form.data['login'] + "_fs")
        new_fs = dbTables.FileSpace(fs_name, new_dir)
        db_connection.session.add(new_fs)
        db_connection.session.commit()
        fs = db_connection.session.execute(sqlalchemy.select([dbTables.FileSpace]).where(dbTables.FileSpace.storage_name == fs_name))
        fs = fs.fetchone()
        time_is = datetime.datetime.strptime(strftime("%d.%m.%Y", gmtime()), "%d.%m.%Y").date()
        time_is = time_is + datetime.timedelta(days=365)
        date_max = time_is.strftime("%d.%m.%Y")
        id_new = db_connection.session.execute(sqlalchemy.func.count(dbTables.Users.id)).fetchone()[0] + 1
        password_hash = str(sha256(form.data['password']+str(id_new)).hexdigest())
        # create new user
        new_user = dbTables.Users(form.data['login'], form.data['fullname'], password_hash, form.data['email'], date_max, 1, 2, fs.id)
        db_connection.session.add(new_user)
        db_connection.session.commit()
        return redirect(url_for('success'))
    return render_template('sign-up.html', title=u"Регистрация", form=form)

@app.route('/sign-in', methods=('GET', 'POST'))
def sign_in():
    return render_template('sign-in.html', title=u"Аутентификация")

@app.route('/forgot-password', methods=('GET', 'POST'))
def forgot_password():
    return render_template('forgot-password.html', title=u"Восстановление доступа") <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import datetime
from hashlib import sha256
from time import gmtime, strftime

import sqlalchemy
from flask import render_template, redirect, url_for
from flask_app import app, db_connection, dbTables
from forms import RegisterForm

@app.route('/', methods=('GET', 'POST'))
def index():
    return render_template('index.html', title=u"Главная")

@app.route('/success', methods=('GET', 'POST'))
def success():
    return render_template('success.html', title=u"Регистрация завершена!")

@app.route('/sign-up', methods=('GET', 'POST'))
def sign_up():
    form = RegisterForm()
    if form.validate_on_submit():
        # new catalog for user
        catalog_name = str(form.data['login'] + "_main")
        new_dir = dbTables.Catalog(catalog_name)
        db_connection.session.add(new_dir)
        db_connection.session.commit()
        # new filespace for user
        fs_name = str(form.data['login'] + "_fs")
        new_fs = dbTables.FileSpace(fs_name, new_dir)
        db_connection.session.add(new_fs)
        db_connection.session.commit()
        fs = db_connection.session.execute(sqlalchemy.select([dbTables.FileSpace]).where(dbTables.FileSpace.storage_name == fs_name))
        fs = fs.fetchone()
        time_is = datetime.datetime.strptime(strftime("%d.%m.%Y", gmtime()), "%d.%m.%Y").date()
        time_is = time_is + datetime.timedelta(days=365)
        date_max = time_is.strftime("%d.%m.%Y")
        id_new = db_connection.session.execute(sqlalchemy.func.count(dbTables.Users.id)).fetchone()[0] + 1
        password_hash = str(sha256(form.data['password']+str(id_new)).hexdigest())
        # create new user
        new_user = dbTables.Users(form.data['login'], form.data['fullname'], password_hash, form.data['email'], date_max, 1, 2, fs.id)
        db_connection.session.add(new_user)
        db_connection.session.commit()
        return redirect(url_for('success'))
    return render_template('sign-up.html', title=u"Регистрация", form=form)

@app.route('/sign-in', methods=('GET', 'POST'))
def sign_in():
    return render_template('sign-in.html', title=u"Аутентификация")

@app.route('/forgot-password', methods=('GET', 'POST'))
def forgot_password():
    return render_template('forgot-password.html', title=u"Восстановление доступа")

Prompt:
Add routes for other pages

from flask import render_template
from flask_app import app

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


#!/usr/bin/env python

from os.path import exists
from setuptools import setup
import dask

extras_require = {
  'array': ['numpy', 'toolz >= 0.7.2'],
  'bag': ['cloudpickle', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
  'dataframe': ['numpy', 'pandas >= 0.16.0', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
  'imperative': ['toolz >= 0.7.2'],
}
extras_require['complete'] = sorted(set(sum(extras_require.values(), [])))

setup(name='dask',
      version=dask.__version__,
      description='Minimal task scheduling abstraction',
      url='http://github.com/dask/dask/',
      maintainer='Matthew Rocklin',
      maintainer_email='mrocklin@gmail.com',
      license='BSD',
      keywords='task-scheduling parallelism',
      packages=['dask', 'dask.array', 'dask.bag', 'dask.store',
                'dask.dataframe', 'dask.diagnostics'],
      long_description=(open('README.rst').read() if exists('README.rst')
                        else ''),
      extras_require=extras_require,
      zip_safe=False)

Response:
<REPLACE_OLD> 0.3.2'],
}
extras_require['complete'] <REPLACE_NEW> 0.3.2'],
  'imperative': ['toolz >= 0.7.2'],
}
extras_require['complete'] <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from os.path import exists
from setuptools import setup
import dask

extras_require = {
  'array': ['numpy', 'toolz >= 0.7.2'],
  'bag': ['cloudpickle', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
  'dataframe': ['numpy', 'pandas >= 0.16.0', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
  'imperative': ['toolz >= 0.7.2'],
}
extras_require['complete'] = sorted(set(sum(extras_require.values(), [])))

setup(name='dask',
      version=dask.__version__,
      description='Minimal task scheduling abstraction',
      url='http://github.com/dask/dask/',
      maintainer='Matthew Rocklin',
      maintainer_email='mrocklin@gmail.com',
      license='BSD',
      keywords='task-scheduling parallelism',
      packages=['dask', 'dask.array', 'dask.bag', 'dask.store',
                'dask.dataframe', 'dask.diagnostics'],
      long_description=(open('README.rst').read() if exists('README.rst')
                        else ''),
      extras_require=extras_require,
      zip_safe=False)

Prompt:
Add dep on toolz 0.7.2 for imperative extra

#!/usr/bin/env python

from os.path import exists
from setuptools import setup
import dask

extras_require = {
  'array': ['numpy', 'toolz >= 0.7.2'],
  'bag': ['cloudpickle', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
  'dataframe': ['numpy', 'pandas >= 0.16.0', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
}
extras_require['complete'] = sorted(set(sum(extras_require.values(), [])))

setup(name='dask',
      version=dask.__version__,
      description='Minimal task scheduling abstraction',
      url='http://github.com/dask/dask/',
      maintainer='Matthew Rocklin',
      maintainer_email='mrocklin@gmail.com',
      license='BSD',
      keywords='task-scheduling parallelism',
      packages=['dask', 'dask.array', 'dask.bag', 'dask.store',
                'dask.dataframe', 'dask.diagnostics'],
      long_description=(open('README.rst').read() if exists('README.rst')
                        else ''),
      extras_require=extras_require,
      zip_safe=False)


from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading

class OutputFileQueue(object):

    def __init__(self, fp):
        self.fp = fp
        self.lock = threading.RLock()

    def enqueue(self, coord):
        with self.lock:
            payload = serialize_coord(coord)
            self.fp.write(payload + '\n')

    def enqueue_batch(self, coords):
        n = 0
        for coord in coords:
            self.enqueue(coord)
            n += 1
        return n, 0

    def read(self, max_to_read=1, timeout_seconds=20):
        with self.lock:
            coords = []
            for _ in range(max_to_read):
                try:
                    coord = next(self.fp)
                except StopIteration:
                    break
                coords.append(CoordMessage(deserialize_coord(coord), None))

        return coords

    def job_done(self, coord_message):
        pass

    def clear(self):
        with self.lock:
            self.fp.seek(0)
            self.fp.truncate()
            return -1

    def close(self):
        with self.lock:
            remaining_queue = "".join([ln for ln in self.fp])
            self.clear()
            self.fp.write(remaining_queue)
            self.fp.close()

Response:
<REPLACE_OLD> self._lock <REPLACE_NEW> self.lock <REPLACE_END> <REPLACE_OLD> self._lock:
 <REPLACE_NEW> self.lock:
 <REPLACE_END> <REPLACE_OLD> self._lock:
 <REPLACE_NEW> self.lock:
 <REPLACE_END> <REPLACE_OLD> self._lock:
 <REPLACE_NEW> self.lock:
 <REPLACE_END> <REPLACE_OLD> self._lock:
 <REPLACE_NEW> self.lock:
 <REPLACE_END> <|endoftext|> from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading

class OutputFileQueue(object):

    def __init__(self, fp):
        self.fp = fp
        self.lock = threading.RLock()

    def enqueue(self, coord):
        with self.lock:
            payload = serialize_coord(coord)
            self.fp.write(payload + '\n')

    def enqueue_batch(self, coords):
        n = 0
        for coord in coords:
            self.enqueue(coord)
            n += 1
        return n, 0

    def read(self, max_to_read=1, timeout_seconds=20):
        with self.lock:
            coords = []
            for _ in range(max_to_read):
                try:
                    coord = next(self.fp)
                except StopIteration:
                    break
                coords.append(CoordMessage(deserialize_coord(coord), None))

        return coords

    def job_done(self, coord_message):
        pass

    def clear(self):
        with self.lock:
            self.fp.seek(0)
            self.fp.truncate()
            return -1

    def close(self):
        with self.lock:
            remaining_queue = "".join([ln for ln in self.fp])
            self.clear()
            self.fp.write(remaining_queue)
            self.fp.close()

Prompt:
Revert "Rename lock to _lock to imply that it's private."

tilequeue/queue/file.py
	-On second thought, the convention of prefixing private instance
	variables with an underscore isn't consistently adhered to
	elsewhere in the codebase, so don't bother using it, or we'll
	end up with a mix of classes that do and don't use it.

This reverts commit 4417b3c701e44fbf94fb7375a7a3f148f1ee6112.

from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading

class OutputFileQueue(object):

    def __init__(self, fp):
        self.fp = fp
        self._lock = threading.RLock()

    def enqueue(self, coord):
        with self._lock:
            payload = serialize_coord(coord)
            self.fp.write(payload + '\n')

    def enqueue_batch(self, coords):
        n = 0
        for coord in coords:
            self.enqueue(coord)
            n += 1
        return n, 0

    def read(self, max_to_read=1, timeout_seconds=20):
        with self._lock:
            coords = []
            for _ in range(max_to_read):
                try:
                    coord = next(self.fp)
                except StopIteration:
                    break
                coords.append(CoordMessage(deserialize_coord(coord), None))

        return coords

    def job_done(self, coord_message):
        pass

    def clear(self):
        with self._lock:
            self.fp.seek(0)
            self.fp.truncate()
            return -1

    def close(self):
        with self._lock:
            remaining_queue = "".join([ln for ln in self.fp])
            self.clear()
            self.fp.write(remaining_queue)
            self.fp.close()