""" Class to encapsulate a message """

import logging

class Message:
    """ A message object """

    def __init__(self, text, user, room, connector):
        """ Create object with minimum properties """
        self.text = text
        self.user = user
        self.room = room
        self.connector = connector
        self.regex = None

    def respond(self, text):
        """ Respond to this message using the connector it was created by """
        self.text = text
        self.connector.respond(self)

Make regex a None property

Make regex a None property

Response:
<REPLACE_OLD> connector

 <REPLACE_NEW> connector
        self.regex = None

 <REPLACE_END> <|endoftext|> """ Class to encapsulate a message """

import logging

class Message:
    """ A message object """

    def __init__(self, text, user, room, connector):
        """ Create object with minimum properties """
        self.text = text
        self.user = user
        self.room = room
        self.connector = connector
        self.regex = None

    def respond(self, text):
        """ Respond to this message using the connector it was created by """
        self.text = text
        self.connector.respond(self)

Prompt:
Make regex a None property

""" Class to encapsulate a message """

import logging

class Message:
    """ A message object """

    def __init__(self, text, user, room, connector):
        """ Create object with minimum properties """
        self.text = text
        self.user = user
        self.room = room
        self.connector = connector

    def respond(self, text):
        """ Respond to this message using the connector it was created by """
        self.text = text
        self.connector.respond(self)


import asyncio
import os
import socket
import tempfile
import uvloop

from uvloop import _testbase as tb

class _TestUnix:
    def test_create_server_1(self):
        CNT = 0           # number of clients that were successful
        TOTAL_CNT = 100   # total number of clients that test will create
        TIMEOUT = 5.0     # timeout for this test

        async def handle_client(reader, writer):
            nonlocal CNT

            data = await reader.readexactly(4)
            self.assertEqual(data, b'AAAA')
            writer.write(b'OK')

            data = await reader.readexactly(4)
            self.assertEqual(data, b'BBBB')
            writer.write(b'SPAM')

            await writer.drain()
            writer.close()

            CNT += 1

        async def test_client(addr):
            sock = socket.socket(socket.AF_UNIX)
            with sock:
                sock.setblocking(False)
                await self.loop.sock_connect(sock, addr)

                await self.loop.sock_sendall(sock, b'AAAA')
                data = await self.loop.sock_recv(sock, 2)
                self.assertEqual(data, b'OK')

                await self.loop.sock_sendall(sock, b'BBBB')
                data = await self.loop.sock_recv(sock, 4)
                self.assertEqual(data, b'SPAM')

        async def start_server():
            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')
                try:
                    srv = await asyncio.start_unix_server(
                        handle_client,
                        sock_name,
                        loop=self.loop)

                    try:
                        srv_socks = srv.sockets
                        self.assertTrue(srv_socks)

                        tasks = []
                        for _ in range(TOTAL_CNT):
                            tasks.append(test_client(sock_name))

                        try:
                            await asyncio.wait_for(
                                asyncio.gather(*tasks, loop=self.loop),
                                TIMEOUT, loop=self.loop)
                        finally:
                            self.loop.stop()

                    finally:
                        srv.close()

                        # Check that the server cleaned-up proxy-sockets
                        for srv_sock in srv_socks:
                            self.assertEqual(srv_sock.fileno(), -1)

                except:
                    self.loop.stop()  # We don't want this test to stuck when
                                      # it fails.
                    raise

        self.loop.create_task(start_server())
        self.loop.run_forever()
        self.assertEqual(CNT, TOTAL_CNT)

class Test_UV_Unix(_TestUnix, tb.UVTestCase):
    pass

class Test_AIO_Unix(_TestUnix, tb.AIOTestCase):
    pass

Add a test for loop.create_unix_server

tests: Add a test for loop.create_unix_server

Response:
<REPLACE_OLD>  <REPLACE_NEW> import asyncio
import os
import socket
import tempfile
import uvloop

from uvloop import _testbase as tb

class _TestUnix:
    def test_create_server_1(self):
        CNT = 0           # number of clients that were successful
        TOTAL_CNT = 100   # total number of clients that test will create
        TIMEOUT = 5.0     # timeout for this test

        async def handle_client(reader, writer):
            nonlocal CNT

            data = await reader.readexactly(4)
            self.assertEqual(data, b'AAAA')
            writer.write(b'OK')

            data = await reader.readexactly(4)
            self.assertEqual(data, b'BBBB')
            writer.write(b'SPAM')

            await writer.drain()
            writer.close()

            CNT += 1

        async def test_client(addr):
            sock = socket.socket(socket.AF_UNIX)
            with sock:
                sock.setblocking(False)
                await self.loop.sock_connect(sock, addr)

                await self.loop.sock_sendall(sock, b'AAAA')
                data = await self.loop.sock_recv(sock, 2)
                self.assertEqual(data, b'OK')

                await self.loop.sock_sendall(sock, b'BBBB')
                data = await self.loop.sock_recv(sock, 4)
                self.assertEqual(data, b'SPAM')

        async def start_server():
            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')
                try:
                    srv = await asyncio.start_unix_server(
                        handle_client,
                        sock_name,
                        loop=self.loop)

                    try:
                        srv_socks = srv.sockets
                        self.assertTrue(srv_socks)

                        tasks = []
                        for _ in range(TOTAL_CNT):
                            tasks.append(test_client(sock_name))

                        try:
                            await asyncio.wait_for(
                                asyncio.gather(*tasks, loop=self.loop),
                                TIMEOUT, loop=self.loop)
                        finally:
                            self.loop.stop()

                    finally:
                        srv.close()

                        # Check that the server cleaned-up proxy-sockets
                        for srv_sock in srv_socks:
                            self.assertEqual(srv_sock.fileno(), -1)

                except:
                    self.loop.stop()  # We don't want this test to stuck when
                                      # it fails.
                    raise

        self.loop.create_task(start_server())
        self.loop.run_forever()
        self.assertEqual(CNT, TOTAL_CNT)

class Test_UV_Unix(_TestUnix, tb.UVTestCase):
    pass

class Test_AIO_Unix(_TestUnix, tb.AIOTestCase):
    pass
 <REPLACE_END> <|endoftext|> import asyncio
import os
import socket
import tempfile
import uvloop

from uvloop import _testbase as tb

class _TestUnix:
    def test_create_server_1(self):
        CNT = 0           # number of clients that were successful
        TOTAL_CNT = 100   # total number of clients that test will create
        TIMEOUT = 5.0     # timeout for this test

        async def handle_client(reader, writer):
            nonlocal CNT

            data = await reader.readexactly(4)
            self.assertEqual(data, b'AAAA')
            writer.write(b'OK')

            data = await reader.readexactly(4)
            self.assertEqual(data, b'BBBB')
            writer.write(b'SPAM')

            await writer.drain()
            writer.close()

            CNT += 1

        async def test_client(addr):
            sock = socket.socket(socket.AF_UNIX)
            with sock:
                sock.setblocking(False)
                await self.loop.sock_connect(sock, addr)

                await self.loop.sock_sendall(sock, b'AAAA')
                data = await self.loop.sock_recv(sock, 2)
                self.assertEqual(data, b'OK')

                await self.loop.sock_sendall(sock, b'BBBB')
                data = await self.loop.sock_recv(sock, 4)
                self.assertEqual(data, b'SPAM')

        async def start_server():
            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')
                try:
                    srv = await asyncio.start_unix_server(
                        handle_client,
                        sock_name,
                        loop=self.loop)

                    try:
                        srv_socks = srv.sockets
                        self.assertTrue(srv_socks)

                        tasks = []
                        for _ in range(TOTAL_CNT):
                            tasks.append(test_client(sock_name))

                        try:
                            await asyncio.wait_for(
                                asyncio.gather(*tasks, loop=self.loop),
                                TIMEOUT, loop=self.loop)
                        finally:
                            self.loop.stop()

                    finally:
                        srv.close()

                        # Check that the server cleaned-up proxy-sockets
                        for srv_sock in srv_socks:
                            self.assertEqual(srv_sock.fileno(), -1)

                except:
                    self.loop.stop()  # We don't want this test to stuck when
                                      # it fails.
                    raise

        self.loop.create_task(start_server())
        self.loop.run_forever()
        self.assertEqual(CNT, TOTAL_CNT)

class Test_UV_Unix(_TestUnix, tb.UVTestCase):
    pass

class Test_AIO_Unix(_TestUnix, tb.AIOTestCase):
    pass

Prompt: tests: Add a test for loop.create_unix_server


from .simple_broker import (_DataBrokerClass, EventQueue, Header,
                            LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers

DataBroker = _DataBrokerClass()  # singleton
register_builtin_handlers()

Add Errors to the public API.

DOC: Add Errors to the public API.

Response:
<REPLACE_OLD> _DataBrokerClass, <REPLACE_NEW> (_DataBrokerClass, <REPLACE_END> <REPLACE_OLD> Header
from <REPLACE_NEW> Header,
                            LocationError, IntegrityError)
from <REPLACE_END> <|endoftext|> from .simple_broker import (_DataBrokerClass, EventQueue, Header,
                            LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers

DataBroker = _DataBrokerClass()  # singleton
register_builtin_handlers()

Prompt:
DOC: Add Errors to the public API.

from .simple_broker import _DataBrokerClass, EventQueue, Header
from .handler_registration import register_builtin_handlers

DataBroker = _DataBrokerClass()  # singleton
register_builtin_handlers()


import pytest
from schematics.models import Model
from schematics.types import IntType

from hyp.adapters.schematics import SchematicsSerializerAdapter

class Post(object):
    def __init__(self):
        self.id = 1

class Simple(Model):
    id = IntType()

@pytest.fixture
def adapter():
    return SchematicsSerializerAdapter(Simple)

def test_object_conversion(adapter):
    assert adapter.to_primitive(Post())['id'] == 1

def test_dict_conversion(adapter):
    adapter = SchematicsSerializerAdapter(Simple)
    assert adapter.to_primitive({'id': 1})['id'] == 1

Response:
<REPLACE_OLD> from <REPLACE_NEW> import pytest
from <REPLACE_END> <REPLACE_OLD> IntType()

def test_object_conversion():
 <REPLACE_NEW> IntType()

@pytest.fixture
def adapter():
 <REPLACE_END> <REPLACE_OLD> adapter = SchematicsSerializerAdapter(Simple)
 <REPLACE_NEW> return SchematicsSerializerAdapter(Simple)

def test_object_conversion(adapter):
 <REPLACE_END> <REPLACE_OLD> test_dict_conversion():
 <REPLACE_NEW> test_dict_conversion(adapter):
 <REPLACE_END> <|endoftext|> import pytest
from schematics.models import Model
from schematics.types import IntType

from hyp.adapters.schematics import SchematicsSerializerAdapter

class Post(object):
    def __init__(self):
        self.id = 1

class Simple(Model):
    id = IntType()

@pytest.fixture
def adapter():
    return SchematicsSerializerAdapter(Simple)

def test_object_conversion(adapter):
    assert adapter.to_primitive(Post())['id'] == 1

def test_dict_conversion(adapter):
    adapter = SchematicsSerializerAdapter(Simple)
    assert adapter.to_primitive({'id': 1})['id'] == 1

Prompt:
Convert the adapter into a pytest fixture

from schematics.models import Model
from schematics.types import IntType

from hyp.adapters.schematics import SchematicsSerializerAdapter

class Post(object):
    def __init__(self):
        self.id = 1

class Simple(Model):
    id = IntType()

def test_object_conversion():
    adapter = SchematicsSerializerAdapter(Simple)
    assert adapter.to_primitive(Post())['id'] == 1

def test_dict_conversion():
    adapter = SchematicsSerializerAdapter(Simple)
    assert adapter.to_primitive({'id': 1})['id'] == 1


__all__ = []

from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer

class Featx(Feats):
    def __init__(self, root, name):
        Feats.__init__(self, root, name)

    def get_slide_feats(self):
        ss = Slider(self.root, self.name)
        imgl = ss.get_slides(None, gray=True, resize=True)
        self.feats(imgl, prefix="s")

    def get_frame_feats(self):
        rr = Reducer(self.root, self.name)
        vv = Video(self.root, self.name)
        imgl = vv.get_frames(rr.frame_ids(), gray=True)
        self.feats(imgl, prefix="f")

    def load_feats(self, key):
        fd = self.load(key)
        if fd is None:
            return []
        return fd

    def get_feats_pair(self, sid, fid):
        """
        Get features by given `slide`, `frame` pairs
        """
        sk = self.load_feats("s_{:03d}_kps".format(sid))
        sd = self.load_feats("s_{:03d}_des".format(sid))
        fk = self.load_feats("f_{:03d}_kps".format(fid))
        fd = self.load_feats("f_{:03d}_des".format(fid))
        return dict(sk=sk, sd=sd, fk=fk, fd=fd)

Load feats with zero length

Load feats with zero length

Response:
<INSERT>    def load_feats(self, key):
        fd = self.load(key)
        if fd is None:
            return []
        return fd

 <INSERT_END> <REPLACE_OLD> self.load("s_{:03d}_kps".format(sid))
 <REPLACE_NEW> self.load_feats("s_{:03d}_kps".format(sid))
 <REPLACE_END> <REPLACE_OLD> self.load("s_{:03d}_des".format(sid))
 <REPLACE_NEW> self.load_feats("s_{:03d}_des".format(sid))
 <REPLACE_END> <REPLACE_OLD> self.load("f_{:03d}_kps".format(fid))
 <REPLACE_NEW> self.load_feats("f_{:03d}_kps".format(fid))
 <REPLACE_END> <REPLACE_OLD> self.load("f_{:03d}_des".format(fid))
 <REPLACE_NEW> self.load_feats("f_{:03d}_des".format(fid))
 <REPLACE_END> <|endoftext|> __all__ = []

from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer

class Featx(Feats):
    def __init__(self, root, name):
        Feats.__init__(self, root, name)

    def get_slide_feats(self):
        ss = Slider(self.root, self.name)
        imgl = ss.get_slides(None, gray=True, resize=True)
        self.feats(imgl, prefix="s")

    def get_frame_feats(self):
        rr = Reducer(self.root, self.name)
        vv = Video(self.root, self.name)
        imgl = vv.get_frames(rr.frame_ids(), gray=True)
        self.feats(imgl, prefix="f")

    def load_feats(self, key):
        fd = self.load(key)
        if fd is None:
            return []
        return fd

    def get_feats_pair(self, sid, fid):
        """
        Get features by given `slide`, `frame` pairs
        """
        sk = self.load_feats("s_{:03d}_kps".format(sid))
        sd = self.load_feats("s_{:03d}_des".format(sid))
        fk = self.load_feats("f_{:03d}_kps".format(fid))
        fd = self.load_feats("f_{:03d}_des".format(fid))
        return dict(sk=sk, sd=sd, fk=fk, fd=fd)

Prompt:
Load feats with zero length

__all__ = []

from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer

class Featx(Feats):
    def __init__(self, root, name):
        Feats.__init__(self, root, name)

    def get_slide_feats(self):
        ss = Slider(self.root, self.name)
        imgl = ss.get_slides(None, gray=True, resize=True)
        self.feats(imgl, prefix="s")

    def get_frame_feats(self):
        rr = Reducer(self.root, self.name)
        vv = Video(self.root, self.name)
        imgl = vv.get_frames(rr.frame_ids(), gray=True)
        self.feats(imgl, prefix="f")

    def get_feats_pair(self, sid, fid):
        """
        Get features by given `slide`, `frame` pairs
        """
        sk = self.load("s_{:03d}_kps".format(sid))
        sd = self.load("s_{:03d}_des".format(sid))
        fk = self.load("f_{:03d}_kps".format(fid))
        fd = self.load("f_{:03d}_des".format(fid))
        return dict(sk=sk, sd=sd, fk=fk, fd=fd)


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

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Token',
            fields=[
                ('key', models.CharField(primary_key=True, serialize=False, max_length=40)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]

Response:
<REPLACE_OLD>
from <REPLACE_NEW> # -*- coding: utf-8 -*-
from <REPLACE_END> <REPLACE_OLD> models.CharField(max_length=40, <REPLACE_NEW> models.CharField(primary_key=True, <REPLACE_END> <REPLACE_OLD> primary_key=True)),
 <REPLACE_NEW> max_length=40)),
 <REPLACE_END> <REPLACE_OLD> models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)),
 <REPLACE_NEW> models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')),
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Token',
            fields=[
                ('key', models.CharField(primary_key=True, serialize=False, max_length=40)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]

Prompt:
Update initial migration to work on Python 3

from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Token',
            fields=[
                ('key', models.CharField(max_length=40, serialize=False, primary_key=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


class Node(object):
    def __init__(self, val, prev=None, next_=None):
        self.val = val
        self.prev = prev
        self.next = next_

    def __repr__(self):
        return '{val}'.format(val=self.val)

class DoublLinkedList(object):
    def __init__(self, iterable=()):
        self._current = None
        self.head = None
        self.tail = None
        self.length = 0
        for val in reversed(iterable):
            self.insert(val)

    def __repr__(self):
        node = self.head
        output = ''
        for node in self:
            output += '{!r}, '.format(node.val)
        return '({})'.format(output.rstrip(' ,'))

    def __len__(self):
        return self.length

    def __iter__(self):
        if self.head is not None:
            self._current = self.head
        return self

    def next(self):
        pass

    def size(self):
        pass

    def search(self, search):
        pass

    def remove(self, search):
        pass

    def insert(self, val):
        pass

    def append(self, val):
        pass

    def pop(self):
        pass

    def shift(self):
        pass

    def display(self):
        ''''''
        return repr(self)

Add structure and methods to double linked list.

Response:
<REPLACE_OLD>  <REPLACE_NEW> class Node(object):
    def __init__(self, val, prev=None, next_=None):
        self.val = val
        self.prev = prev
        self.next = next_

    def __repr__(self):
        return '{val}'.format(val=self.val)

class DoublLinkedList(object):
    def __init__(self, iterable=()):
        self._current = None
        self.head = None
        self.tail = None
        self.length = 0
        for val in reversed(iterable):
            self.insert(val)

    def __repr__(self):
        node = self.head
        output = ''
        for node in self:
            output += '{!r}, '.format(node.val)
        return '({})'.format(output.rstrip(' ,'))

    def __len__(self):
        return self.length

    def __iter__(self):
        if self.head is not None:
            self._current = self.head
        return self

    def next(self):
        pass

    def size(self):
        pass

    def search(self, search):
        pass

    def remove(self, search):
        pass

    def insert(self, val):
        pass

    def append(self, val):
        pass

    def pop(self):
        pass

    def shift(self):
        pass

    def display(self):
        ''''''
        return repr(self)
 <REPLACE_END> <|endoftext|> class Node(object):
    def __init__(self, val, prev=None, next_=None):
        self.val = val
        self.prev = prev
        self.next = next_

    def __repr__(self):
        return '{val}'.format(val=self.val)

class DoublLinkedList(object):
    def __init__(self, iterable=()):
        self._current = None
        self.head = None
        self.tail = None
        self.length = 0
        for val in reversed(iterable):
            self.insert(val)

    def __repr__(self):
        node = self.head
        output = ''
        for node in self:
            output += '{!r}, '.format(node.val)
        return '({})'.format(output.rstrip(' ,'))

    def __len__(self):
        return self.length

    def __iter__(self):
        if self.head is not None:
            self._current = self.head
        return self

    def next(self):
        pass

    def size(self):
        pass

    def search(self, search):
        pass

    def remove(self, search):
        pass

    def insert(self, val):
        pass

    def append(self, val):
        pass

    def pop(self):
        pass

    def shift(self):
        pass

    def display(self):
        ''''''
        return repr(self)

Prompt: Add structure and methods to double linked list.


from .default import *  # NOQA

#
# Django Development
# ..........................

DEBUG = True
TEMPLATE_DEBUG = True

SOUTH_TESTS_MIGRATE = False  # Tested at settings.tests

#
# Developper Toolbar
# ..........................

INSTALLED_APPS = (
    # 'debug_toolbar',
    'django_extensions',
) + INSTALLED_APPS

#
# Use some default tiles
# ..........................

LEAFLET_CONFIG['TILES'] = [
    (gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
    (gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
    (gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]

LEAFLET_CONFIG['SRID'] = 3857

LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Response:
<REPLACE_OLD> 'DEBUG'
 <REPLACE_NEW> 'DEBUG'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
 <REPLACE_END> <|endoftext|> from .default import *  # NOQA

#
# Django Development
# ..........................

DEBUG = True
TEMPLATE_DEBUG = True

SOUTH_TESTS_MIGRATE = False  # Tested at settings.tests

#
# Developper Toolbar
# ..........................

INSTALLED_APPS = (
    # 'debug_toolbar',
    'django_extensions',
) + INSTALLED_APPS

#
# Use some default tiles
# ..........................

LEAFLET_CONFIG['TILES'] = [
    (gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
    (gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
    (gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]

LEAFLET_CONFIG['SRID'] = 3857

LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Prompt:
Set up console email backend in debug mode

from .default import *  # NOQA

#
# Django Development
# ..........................

DEBUG = True
TEMPLATE_DEBUG = True

SOUTH_TESTS_MIGRATE = False  # Tested at settings.tests

#
# Developper Toolbar
# ..........................

INSTALLED_APPS = (
    # 'debug_toolbar',
    'django_extensions',
) + INSTALLED_APPS

#
# Use some default tiles
# ..........................

LEAFLET_CONFIG['TILES'] = [
    (gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
    (gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
    (gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]

LEAFLET_CONFIG['SRID'] = 3857

LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'


import time

def is_sorted(l):
  return all(l[i] <= l[i+1] for i in xrange(len(l)-1))

def is_strictly_sorted(l):
  return all(l[i] < l[i+1] for i in xrange(len(l)-1))

def timestamp_string():
  return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())

def find(f, seq):
  """Return first item in sequence where f(item) == True."""
  for item in seq:
    if f(item):
      return item

def find_index(f, seq):
  """Return the index of the first item in sequence where f(item) == True."""
  for index, item in enumerate(seq):
    if f(item):
      return index

Response:
<INSERT> is_sorted(l):
  return all(l[i] <= l[i+1] for i in xrange(len(l)-1))

def is_strictly_sorted(l):
  return all(l[i] < l[i+1] for i in xrange(len(l)-1))

def <INSERT_END> <|endoftext|> import time

def is_sorted(l):
  return all(l[i] <= l[i+1] for i in xrange(len(l)-1))

def is_strictly_sorted(l):
  return all(l[i] < l[i+1] for i in xrange(len(l)-1))

def timestamp_string():
  return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())

def find(f, seq):
  """Return first item in sequence where f(item) == True."""
  for item in seq:
    if f(item):
      return item

def find_index(f, seq):
  """Return the index of the first item in sequence where f(item) == True."""
  for index, item in enumerate(seq):
    if f(item):
      return index

Prompt:
Add little functions for checking if a list is sorted without sorting it

import time

def timestamp_string():
  return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())

def find(f, seq):
  """Return first item in sequence where f(item) == True."""
  for item in seq:
    if f(item):
      return item

def find_index(f, seq):
  """Return the index of the first item in sequence where f(item) == True."""
  for index, item in enumerate(seq):
    if f(item):
      return index


from options import *

test = { INPUT : 'catch_release.i',
         EXODIFF : ['catch_release_out.e'],
         SKIP : 'temp'
       }

Response:
<REPLACE_OLD> ['catch_release_out.e']}

 <REPLACE_NEW> ['catch_release_out.e'],
         SKIP : 'temp'
       }

 <REPLACE_END> <|endoftext|> from options import *

test = { INPUT : 'catch_release.i',
         EXODIFF : ['catch_release_out.e'],
         SKIP : 'temp'
       }

Prompt:
Test passes on my machine, dies on others. Skipping for now.

r8830

from options import *

test = { INPUT : 'catch_release.i',
         EXODIFF : ['catch_release_out.e']}


from operator import mul
import heapq
class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        largest3 = heapq.nlargest(3, nums)
        smallest3 = heapq.nsmallest(3, nums)
        if largest3[0] <= 0:
            if largest3[0] == 0:
                return 0
            else:
                return reduce(mul, largest3)
        elif largest3[1] <= 0:
            if smallest3[1] < 0:
                return smallest3[0] * smallest3[1] * largest3[0]
            else:
                return 0
        elif largest3[2] <= 0:
            if smallest3[1] < 0:
                return smallest3[0] * smallest3[1] * largest3[0]
            else:
                return reduce(mul, largest3)
        else:
            if smallest3[1] < 0:
                return max(smallest3[0] * smallest3[1] * largest3[0], reduce(mul, largest3))
            else:
                return reduce(mul, largest3)

Add py solution for 628. Maximum Product of Three Numbers

628. Maximum Product of Three Numbers: https://leetcode.com/problems/maximum-product-of-three-numbers/

Response:
<REPLACE_OLD>  <REPLACE_NEW> from operator import mul
import heapq
class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        largest3 = heapq.nlargest(3, nums)
        smallest3 = heapq.nsmallest(3, nums)
        if largest3[0] <= 0:
            if largest3[0] == 0:
                return 0
            else:
                return reduce(mul, largest3)
        elif largest3[1] <= 0:
            if smallest3[1] < 0:
                return smallest3[0] * smallest3[1] * largest3[0]
            else:
                return 0
        elif largest3[2] <= 0:
            if smallest3[1] < 0:
                return smallest3[0] * smallest3[1] * largest3[0]
            else:
                return reduce(mul, largest3)
        else:
            if smallest3[1] < 0:
                return max(smallest3[0] * smallest3[1] * largest3[0], reduce(mul, largest3))
            else:
                return reduce(mul, largest3)

 <REPLACE_END> <|endoftext|> from operator import mul
import heapq
class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        largest3 = heapq.nlargest(3, nums)
        smallest3 = heapq.nsmallest(3, nums)
        if largest3[0] <= 0:
            if largest3[0] == 0:
                return 0
            else:
                return reduce(mul, largest3)
        elif largest3[1] <= 0:
            if smallest3[1] < 0:
                return smallest3[0] * smallest3[1] * largest3[0]
            else:
                return 0
        elif largest3[2] <= 0:
            if smallest3[1] < 0:
                return smallest3[0] * smallest3[1] * largest3[0]
            else:
                return reduce(mul, largest3)
        else:
            if smallest3[1] < 0:
                return max(smallest3[0] * smallest3[1] * largest3[0], reduce(mul, largest3))
            else:
                return reduce(mul, largest3)

Prompt:
Add py solution for 628. Maximum Product of Three Numbers

628. Maximum Product of Three Numbers: https://leetcode.com/problems/maximum-product-of-three-numbers/


from lib.constants.test import create_new_program
from lib.page import dashboard
from lib import base

class TestProgramPage(base.Test):
    def create_private_program_test(self):
        dashboard_page = dashboard.DashboardPage(self.driver)
        dashboard_page.navigate_to()
        lhn_menu = dashboard_page.open_lhn_menu()
        lhn_menu.select_all_objects()
        program_dropdown = lhn_menu.open_programs()
        new_program_page = program_dropdown.open_create_new_program()
        new_program_page.enter_title(create_new_program.TEST_TITLE)
        new_program_page.enter_description(create_new_program.TEST_DESCRIPTION)
        new_program_page.enter_notes(create_new_program.TEST_NOTES)
        new_program_page.enter_code(create_new_program.TEST_CODE)
        new_program_page.checkbox_check_private_program()
        new_program_page.enter_primary_contact(
            create_new_program.TEST_PRIMARY_CONTACT
        )
        new_program_page.enter_secondary_contact(
            create_new_program.TEST_SECONDARY_CONTACT
        )
        new_program_page.enter_program_url(create_new_program.TEST_PROGRAM_URL)
        new_program_page.enter_reference_url(
            create_new_program.TEST_REFERENCE_URL
        )
        new_program_page.enter_effective_date_start_month()
        new_program_page.enter_stop_date_end_month()
        new_program_page.save_and_close()

Fix import error for program page test

Fix import error for program page test

Response:
<INSERT> lib.page import dashboard
from <INSERT_END> <REPLACE_OLD> base, page

class <REPLACE_NEW> base

class <REPLACE_END> <REPLACE_OLD> dashboard = page.dashboard.DashboardPage(self.driver)
        dashboard.navigate_to()
 <REPLACE_NEW> dashboard_page = dashboard.DashboardPage(self.driver)
        dashboard_page.navigate_to()
 <REPLACE_END> <REPLACE_OLD> dashboard.open_lhn_menu()
 <REPLACE_NEW> dashboard_page.open_lhn_menu()
 <REPLACE_END> <|endoftext|> from lib.constants.test import create_new_program
from lib.page import dashboard
from lib import base

class TestProgramPage(base.Test):
    def create_private_program_test(self):
        dashboard_page = dashboard.DashboardPage(self.driver)
        dashboard_page.navigate_to()
        lhn_menu = dashboard_page.open_lhn_menu()
        lhn_menu.select_all_objects()
        program_dropdown = lhn_menu.open_programs()
        new_program_page = program_dropdown.open_create_new_program()
        new_program_page.enter_title(create_new_program.TEST_TITLE)
        new_program_page.enter_description(create_new_program.TEST_DESCRIPTION)
        new_program_page.enter_notes(create_new_program.TEST_NOTES)
        new_program_page.enter_code(create_new_program.TEST_CODE)
        new_program_page.checkbox_check_private_program()
        new_program_page.enter_primary_contact(
            create_new_program.TEST_PRIMARY_CONTACT
        )
        new_program_page.enter_secondary_contact(
            create_new_program.TEST_SECONDARY_CONTACT
        )
        new_program_page.enter_program_url(create_new_program.TEST_PROGRAM_URL)
        new_program_page.enter_reference_url(
            create_new_program.TEST_REFERENCE_URL
        )
        new_program_page.enter_effective_date_start_month()
        new_program_page.enter_stop_date_end_month()
        new_program_page.save_and_close()

Prompt:
Fix import error for program page test

from lib.constants.test import create_new_program
from lib import base, page

class TestProgramPage(base.Test):
    def create_private_program_test(self):
        dashboard = page.dashboard.DashboardPage(self.driver)
        dashboard.navigate_to()
        lhn_menu = dashboard.open_lhn_menu()
        lhn_menu.select_all_objects()
        program_dropdown = lhn_menu.open_programs()
        new_program_page = program_dropdown.open_create_new_program()
        new_program_page.enter_title(create_new_program.TEST_TITLE)
        new_program_page.enter_description(create_new_program.TEST_DESCRIPTION)
        new_program_page.enter_notes(create_new_program.TEST_NOTES)
        new_program_page.enter_code(create_new_program.TEST_CODE)
        new_program_page.checkbox_check_private_program()
        new_program_page.enter_primary_contact(
            create_new_program.TEST_PRIMARY_CONTACT
        )
        new_program_page.enter_secondary_contact(
            create_new_program.TEST_SECONDARY_CONTACT
        )
        new_program_page.enter_program_url(create_new_program.TEST_PROGRAM_URL)
        new_program_page.enter_reference_url(
            create_new_program.TEST_REFERENCE_URL
        )
        new_program_page.enter_effective_date_start_month()
        new_program_page.enter_stop_date_end_month()
        new_program_page.save_and_close()


"""
Misc utility functions.
"""

import os.path

from dotfiles.compat import islink, realpath

def compare_path(path1, path2):
    return (realpath_expanduser(path1) == realpath_expanduser(path2))

def realpath_expanduser(path):
    return realpath(os.path.expanduser(path))

def is_link_to(path, target):
    def normalize(path):
        return os.path.normcase(os.path.normpath(path))
    return islink(path) and \
        normalize(realpath(path)) == normalize(realpath(target))

Response:
<REPLACE_OLD> normalize(target)

 <REPLACE_NEW> normalize(realpath(target))
 <REPLACE_END> <|endoftext|> """
Misc utility functions.
"""

import os.path

from dotfiles.compat import islink, realpath

def compare_path(path1, path2):
    return (realpath_expanduser(path1) == realpath_expanduser(path2))

def realpath_expanduser(path):
    return realpath(os.path.expanduser(path))

def is_link_to(path, target):
    def normalize(path):
        return os.path.normcase(os.path.normpath(path))
    return islink(path) and \
        normalize(realpath(path)) == normalize(realpath(target))

Prompt:
Fix link detection when target is itself a symlink

This shows up on OSX where /tmp is actually a symlink to /private/tmp.

"""
Misc utility functions.
"""

import os.path

from dotfiles.compat import islink, realpath

def compare_path(path1, path2):
    return (realpath_expanduser(path1) == realpath_expanduser(path2))

def realpath_expanduser(path):
    return realpath(os.path.expanduser(path))

def is_link_to(path, target):
    def normalize(path):
        return os.path.normcase(os.path.normpath(path))
    return islink(path) and \
        normalize(realpath(path)) == normalize(target)


"""
Various functions to dynamically import (abitrary names from) arbitrary files.

To import a file like it is a module, use `import_file`.
"""

from sys import version_info

def import_file(name, file):
    """
    Import `file` as a module with _name_.

    Raises an ImportError if it could not be imported.
    """
    if version_info > (3, 5):
        from importlib.util import module_from_spec, spec_from_file_location

        spec = spec_from_file_location(name, file)

        if not spec:
            raise ImportError("Could not import: '{}'".format(file))

        module = module_from_spec(spec)
        spec.loader.exec_module(module)
        return module

    else:
        raise ImportError("Dymport: unsupported Python version, could not "
                          "import '{}'".format(file))

Add check for supported Python versions

Response:
<REPLACE_OLD> importlib.util <REPLACE_NEW> sys <REPLACE_END> <REPLACE_OLD> module_from_spec, spec_from_file_location

def <REPLACE_NEW> version_info

def <REPLACE_END> <INSERT> if version_info > (3, 5):
        from importlib.util import module_from_spec, spec_from_file_location

        <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> module
 <REPLACE_NEW> module

    else:
        raise ImportError("Dymport: unsupported Python version, could not "
                          "import '{}'".format(file))
 <REPLACE_END> <|endoftext|> """
Various functions to dynamically import (abitrary names from) arbitrary files.

To import a file like it is a module, use `import_file`.
"""

from sys import version_info

def import_file(name, file):
    """
    Import `file` as a module with _name_.

    Raises an ImportError if it could not be imported.
    """
    if version_info > (3, 5):
        from importlib.util import module_from_spec, spec_from_file_location

        spec = spec_from_file_location(name, file)

        if not spec:
            raise ImportError("Could not import: '{}'".format(file))

        module = module_from_spec(spec)
        spec.loader.exec_module(module)
        return module

    else:
        raise ImportError("Dymport: unsupported Python version, could not "
                          "import '{}'".format(file))

Prompt:
Add check for supported Python versions

Not all Python versions are supported by this package, because the import
mechanism changes in the different Python versions.
If an unsupported Python version is used, an ImportError is raised.

"""
Various functions to dynamically import (abitrary names from) arbitrary files.

To import a file like it is a module, use `import_file`.
"""

from importlib.util import module_from_spec, spec_from_file_location

def import_file(name, file):
    """
    Import `file` as a module with _name_.

    Raises an ImportError if it could not be imported.
    """
    spec = spec_from_file_location(name, file)

    if not spec:
        raise ImportError("Could not import: '{}'".format(file))

    module = module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="mock-firestore",
    version="0.1.2",
    author="Matt Dowds",
    description="In-memory implementation of Google Cloud Firestore for use in tests",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/mdowds/mock-firestore",
    packages=setuptools.find_packages(),
    test_suite='',
    classifiers=[
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        "License :: OSI Approved :: MIT License",
    ],
)

Response:
<INSERT>    long_description_content_type="text/markdown",
 <INSERT_END> <|endoftext|> import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="mock-firestore",
    version="0.1.2",
    author="Matt Dowds",
    description="In-memory implementation of Google Cloud Firestore for use in tests",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/mdowds/mock-firestore",
    packages=setuptools.find_packages(),
    test_suite='',
    classifiers=[
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        "License :: OSI Approved :: MIT License",
    ],
)

Prompt:
Set description content type so it renders on PyPI

import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="mock-firestore",
    version="0.1.2",
    author="Matt Dowds",
    description="In-memory implementation of Google Cloud Firestore for use in tests",
    long_description=long_description,
    url="https://github.com/mdowds/mock-firestore",
    packages=setuptools.find_packages(),
    test_suite='',
    classifiers=[
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        "License :: OSI Approved :: MIT License",
    ],
)


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

class StockUpdater:

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

    def set_items(self, items):
        self.items = items

    def set_table(self, table):
        self.table = table

    def set_destination_colums(self, product_code, quantity):
        self.product_code_column = product_code
        self.quantity_column = quantity

    def update(self):
        # cursor.execute_many?
        for item in self.items:
            self.update_quantity(item['product_code'], item['quantity'])

    def update_quantity(self, product_code, quantity):
        query = "UPDATE {} SET {} = ? WHERE {} LIKE ?".format(
            self.table, self.quantity_column, self.product_code_column)
        cursor = self.db_connection.cursor()
        try:
            cursor.execute(query, (quantity, product_code))
            self.db_connection.commit()
        except Exception as err:
            raise err
        finally:
            cursor.close()

Add class for updating stock

Add class for updating stock

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# -*- coding: utf-8 -*-

class StockUpdater:

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

    def set_items(self, items):
        self.items = items

    def set_table(self, table):
        self.table = table

    def set_destination_colums(self, product_code, quantity):
        self.product_code_column = product_code
        self.quantity_column = quantity

    def update(self):
        # cursor.execute_many?
        for item in self.items:
            self.update_quantity(item['product_code'], item['quantity'])

    def update_quantity(self, product_code, quantity):
        query = "UPDATE {} SET {} = ? WHERE {} LIKE ?".format(
            self.table, self.quantity_column, self.product_code_column)
        cursor = self.db_connection.cursor()
        try:
            cursor.execute(query, (quantity, product_code))
            self.db_connection.commit()
        except Exception as err:
            raise err
        finally:
            cursor.close()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

class StockUpdater:

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

    def set_items(self, items):
        self.items = items

    def set_table(self, table):
        self.table = table

    def set_destination_colums(self, product_code, quantity):
        self.product_code_column = product_code
        self.quantity_column = quantity

    def update(self):
        # cursor.execute_many?
        for item in self.items:
            self.update_quantity(item['product_code'], item['quantity'])

    def update_quantity(self, product_code, quantity):
        query = "UPDATE {} SET {} = ? WHERE {} LIKE ?".format(
            self.table, self.quantity_column, self.product_code_column)
        cursor = self.db_connection.cursor()
        try:
            cursor.execute(query, (quantity, product_code))
            self.db_connection.commit()
        except Exception as err:
            raise err
        finally:
            cursor.close()

Prompt: Add class for updating stock


from django.db import models
from django.core.exceptions import ValidationError

class OrderedModel(models.Model):
  order = models.PositiveIntegerField(blank=True, unique=True)

  class Meta:
    abstract = True
    ordering = ['order']

  def save(self, swapping=False, *args, **kwargs):
    if not self.id:
      try:
        self.order = self.max_order() + 1
      except:
        self.order = 1 # 0 is a special index used in swap
    if self.order == 0 and not swapping:
      raise ValidationError("Can't set 'order' to 0")
    super(OrderedModel, self).save(*args, **kwargs)

  @classmethod
  def swap(cls, obj1, obj2):
    tmp, obj2.order = obj2.order, 0
    obj2.save(swapping=True)
    obj2.order, obj1.order = obj1.order, tmp
    obj1.save()
    obj2.save()

  @classmethod
  def max_order(cls):
    return cls.objects.order_by('-order')[0].order

Fix critical stupid copypaste error

Fix critical stupid copypaste error

Response:
<REPLACE_OLD> self.max_order <REPLACE_NEW> self.max_order() <REPLACE_END> <REPLACE_OLD> self.__class__.objects.order_by('-order')[0].order
 <REPLACE_NEW> cls.objects.order_by('-order')[0].order
 <REPLACE_END> <|endoftext|> from django.db import models
from django.core.exceptions import ValidationError

class OrderedModel(models.Model):
  order = models.PositiveIntegerField(blank=True, unique=True)

  class Meta:
    abstract = True
    ordering = ['order']

  def save(self, swapping=False, *args, **kwargs):
    if not self.id:
      try:
        self.order = self.max_order() + 1
      except:
        self.order = 1 # 0 is a special index used in swap
    if self.order == 0 and not swapping:
      raise ValidationError("Can't set 'order' to 0")
    super(OrderedModel, self).save(*args, **kwargs)

  @classmethod
  def swap(cls, obj1, obj2):
    tmp, obj2.order = obj2.order, 0
    obj2.save(swapping=True)
    obj2.order, obj1.order = obj1.order, tmp
    obj1.save()
    obj2.save()

  @classmethod
  def max_order(cls):
    return cls.objects.order_by('-order')[0].order

Prompt:
Fix critical stupid copypaste error

from django.db import models
from django.core.exceptions import ValidationError

class OrderedModel(models.Model):
  order = models.PositiveIntegerField(blank=True, unique=True)

  class Meta:
    abstract = True
    ordering = ['order']

  def save(self, swapping=False, *args, **kwargs):
    if not self.id:
      try:
        self.order = self.max_order + 1
      except:
        self.order = 1 # 0 is a special index used in swap
    if self.order == 0 and not swapping:
      raise ValidationError("Can't set 'order' to 0")
    super(OrderedModel, self).save(*args, **kwargs)

  @classmethod
  def swap(cls, obj1, obj2):
    tmp, obj2.order = obj2.order, 0
    obj2.save(swapping=True)
    obj2.order, obj1.order = obj1.order, tmp
    obj1.save()
    obj2.save()

  @classmethod
  def max_order(cls):
    return self.__class__.objects.order_by('-order')[0].order


from collections import deque

def split_path(path):
    """
    Split a url path into its sub-paths.

    A url's sub-paths consist of all substrings ending in / and starting at
    the start of the url.

    eg: /path/containing/subpaths/ becomes:

        /
        /path/
        /path/containing/
        /path/containing/subpaths/
    """
    paths = deque()
    path = path or '/'
    while path:
        path = path.rpartition('/')[0]
        paths.appendleft(path + '/')
    return list(paths)

Response:
<INSERT> from collections <INSERT_END> <REPLACE_OLD> os

def <REPLACE_NEW> deque

def <REPLACE_END> <REPLACE_OLD> url.
 <REPLACE_NEW> url.

    eg: /path/containing/subpaths/ becomes:

        /
        /path/
        /path/containing/
        /path/containing/subpaths/
 <REPLACE_END> <REPLACE_OLD> ['/']
 <REPLACE_NEW> deque()
 <REPLACE_END> <REPLACE_OLD> path.rstrip('/')

 <REPLACE_NEW> path or '/'
 <REPLACE_END> <DELETE> paths.insert(1, <DELETE_END> <REPLACE_OLD> + '/')
 <REPLACE_NEW> = path.rpartition('/')[0]
 <REPLACE_END> <REPLACE_OLD> path = os.path.split(path)[0]
        if path == '/':
            break
 <REPLACE_NEW> paths.appendleft(path + '/')
 <REPLACE_END> <REPLACE_OLD> paths
 <REPLACE_NEW> list(paths)
 <REPLACE_END> <|endoftext|> from collections import deque

def split_path(path):
    """
    Split a url path into its sub-paths.

    A url's sub-paths consist of all substrings ending in / and starting at
    the start of the url.

    eg: /path/containing/subpaths/ becomes:

        /
        /path/
        /path/containing/
        /path/containing/subpaths/
    """
    paths = deque()
    path = path or '/'
    while path:
        path = path.rpartition('/')[0]
        paths.appendleft(path + '/')
    return list(paths)

Prompt:
Refactor split_path code for brevity and clarity

import os

def split_path(path):
    """
    Split a url path into its sub-paths.

    A url's sub-paths consist of all substrings ending in / and starting at
    the start of the url.
    """
    paths = ['/']
    path = path.rstrip('/')

    while path:
        paths.insert(1, path + '/')
        path = os.path.split(path)[0]
        if path == '/':
            break
    return paths


from devbot import chat

def call(message, name, protocol, cfg, commands):
    if message == '':
        chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
        return

    aliases = ''
    for tupl in commands['regex'].items():
        if tupl[1] == message:
            aliases = aliases + tupl[0] + ', '
    if aliases == '':
        chat.say('/r Sorry, there is no command by that name.', protocol)
    else:
        chat.say('/r ' + aliases, protocol)

Response:
<REPLACE_OLD> chat.say('Sorry, <REPLACE_NEW> chat.say('/r Sorry, <REPLACE_END> <|endoftext|> from devbot import chat

def call(message, name, protocol, cfg, commands):
    if message == '':
        chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
        return

    aliases = ''
    for tupl in commands['regex'].items():
        if tupl[1] == message:
            aliases = aliases + tupl[0] + ', '
    if aliases == '':
        chat.say('/r Sorry, there is no command by that name.', protocol)
    else:
        chat.say('/r ' + aliases, protocol)

Prompt:
Fix bug with DevotedBot speaking error in chat

from devbot import chat

def call(message, name, protocol, cfg, commands):
    if message == '':
        chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
        return

    aliases = ''
    for tupl in commands['regex'].items():
        if tupl[1] == message:
            aliases = aliases + tupl[0] + ', '
    if aliases == '':
        chat.say('Sorry, there is no command by that name.', protocol)
    else:
        chat.say('/r ' + aliases, protocol)


from __future__ import absolute_import, division, print_function, unicode_literals

from setuptools import setup

setup( name='lifecycle'
     , author='Gittip, LLC'
     , author_email='support@gittip.com'
     , description="This library models a process lifecycle as a list of functions."
     , url='http://lifecycle-py.readthedocs.org'
     , version='0.0.0-dev'
     , py_modules=['lifecycle']
     , install_requires=['dependency_injection']
     , classifiers=[ 'Development Status :: 5 - Production/Stable'
                   , 'Intended Audience :: Developers'
                   , 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication'
                   , 'Operating System :: OS Independent'
                   , 'Programming Language :: Python :: 2'
                   , 'Programming Language :: Python :: 2.6'
                   , 'Programming Language :: Python :: 2.7'
                   , 'Programming Language :: Python :: 3'
                   , 'Programming Language :: Python :: 3.2'
                   , 'Programming Language :: Python :: 3.3'
                   , 'Topic :: Software Development :: Libraries :: Python Modules'
                    ]
      )

Response:
<INSERT> install_requires=['dependency_injection']
     , <INSERT_END> <|endoftext|> from __future__ import absolute_import, division, print_function, unicode_literals

from setuptools import setup

setup( name='lifecycle'
     , author='Gittip, LLC'
     , author_email='support@gittip.com'
     , description="This library models a process lifecycle as a list of functions."
     , url='http://lifecycle-py.readthedocs.org'
     , version='0.0.0-dev'
     , py_modules=['lifecycle']
     , install_requires=['dependency_injection']
     , classifiers=[ 'Development Status :: 5 - Production/Stable'
                   , 'Intended Audience :: Developers'
                   , 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication'
                   , 'Operating System :: OS Independent'
                   , 'Programming Language :: Python :: 2'
                   , 'Programming Language :: Python :: 2.6'
                   , 'Programming Language :: Python :: 2.7'
                   , 'Programming Language :: Python :: 3'
                   , 'Programming Language :: Python :: 3.2'
                   , 'Programming Language :: Python :: 3.3'
                   , 'Topic :: Software Development :: Libraries :: Python Modules'
                    ]
      )

Prompt:
Add install_requires so we can build at RTD

from __future__ import absolute_import, division, print_function, unicode_literals

from setuptools import setup

setup( name='lifecycle'
     , author='Gittip, LLC'
     , author_email='support@gittip.com'
     , description="This library models a process lifecycle as a list of functions."
     , url='http://lifecycle-py.readthedocs.org'
     , version='0.0.0-dev'
     , py_modules=['lifecycle']
     , classifiers=[ 'Development Status :: 5 - Production/Stable'
                   , 'Intended Audience :: Developers'
                   , 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication'
                   , 'Operating System :: OS Independent'
                   , 'Programming Language :: Python :: 2'
                   , 'Programming Language :: Python :: 2.6'
                   , 'Programming Language :: Python :: 2.7'
                   , 'Programming Language :: Python :: 3'
                   , 'Programming Language :: Python :: 3.2'
                   , 'Programming Language :: Python :: 3.3'
                   , 'Topic :: Software Development :: Libraries :: Python Modules'
                    ]
      )


#!/usr/bin/env python

from datetime import date, timedelta
import redis

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

r = redis.Redis('localhost', 6334, db=1)

for result in perdelta(date(2015, 03, 01), date(2015, 12, 12), timedelta(days=1)):
    val = r.zcard('{}_submissions'.format(result))
    print('{},{}'.format(result, val))

Add a script to generate stats

Add a script to generate stats

Response:
<INSERT> #!/usr/bin/env python

from datetime import date, timedelta
import redis

def perdelta(start, end, delta):
 <INSERT_END> <INSERT>   curr = start
    while curr < end:
        yield curr
        curr += delta

r = redis.Redis('localhost', 6334, db=1)

for result in perdelta(date(2015, 03, 01), date(2015, 12, 12), timedelta(days=1)):
    val = r.zcard('{}_submissions'.format(result))
    print('{},{}'.format(result, val))
 <INSERT_END> <|endoftext|> #!/usr/bin/env python

from datetime import date, timedelta
import redis

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

r = redis.Redis('localhost', 6334, db=1)

for result in perdelta(date(2015, 03, 01), date(2015, 12, 12), timedelta(days=1)):
    val = r.zcard('{}_submissions'.format(result))
    print('{},{}'.format(result, val))

Prompt: Add a script to generate stats


import numpy as np
from numpy.testing import *

import scipy.ndimage as ndimage

def test_byte_order_median():
    """Regression test for #413: median_filter does not handle bytes orders."""
    a = np.arange(9, dtype='<f4').reshape(3, 3)
    ref = ndimage.filters.median_filter(a,(3, 3))
    b = np.arange(9, dtype='>f4').reshape(3, 3)
    t = ndimage.filters.median_filter(b, (3, 3))
    assert_array_almost_equal(ref, t)

def test_zoom_output_shape():
    """Ticket #643"""
    x = np.arange(12).reshape((3,4))
    ndimage.zoom(x, 2, output=np.zeros((6,8)))

if __name__ == "__main__":
    run_module_suite()

Response:
<REPLACE_OLD> NumpyTest().run()
 <REPLACE_NEW> run_module_suite()
 <REPLACE_END> <|endoftext|> import numpy as np
from numpy.testing import *

import scipy.ndimage as ndimage

def test_byte_order_median():
    """Regression test for #413: median_filter does not handle bytes orders."""
    a = np.arange(9, dtype='<f4').reshape(3, 3)
    ref = ndimage.filters.median_filter(a,(3, 3))
    b = np.arange(9, dtype='>f4').reshape(3, 3)
    t = ndimage.filters.median_filter(b, (3, 3))
    assert_array_almost_equal(ref, t)

def test_zoom_output_shape():
    """Ticket #643"""
    x = np.arange(12).reshape((3,4))
    ndimage.zoom(x, 2, output=np.zeros((6,8)))

if __name__ == "__main__":
    run_module_suite()

Prompt:
Use run_module_suite instead of deprecated NumpyTest.

git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5310 d6536bca-fef9-0310-8506-e4c0a848fbcf

import numpy as np
from numpy.testing import *

import scipy.ndimage as ndimage

def test_byte_order_median():
    """Regression test for #413: median_filter does not handle bytes orders."""
    a = np.arange(9, dtype='<f4').reshape(3, 3)
    ref = ndimage.filters.median_filter(a,(3, 3))
    b = np.arange(9, dtype='>f4').reshape(3, 3)
    t = ndimage.filters.median_filter(b, (3, 3))
    assert_array_almost_equal(ref, t)

def test_zoom_output_shape():
    """Ticket #643"""
    x = np.arange(12).reshape((3,4))
    ndimage.zoom(x, 2, output=np.zeros((6,8)))

if __name__ == "__main__":
    NumpyTest().run()


from xml.dom.minidom import getDOMImplementation
import codecs

class XMLOutput():
    def __init__(self, groups):
        impl = getDOMImplementation()
        xml_document = impl.createDocument(None, "parameters", None)
        xml_parameters = xml_document.documentElement
        xml_version = xml_document.createElement("version")
        xml_parameters.appendChild(xml_version)
        xml_version_value = xml_document.createTextNode("1")
        xml_version.appendChild(xml_version_value)
        for group in groups:
            xml_group = xml_document.createElement("group")
            xml_group.setAttribute("name", group.GetName())
            xml_parameters.appendChild(xml_group)
            for param in group.GetParams():
                xml_param = xml_document.createElement("parameter")
                xml_group.appendChild(xml_param)
                for code in param.GetFieldCodes():
                    value = param.GetFieldValue(code)
                    xml_field = xml_document.createElement(code)
                    xml_param.appendChild(xml_field)
                    xml_value = xml_document.createTextNode(value)
                    xml_field.appendChild(xml_value)
        self.xml_document = xml_document

    def Save(self, filename):
        with codecs.open(filename, 'w', 'utf-8') as f:
            self.xml_document.writexml(f, indent="    ", addindent="    ", newl="\n")

Response:
<INSERT> xml_version = xml_document.createElement("version")
        xml_parameters.appendChild(xml_version)
        xml_version_value = xml_document.createTextNode("1")
        xml_version.appendChild(xml_version_value)
        <INSERT_END> <|endoftext|> from xml.dom.minidom import getDOMImplementation
import codecs

class XMLOutput():
    def __init__(self, groups):
        impl = getDOMImplementation()
        xml_document = impl.createDocument(None, "parameters", None)
        xml_parameters = xml_document.documentElement
        xml_version = xml_document.createElement("version")
        xml_parameters.appendChild(xml_version)
        xml_version_value = xml_document.createTextNode("1")
        xml_version.appendChild(xml_version_value)
        for group in groups:
            xml_group = xml_document.createElement("group")
            xml_group.setAttribute("name", group.GetName())
            xml_parameters.appendChild(xml_group)
            for param in group.GetParams():
                xml_param = xml_document.createElement("parameter")
                xml_group.appendChild(xml_param)
                for code in param.GetFieldCodes():
                    value = param.GetFieldValue(code)
                    xml_field = xml_document.createElement(code)
                    xml_param.appendChild(xml_field)
                    xml_value = xml_document.createTextNode(value)
                    xml_field.appendChild(xml_value)
        self.xml_document = xml_document

    def Save(self, filename):
        with codecs.open(filename, 'w', 'utf-8') as f:
            self.xml_document.writexml(f, indent="    ", addindent="    ", newl="\n")

Prompt:
Add version number to parameter meta data

from xml.dom.minidom import getDOMImplementation
import codecs

class XMLOutput():
    def __init__(self, groups):
        impl = getDOMImplementation()
        xml_document = impl.createDocument(None, "parameters", None)
        xml_parameters = xml_document.documentElement
        for group in groups:
            xml_group = xml_document.createElement("group")
            xml_group.setAttribute("name", group.GetName())
            xml_parameters.appendChild(xml_group)
            for param in group.GetParams():
                xml_param = xml_document.createElement("parameter")
                xml_group.appendChild(xml_param)
                for code in param.GetFieldCodes():
                    value = param.GetFieldValue(code)
                    xml_field = xml_document.createElement(code)
                    xml_param.appendChild(xml_field)
                    xml_value = xml_document.createTextNode(value)
                    xml_field.appendChild(xml_value)
        self.xml_document = xml_document

    def Save(self, filename):
        with codecs.open(filename, 'w', 'utf-8') as f:
            self.xml_document.writexml(f, indent="    ", addindent="    ", newl="\n")


import collections

def each(function, iterable):
  for item in iterable:
    function(item)

def each_unpack(function, iterable):
  for item in iterable:
    function(*item)

def minmax(*args):
  min = None
  max = None
  for x in args:
    if max < x:
      max = x
    if x > min:
      min = x
  return min, max

def map_inplace(function, list, depth=0):
  if depth <= 0:
    list[:] = map(function, list)
  else:
    for item in list:
      map_inplace(function, item, depth - 1)

def count_if(function, iterable):
  count = 0
  for item in iterable:
    if function(item):
      count += 1
  return count

def teemap(iterable, *functions):
  map(lambda item: (f(item) for f in functions), iterable)

class ProbabilityDistribution(collections.defaultdict):
  """"Holds a probability distribution and can compute the distance to other dists"""

  def __init__(self):
    collections.defaultdict.__init__(self, int)

  def get(self, k, d = 0):
    return dict.get(self, k, d)

  def distance_to(self, compare_to):
    return sum(
      (abs(self.get(bin) - compare_to.get(bin))
        for bin in self.viewkeys() | compare_to.viewkeys()),
      0)

Response:
<REPLACE_OLD> key_set = <REPLACE_NEW> return sum(
      (abs(self.get(bin) - compare_to.get(bin))
        for bin in <REPLACE_END> <REPLACE_OLD> compare_to.viewkeys()

    currentEMD = 0
    lastEMD = 0
    totaldistance = 0

    for key in key_set:
      lastEMD = currentEMD
      currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, <REPLACE_NEW> compare_to.viewkeys()),
      <REPLACE_END> <DELETE>      totaldistance += math.fabs(currentEMD)

    return totaldistance <DELETE_END> <|endoftext|> import collections

def each(function, iterable):
  for item in iterable:
    function(item)

def each_unpack(function, iterable):
  for item in iterable:
    function(*item)

def minmax(*args):
  min = None
  max = None
  for x in args:
    if max < x:
      max = x
    if x > min:
      min = x
  return min, max

def map_inplace(function, list, depth=0):
  if depth <= 0:
    list[:] = map(function, list)
  else:
    for item in list:
      map_inplace(function, item, depth - 1)

def count_if(function, iterable):
  count = 0
  for item in iterable:
    if function(item):
      count += 1
  return count

def teemap(iterable, *functions):
  map(lambda item: (f(item) for f in functions), iterable)

class ProbabilityDistribution(collections.defaultdict):
  """"Holds a probability distribution and can compute the distance to other dists"""

  def __init__(self):
    collections.defaultdict.__init__(self, int)

  def get(self, k, d = 0):
    return dict.get(self, k, d)

  def distance_to(self, compare_to):
    return sum(
      (abs(self.get(bin) - compare_to.get(bin))
        for bin in self.viewkeys() | compare_to.viewkeys()),
      0)

Prompt:
Refactor earth mover's distance implementation

import collections

def each(function, iterable):
  for item in iterable:
    function(item)

def each_unpack(function, iterable):
  for item in iterable:
    function(*item)

def minmax(*args):
  min = None
  max = None
  for x in args:
    if max < x:
      max = x
    if x > min:
      min = x
  return min, max

def map_inplace(function, list, depth=0):
  if depth <= 0:
    list[:] = map(function, list)
  else:
    for item in list:
      map_inplace(function, item, depth - 1)

def count_if(function, iterable):
  count = 0
  for item in iterable:
    if function(item):
      count += 1
  return count

def teemap(iterable, *functions):
  map(lambda item: (f(item) for f in functions), iterable)

class ProbabilityDistribution(collections.defaultdict):
  """"Holds a probability distribution and can compute the distance to other dists"""

  def __init__(self):
    collections.defaultdict.__init__(self, int)

  def get(self, k, d = 0):
    return dict.get(self, k, d)

  def distance_to(self, compare_to):
    key_set = self.viewkeys() | compare_to.viewkeys()

    currentEMD = 0
    lastEMD = 0
    totaldistance = 0

    for key in key_set:
      lastEMD = currentEMD
      currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, 0)
      totaldistance += math.fabs(currentEMD)

    return totaldistance


import pytest
try:
    from unittest import mock
except ImportError:
    import mock

from k2catalogue import models

@pytest.fixture
def proposal():
    return models.Proposal(proposal_id='abc', pi='pi', title='title',
                           pdf_url='pdf_url')

def test_proposal_printing(proposal):
    assert repr(proposal) == '<Proposal: abc>'

def test_proposal():
    proposals = models.Proposal.create(['abc', 'def'],
                                       campaign=mock.MagicMock(),
                                       proposal_mapping=mock.MagicMock())
    assert (proposals[0].proposal_id == 'abc' and
            proposals[1].proposal_id == 'def')

def test_open_proposals_page(proposal):
    with mock.patch.object(proposal, 'campaign') as campaign:
        proposal.open_proposals_page()
        campaign.open_proposals_page.assert_called_once_with()

def test_open_proposal(proposal):
    with mock.patch('k2catalogue.models.webbrowser.open') as mock_open:
        proposal.open_proposal()
        mock_open.assert_called_once_with('pdf_url')

def test_open_proposal_without_url(proposal):
    proposal.pdf_url = None
    with mock.patch('k2catalogue.models.webbrowser.open') as mock_open:
        proposal.open_proposal()
        assert not mock_open.called

def test_create_with_no_mapping(capsys):
    proposal_mapping = {}
    campaign = mock.Mock()
    proposal_ids = ['abc', ]
    models.Proposal.create(proposal_ids, campaign, proposal_mapping)
    out, err = capsys.readouterr()
    assert err == 'No proposal metadata for abc\n'

@pytest.mark.parametrize('input,expected', [
    ('GO2069_LC', True),
    ('G', False),
    ('LC_2007JJ43_TILE', False),
])
def test_valid_proposal(input, expected):
    assert models.Proposal.valid_proposal(input) == expected

Response:
<REPLACE_OLD> 'def')

@pytest.mark.parametrize('input,expected', <REPLACE_NEW> 'def')

def test_open_proposals_page(proposal):
    with mock.patch.object(proposal, 'campaign') as campaign:
        proposal.open_proposals_page()
        campaign.open_proposals_page.assert_called_once_with()

def test_open_proposal(proposal):
    with mock.patch('k2catalogue.models.webbrowser.open') as mock_open:
        proposal.open_proposal()
        mock_open.assert_called_once_with('pdf_url')

def test_open_proposal_without_url(proposal):
    proposal.pdf_url = None
    with mock.patch('k2catalogue.models.webbrowser.open') as mock_open:
        proposal.open_proposal()
        assert not mock_open.called

def test_create_with_no_mapping(capsys):
    proposal_mapping = {}
    campaign = mock.Mock()
    proposal_ids = ['abc', ]
    models.Proposal.create(proposal_ids, campaign, proposal_mapping)
    out, err = capsys.readouterr()
    assert err == 'No proposal metadata for abc\n'

@pytest.mark.parametrize('input,expected', <REPLACE_END> <|endoftext|> import pytest
try:
    from unittest import mock
except ImportError:
    import mock

from k2catalogue import models

@pytest.fixture
def proposal():
    return models.Proposal(proposal_id='abc', pi='pi', title='title',
                           pdf_url='pdf_url')

def test_proposal_printing(proposal):
    assert repr(proposal) == '<Proposal: abc>'

def test_proposal():
    proposals = models.Proposal.create(['abc', 'def'],
                                       campaign=mock.MagicMock(),
                                       proposal_mapping=mock.MagicMock())
    assert (proposals[0].proposal_id == 'abc' and
            proposals[1].proposal_id == 'def')

def test_open_proposals_page(proposal):
    with mock.patch.object(proposal, 'campaign') as campaign:
        proposal.open_proposals_page()
        campaign.open_proposals_page.assert_called_once_with()

def test_open_proposal(proposal):
    with mock.patch('k2catalogue.models.webbrowser.open') as mock_open:
        proposal.open_proposal()
        mock_open.assert_called_once_with('pdf_url')

def test_open_proposal_without_url(proposal):
    proposal.pdf_url = None
    with mock.patch('k2catalogue.models.webbrowser.open') as mock_open:
        proposal.open_proposal()
        assert not mock_open.called

def test_create_with_no_mapping(capsys):
    proposal_mapping = {}
    campaign = mock.Mock()
    proposal_ids = ['abc', ]
    models.Proposal.create(proposal_ids, campaign, proposal_mapping)
    out, err = capsys.readouterr()
    assert err == 'No proposal metadata for abc\n'

@pytest.mark.parametrize('input,expected', [
    ('GO2069_LC', True),
    ('G', False),
    ('LC_2007JJ43_TILE', False),
])
def test_valid_proposal(input, expected):
    assert models.Proposal.valid_proposal(input) == expected

Prompt:
Add more tests around the proposal model behaviour

import pytest
try:
    from unittest import mock
except ImportError:
    import mock

from k2catalogue import models

@pytest.fixture
def proposal():
    return models.Proposal(proposal_id='abc', pi='pi', title='title',
                           pdf_url='pdf_url')

def test_proposal_printing(proposal):
    assert repr(proposal) == '<Proposal: abc>'

def test_proposal():
    proposals = models.Proposal.create(['abc', 'def'],
                                       campaign=mock.MagicMock(),
                                       proposal_mapping=mock.MagicMock())
    assert (proposals[0].proposal_id == 'abc' and
            proposals[1].proposal_id == 'def')

@pytest.mark.parametrize('input,expected', [
    ('GO2069_LC', True),
    ('G', False),
    ('LC_2007JJ43_TILE', False),
])
def test_valid_proposal(input, expected):
    assert models.Proposal.valid_proposal(input) == expected


from math import exp

MIN_PRECISION = 32

for n in [0.5,1.0,2.0,3.0]:
    print '    uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
    print '    uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int(   (n)*(1<<MIN_PRECISION))).replace('.','P')

Response:
<REPLACE_OLD> common <REPLACE_NEW> math <REPLACE_END> <|endoftext|> from math import exp

MIN_PRECISION = 32

for n in [0.5,1.0,2.0,3.0]:
    print '    uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
    print '    uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int(   (n)*(1<<MIN_PRECISION))).replace('.','P')

Prompt:
Revert previous commit on this specific file (mistake).

from common import exp

MIN_PRECISION = 32

for n in [0.5,1.0,2.0,3.0]:
    print '    uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
    print '    uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int(   (n)*(1<<MIN_PRECISION))).replace('.','P')


######
#  Check ExId (GUID) by Email through JDBC
#
#  Author:        Christoph Stoettner
#  Mail:          christoph.stoettner@stoeps.de
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-04
#
#  License:       Apache 2.0
#
#  Check ExId of a User in all Connections Applications

import ibmcnx.functions

cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"

# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
    dbname = db.split('(')
    n = 0
    for i in dbname:
        # i is only the name of the DataSource, db is DataSource ID!
        if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
            dblist.append(str(db).replace('"',''))
        n += 1

dblist.sort()

for db in dblist:
    print "AdminConfig.list( db ): "
    try:
        AdminConfig.list ( db )
    except:
        print "error on: " + db
    print "AdminConfig.showAttribute( db, 'name' ): "
    try:
        AdminConfig.showAttribute( db, 'name' )
    except:
        print "error on: " + db

Response:
<INSERT> try:
        <INSERT_END> <INSERT>    except:
        print "error on: " + db
 <INSERT_END> <INSERT> try:
        <INSERT_END> <REPLACE_OLD> ) <REPLACE_NEW> )
    except:
        print "error on: " + db <REPLACE_END> <|endoftext|> ######
#  Check ExId (GUID) by Email through JDBC
#
#  Author:        Christoph Stoettner
#  Mail:          christoph.stoettner@stoeps.de
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-04
#
#  License:       Apache 2.0
#
#  Check ExId of a User in all Connections Applications

import ibmcnx.functions

cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"

# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
    dbname = db.split('(')
    n = 0
    for i in dbname:
        # i is only the name of the DataSource, db is DataSource ID!
        if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
            dblist.append(str(db).replace('"',''))
        n += 1

dblist.sort()

for db in dblist:
    print "AdminConfig.list( db ): "
    try:
        AdminConfig.list ( db )
    except:
        print "error on: " + db
    print "AdminConfig.showAttribute( db, 'name' ): "
    try:
        AdminConfig.showAttribute( db, 'name' )
    except:
        print "error on: " + db

Prompt:
8: Create documentation of DataSource Settings

Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
######
#  Check ExId (GUID) by Email through JDBC
#
#  Author:        Christoph Stoettner
#  Mail:          christoph.stoettner@stoeps.de
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-04
#
#  License:       Apache 2.0
#
#  Check ExId of a User in all Connections Applications

import ibmcnx.functions

cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"

# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
    dbname = db.split('(')
    n = 0
    for i in dbname:
        # i is only the name of the DataSource, db is DataSource ID!
        if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
            dblist.append(str(db).replace('"',''))
        n += 1

dblist.sort()

for db in dblist:
    print "AdminConfig.list( db ): "
    AdminConfig.list ( db )
    print "AdminConfig.showAttribute( db, 'name' ): "
    AdminConfig.showAttribute( db, 'name' )


from django.core.management.base import BaseCommand, CommandError

from studygroups.models import Course
from django.contrib.auth.models import User

class Command(BaseCommand):
    help = 'Add a created_by field to all courses'

    def handle(self, *args, **options):
        user1 = User.objects.get(pk=1324)
        courses = Course.objects.filter(created_by__isnull=True, created_at__gt=user1.date_joined)
        courses.update(created_by=user1)
        courses = Course.objects.filter(created_by__isnull=True)
        courses.update(created_by=User.objects.get(pk=3))

Add task to fix created_by for courses without it

Response:
<INSERT> from django.core.management.base import BaseCommand, CommandError

from studygroups.models import Course
from django.contrib.auth.models import User

class Command(BaseCommand):
 <INSERT_END> <INSERT>   help = 'Add a created_by field to all courses'

    def handle(self, *args, **options):
        user1 = User.objects.get(pk=1324)
        courses = Course.objects.filter(created_by__isnull=True, created_at__gt=user1.date_joined)
        courses.update(created_by=user1)
        courses = Course.objects.filter(created_by__isnull=True)
        courses.update(created_by=User.objects.get(pk=3))
 <INSERT_END> <|endoftext|> from django.core.management.base import BaseCommand, CommandError

from studygroups.models import Course
from django.contrib.auth.models import User

class Command(BaseCommand):
    help = 'Add a created_by field to all courses'

    def handle(self, *args, **options):
        user1 = User.objects.get(pk=1324)
        courses = Course.objects.filter(created_by__isnull=True, created_at__gt=user1.date_joined)
        courses.update(created_by=user1)
        courses = Course.objects.filter(created_by__isnull=True)
        courses.update(created_by=User.objects.get(pk=3))

Prompt: Add task to fix created_by for courses without it


import matplotlib
matplotlib.use('Agg')

import matplotlib.colors
import matplotlib.pyplot as plt
import matplotlib.animation as animation

class AnimatedGif:

    """ Setup various rendering things
    """
    def __init__(self, dpi=100, colors="Purples"):
        self.frames = []
        self.fig = plt.figure(dpi=dpi)
        plt.axis("off")
        self.colors = colors
        self.normalize = matplotlib.colors.Normalize()
        self.dimensions = None

    def append(self, universe):
        if not self.dimensions:
            if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]):
                raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values")
            self.dimensions = universe.shape
        if self.dimensions != universe.shape:
            raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape))

        self.frames.append((plt.imshow(universe, norm=self.normalize, cmap=self.colors),))

    def render(self, filename, interval=300):
        im_ani = animation.ArtistAnimation(
            self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True
        )
        im_ani.save(filename, writer="imagemagick")

Use the same normlization for whole gif

Use the same normlization for whole gif

Response:
<INSERT> matplotlib.colors
import <INSERT_END> <INSERT>        self.normalize = matplotlib.colors.Normalize()
 <INSERT_END> <INSERT> norm=self.normalize, <INSERT_END> <|endoftext|> import matplotlib
matplotlib.use('Agg')

import matplotlib.colors
import matplotlib.pyplot as plt
import matplotlib.animation as animation

class AnimatedGif:

    """ Setup various rendering things
    """
    def __init__(self, dpi=100, colors="Purples"):
        self.frames = []
        self.fig = plt.figure(dpi=dpi)
        plt.axis("off")
        self.colors = colors
        self.normalize = matplotlib.colors.Normalize()
        self.dimensions = None

    def append(self, universe):
        if not self.dimensions:
            if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]):
                raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values")
            self.dimensions = universe.shape
        if self.dimensions != universe.shape:
            raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape))

        self.frames.append((plt.imshow(universe, norm=self.normalize, cmap=self.colors),))

    def render(self, filename, interval=300):
        im_ani = animation.ArtistAnimation(
            self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True
        )
        im_ani.save(filename, writer="imagemagick")

Prompt:
Use the same normlization for whole gif

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import matplotlib.animation as animation

class AnimatedGif:

    """ Setup various rendering things
    """
    def __init__(self, dpi=100, colors="Purples"):
        self.frames = []
        self.fig = plt.figure(dpi=dpi)
        plt.axis("off")
        self.colors = colors
        self.dimensions = None

    def append(self, universe):
        if not self.dimensions:
            if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]):
                raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values")
            self.dimensions = universe.shape
        if self.dimensions != universe.shape:
            raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape))

        self.frames.append((plt.imshow(universe, cmap=self.colors),))

    def render(self, filename, interval=300):
        im_ani = animation.ArtistAnimation(
            self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True
        )
        im_ani.save(filename, writer="imagemagick")


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

"""
byceps.database
~~~~~~~~~~~~~~~

Database utilities.

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

import uuid

from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID

db = SQLAlchemy(session_options={'autoflush': False})

db.Uuid = UUID

def generate_uuid():
    """Generate a random UUID (Universally Unique IDentifier)."""
    return uuid.uuid4()

Response:
<REPLACE_OLD> SQLAlchemy()

db.Uuid <REPLACE_NEW> SQLAlchemy(session_options={'autoflush': False})

db.Uuid <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

"""
byceps.database
~~~~~~~~~~~~~~~

Database utilities.

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

import uuid

from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID

db = SQLAlchemy(session_options={'autoflush': False})

db.Uuid = UUID

def generate_uuid():
    """Generate a random UUID (Universally Unique IDentifier)."""
    return uuid.uuid4()

Prompt:
Disable autoflushing as introduced with Flask-SQLAlchemy 2.0.

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

"""
byceps.database
~~~~~~~~~~~~~~~

Database utilities.

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

import uuid

from flask.ext.sqlalchemy import BaseQuery, SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID

db = SQLAlchemy()

db.Uuid = UUID

def generate_uuid():
    """Generate a random UUID (Universally Unique IDentifier)."""
    return uuid.uuid4()


"""
Example usage of UNO, graphic objects and networking in LO extension
"""

import unohelper
from com.sun.star.task import XJobExecutor

class ImageExample(unohelper.Base, XJobExecutor):
    '''Class that implements the service registered in LibreOffice'''

    def __init__(self, context):
        self.context = context
        self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
        self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")

    def createUnoService(self, name):
        return self.context.ServiceManager.createInstanceWithContext(name, self.context)

g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
    ImageExample,
    'org.libreoffice.imageexample.ImageExample',
    ('com.sun.star.task.JobExecutor',))

Add code to create needed uno services

Add code to create needed uno services

Response:
<REPLACE_OLD> context

g_ImplementationHelper <REPLACE_NEW> context
        self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
        self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")

    def createUnoService(self, name):
        return self.context.ServiceManager.createInstanceWithContext(name, self.context)

g_ImplementationHelper <REPLACE_END> <|endoftext|> """
Example usage of UNO, graphic objects and networking in LO extension
"""

import unohelper
from com.sun.star.task import XJobExecutor

class ImageExample(unohelper.Base, XJobExecutor):
    '''Class that implements the service registered in LibreOffice'''

    def __init__(self, context):
        self.context = context
        self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
        self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")

    def createUnoService(self, name):
        return self.context.ServiceManager.createInstanceWithContext(name, self.context)

g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
    ImageExample,
    'org.libreoffice.imageexample.ImageExample',
    ('com.sun.star.task.JobExecutor',))

Prompt:
Add code to create needed uno services

"""
Example usage of UNO, graphic objects and networking in LO extension
"""

import unohelper
from com.sun.star.task import XJobExecutor

class ImageExample(unohelper.Base, XJobExecutor):
    '''Class that implements the service registered in LibreOffice'''

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

g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
    ImageExample,
    'org.libreoffice.imageexample.ImageExample',
    ('com.sun.star.task.JobExecutor',))


"""
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess

PLATFORMS = ['bsd', 'linux', 'nt']

# Detect what platform we are on
try:
    platform = os.uname()[0].lower()
except AttributeError:
    platform = os.name.lower()

if platform == 'darwin':
    platform = 'bsd'

DIRECTORIES = ['functional', 'unit'] # Unit tests to be added here

def platform_test(filename):
    for key in PLATFORMS:
        if filename.find(key) > -1:
            return True
    return False

def this_platform(filename):
    if filename.find(platform) > -1:
        return True
    return False

def run_test(file):
    print "Running test: %s" % file
    print
    proc = subprocess.Popen("python %s" % file,
                            shell=True,
                            stdout=subprocess.PIPE)
    output = proc.communicate()[0]
    print output

    # We don't do anything with this yet but I'll probably try and group all
    # these calls up and keep track of the data at the top level
    if output.find('OK'):
        return True
    return False

for directory in DIRECTORIES:
    files = os.listdir(directory)
    for file in files:
        file_path = os.path.join(directory, file)
        if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
            if platform_test(file):
                if this_platform(file):
                    run_test(file_path)
            else:
                run_test(file_path)

Add unit to the test directories

Add unit to the test directories

Response:
<REPLACE_OLD> ['functional'] <REPLACE_NEW> ['functional', 'unit'] <REPLACE_END> <|endoftext|> """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess

PLATFORMS = ['bsd', 'linux', 'nt']

# Detect what platform we are on
try:
    platform = os.uname()[0].lower()
except AttributeError:
    platform = os.name.lower()

if platform == 'darwin':
    platform = 'bsd'

DIRECTORIES = ['functional', 'unit'] # Unit tests to be added here

def platform_test(filename):
    for key in PLATFORMS:
        if filename.find(key) > -1:
            return True
    return False

def this_platform(filename):
    if filename.find(platform) > -1:
        return True
    return False

def run_test(file):
    print "Running test: %s" % file
    print
    proc = subprocess.Popen("python %s" % file,
                            shell=True,
                            stdout=subprocess.PIPE)
    output = proc.communicate()[0]
    print output

    # We don't do anything with this yet but I'll probably try and group all
    # these calls up and keep track of the data at the top level
    if output.find('OK'):
        return True
    return False

for directory in DIRECTORIES:
    files = os.listdir(directory)
    for file in files:
        file_path = os.path.join(directory, file)
        if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
            if platform_test(file):
                if this_platform(file):
                    run_test(file_path)
            else:
                run_test(file_path)

Prompt:
Add unit to the test directories

"""
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess

PLATFORMS = ['bsd', 'linux', 'nt']

# Detect what platform we are on
try:
    platform = os.uname()[0].lower()
except AttributeError:
    platform = os.name.lower()

if platform == 'darwin':
    platform = 'bsd'

DIRECTORIES = ['functional'] # Unit tests to be added here

def platform_test(filename):
    for key in PLATFORMS:
        if filename.find(key) > -1:
            return True
    return False

def this_platform(filename):
    if filename.find(platform) > -1:
        return True
    return False

def run_test(file):
    print "Running test: %s" % file
    print
    proc = subprocess.Popen("python %s" % file,
                            shell=True,
                            stdout=subprocess.PIPE)
    output = proc.communicate()[0]
    print output

    # We don't do anything with this yet but I'll probably try and group all
    # these calls up and keep track of the data at the top level
    if output.find('OK'):
        return True
    return False

for directory in DIRECTORIES:
    files = os.listdir(directory)
    for file in files:
        file_path = os.path.join(directory, file)
        if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
            if platform_test(file):
                if this_platform(file):
                    run_test(file_path)
            else:
                run_test(file_path)


#!/usr/bin/env python

import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging

application = create_app(
    os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manager.add_command("runserver", Server(host='0.0.0.0', port=port))

log_group = os.getenv('EQ_SR_LOG_GROUP')
cloud_watch_handler = watchtower.CloudWatchLogHandler(log_group=log_group)
FORMAT = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s"
levels = {
    'CRITICAL': logging.CRITICAL,
    'ERROR': logging.ERROR,
    'WARNING': logging.WARNING,
    'INFO': logging.INFO,
    'DEBUG': logging.DEBUG
}
logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING'], format=FORMAT)
application.logger.addHandler(cloud_watch_handler)
logging.getLogger().addHandler(cloud_watch_handler)
logging.getLogger(__name__).addHandler(cloud_watch_handler)
logging.getLogger('werkzeug').addHandler(cloud_watch_handler)

if __name__ == '__main__':
    manager.run()

Allow log group to be set from env

Allow log group to be set from env

Response:
<REPLACE_OLD> port=port))

cloud_watch_handler <REPLACE_NEW> port=port))

log_group <REPLACE_END> <REPLACE_OLD> watchtower.CloudWatchLogHandler()
FORMAT <REPLACE_NEW> os.getenv('EQ_SR_LOG_GROUP')
cloud_watch_handler = watchtower.CloudWatchLogHandler(log_group=log_group)
FORMAT <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging

application = create_app(
    os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manager.add_command("runserver", Server(host='0.0.0.0', port=port))

log_group = os.getenv('EQ_SR_LOG_GROUP')
cloud_watch_handler = watchtower.CloudWatchLogHandler(log_group=log_group)
FORMAT = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s"
levels = {
    'CRITICAL': logging.CRITICAL,
    'ERROR': logging.ERROR,
    'WARNING': logging.WARNING,
    'INFO': logging.INFO,
    'DEBUG': logging.DEBUG
}
logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING'], format=FORMAT)
application.logger.addHandler(cloud_watch_handler)
logging.getLogger().addHandler(cloud_watch_handler)
logging.getLogger(__name__).addHandler(cloud_watch_handler)
logging.getLogger('werkzeug').addHandler(cloud_watch_handler)

if __name__ == '__main__':
    manager.run()

Prompt:
Allow log group to be set from env

#!/usr/bin/env python

import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging

application = create_app(
    os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manager.add_command("runserver", Server(host='0.0.0.0', port=port))

cloud_watch_handler = watchtower.CloudWatchLogHandler()
FORMAT = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s"
levels = {
    'CRITICAL': logging.CRITICAL,
    'ERROR': logging.ERROR,
    'WARNING': logging.WARNING,
    'INFO': logging.INFO,
    'DEBUG': logging.DEBUG
}
logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING'], format=FORMAT)
application.logger.addHandler(cloud_watch_handler)
logging.getLogger().addHandler(cloud_watch_handler)
logging.getLogger(__name__).addHandler(cloud_watch_handler)
logging.getLogger('werkzeug').addHandler(cloud_watch_handler)

if __name__ == '__main__':
    manager.run()