"""Use native postgres JSON type for Entry.content

Revision ID: 588336e02ca
Revises: 2b7f5e38dd73
Create Date: 2014-01-09 22:40:07.690000

"""

# revision identifiers, used by Alembic.
revision = '588336e02ca'
down_revision = '2b7f5e38dd73'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    # Couldn't find a way to specify a USING clause with alembic's alter_table
    op.execute('ALTER TABLE entry ALTER COLUMN content TYPE json USING content::json')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('entry', 'content',
               type_=sa.TEXT(),
               nullable=False)
    ### end Alembic commands ###

Add migration for native postgres JSON type

Response:
<INSERT> """Use native postgres JSON type for Entry.content

Revision ID: 588336e02ca
Revises: 2b7f5e38dd73
Create Date: 2014-01-09 22:40:07.690000

"""

# revision identifiers, used by Alembic.
revision = '588336e02ca'
down_revision = '2b7f5e38dd73'

from alembic import op
import sqlalchemy as sa

def upgrade():
 <INSERT_END> <INSERT>   ### commands auto generated by Alembic - please adjust! ###
    # Couldn't find a way to specify a USING clause with alembic's alter_table
    op.execute('ALTER TABLE entry ALTER COLUMN content TYPE json USING content::json')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('entry', 'content',
               type_=sa.TEXT(),
               nullable=False)
    ### end Alembic commands ###
 <INSERT_END> <|endoftext|> """Use native postgres JSON type for Entry.content

Revision ID: 588336e02ca
Revises: 2b7f5e38dd73
Create Date: 2014-01-09 22:40:07.690000

"""

# revision identifiers, used by Alembic.
revision = '588336e02ca'
down_revision = '2b7f5e38dd73'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    # Couldn't find a way to specify a USING clause with alembic's alter_table
    op.execute('ALTER TABLE entry ALTER COLUMN content TYPE json USING content::json')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('entry', 'content',
               type_=sa.TEXT(),
               nullable=False)
    ### end Alembic commands ###

Prompt: Add migration for native postgres JSON type


from setuptools import setup

setup(
    name='tangled.contrib',
    version='0.1a4.dev0',
    description='Tangled namespace for contributed packages',
    long_description=open('README.rst').read(),
    url='http://tangledframework.org/',
    download_url='https://github.com/TangledWeb/tangled.contrib/tags',
    author='Wyatt Baldwin',
    author_email='self@wyattbaldwin.com',
    packages=[
        'tangled',
        'tangled.contrib',
        'tangled.contrib.scaffolds',
        'tangled.contrib.tests',
    ],
    include_package_data=True,
    install_requires=[
        'tangled>=0.1a8',
    ],
    extras_require={
        'dev': [
            'tangled[dev]>=0.1a8',
        ],
    },
    entry_points="""
    [tangled.scaffolds]
    contrib = tangled.contrib.scaffolds:default
    contrib-core = tangled.contrib.scaffolds:core

    """,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)

Upgrade tangled from 0.1a5 to 0.1a8

Upgrade tangled from 0.1a5 to 0.1a8

Response:
<REPLACE_OLD> 'tangled>=0.1a5',
 <REPLACE_NEW> 'tangled>=0.1a8',
 <REPLACE_END> <REPLACE_OLD> 'tangled[dev]>=0.1a5',
 <REPLACE_NEW> 'tangled[dev]>=0.1a8',
 <REPLACE_END> <|endoftext|> from setuptools import setup

setup(
    name='tangled.contrib',
    version='0.1a4.dev0',
    description='Tangled namespace for contributed packages',
    long_description=open('README.rst').read(),
    url='http://tangledframework.org/',
    download_url='https://github.com/TangledWeb/tangled.contrib/tags',
    author='Wyatt Baldwin',
    author_email='self@wyattbaldwin.com',
    packages=[
        'tangled',
        'tangled.contrib',
        'tangled.contrib.scaffolds',
        'tangled.contrib.tests',
    ],
    include_package_data=True,
    install_requires=[
        'tangled>=0.1a8',
    ],
    extras_require={
        'dev': [
            'tangled[dev]>=0.1a8',
        ],
    },
    entry_points="""
    [tangled.scaffolds]
    contrib = tangled.contrib.scaffolds:default
    contrib-core = tangled.contrib.scaffolds:core

    """,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)

Prompt:
Upgrade tangled from 0.1a5 to 0.1a8

from setuptools import setup

setup(
    name='tangled.contrib',
    version='0.1a4.dev0',
    description='Tangled namespace for contributed packages',
    long_description=open('README.rst').read(),
    url='http://tangledframework.org/',
    download_url='https://github.com/TangledWeb/tangled.contrib/tags',
    author='Wyatt Baldwin',
    author_email='self@wyattbaldwin.com',
    packages=[
        'tangled',
        'tangled.contrib',
        'tangled.contrib.scaffolds',
        'tangled.contrib.tests',
    ],
    include_package_data=True,
    install_requires=[
        'tangled>=0.1a5',
    ],
    extras_require={
        'dev': [
            'tangled[dev]>=0.1a5',
        ],
    },
    entry_points="""
    [tangled.scaffolds]
    contrib = tangled.contrib.scaffolds:default
    contrib-core = tangled.contrib.scaffolds:core

    """,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)


import pytest
from gi.repository import Gtk

from gaphas.item import Element
from gaphas.tool.placement import PlacementState, on_drag_begin, placement_tool

@pytest.fixture
def tool_factory(connections):
    def tool_factory():
        return Element(connections)

    return tool_factory

def test_can_create_placement_tool(view, tool_factory):
    tool = placement_tool(view, tool_factory, 2)

    assert isinstance(tool, Gtk.Gesture)

def test_create_new_element(view, tool_factory, window):
    state = PlacementState(tool_factory, 2)
    tool = placement_tool(view, tool_factory, 2)

    on_drag_begin(tool, 0, 0, state)

    assert state.moving

Add some extra tests for placement

Add some extra tests for placement

Response:
<INSERT> import pytest
from gi.repository import Gtk

from gaphas.item import Element
from gaphas.tool.placement import PlacementState, on_drag_begin, placement_tool

@pytest.fixture
def tool_factory(connections):
 <INSERT_END> <INSERT>   def tool_factory():
        return Element(connections)

    return tool_factory

def test_can_create_placement_tool(view, tool_factory):
    tool = placement_tool(view, tool_factory, 2)

    assert isinstance(tool, Gtk.Gesture)

def test_create_new_element(view, tool_factory, window):
    state = PlacementState(tool_factory, 2)
    tool = placement_tool(view, tool_factory, 2)

    on_drag_begin(tool, 0, 0, state)

    assert state.moving
 <INSERT_END> <|endoftext|> import pytest
from gi.repository import Gtk

from gaphas.item import Element
from gaphas.tool.placement import PlacementState, on_drag_begin, placement_tool

@pytest.fixture
def tool_factory(connections):
    def tool_factory():
        return Element(connections)

    return tool_factory

def test_can_create_placement_tool(view, tool_factory):
    tool = placement_tool(view, tool_factory, 2)

    assert isinstance(tool, Gtk.Gesture)

def test_create_new_element(view, tool_factory, window):
    state = PlacementState(tool_factory, 2)
    tool = placement_tool(view, tool_factory, 2)

    on_drag_begin(tool, 0, 0, state)

    assert state.moving

Prompt: Add some extra tests for placement


import logging
import os

import yaml

import monsetup.agent_config
import monsetup.detection

log = logging.getLogger(__name__)

class Zookeeper(monsetup.detection.Plugin):

    """Detect Zookeeper daemons and setup configuration to monitor them.

    """

    def _detect(self):
        """Run detection, set self.available True if the service is detected.

        """
        if monsetup.detection.find_process_cmdline('org.apache.zookeeper') is not None:
            self.available = True

    def build_config(self):
        """Build the config as a Plugins object and return.

        """
        config = monsetup.agent_config.Plugins()
        # First watch the process
        log.info("\tWatching the zookeeper process.")
        config.merge(monsetup.detection.watch_process(['zookeeper']))

        log.info("\tEnabling the zookeeper plugin")
        with open(os.path.join(self.template_dir, 'conf.d/zk.yaml.example'), 'r') as zk_template:
            zk_config = yaml.load(zk_template.read())
        config['zk'] = zk_config

        return config

    def dependencies_installed(self):
        # The current plugin just does a simple socket connection to zookeeper and
        # parses the stat command
        return True

Response:
<REPLACE_OLD> monsetup.detection.find_process_cmdline('zookeeper') <REPLACE_NEW> monsetup.detection.find_process_cmdline('org.apache.zookeeper') <REPLACE_END> <|endoftext|> import logging
import os

import yaml

import monsetup.agent_config
import monsetup.detection

log = logging.getLogger(__name__)

class Zookeeper(monsetup.detection.Plugin):

    """Detect Zookeeper daemons and setup configuration to monitor them.

    """

    def _detect(self):
        """Run detection, set self.available True if the service is detected.

        """
        if monsetup.detection.find_process_cmdline('org.apache.zookeeper') is not None:
            self.available = True

    def build_config(self):
        """Build the config as a Plugins object and return.

        """
        config = monsetup.agent_config.Plugins()
        # First watch the process
        log.info("\tWatching the zookeeper process.")
        config.merge(monsetup.detection.watch_process(['zookeeper']))

        log.info("\tEnabling the zookeeper plugin")
        with open(os.path.join(self.template_dir, 'conf.d/zk.yaml.example'), 'r') as zk_template:
            zk_config = yaml.load(zk_template.read())
        config['zk'] = zk_config

        return config

    def dependencies_installed(self):
        # The current plugin just does a simple socket connection to zookeeper and
        # parses the stat command
        return True

Prompt:
Fix detection of Zookeeper in monasca-setup

The Zookeeper detection plugin was looking for zookeeper in the process
command-line.  This was producing false positives in the detection
process because storm uses the zookeeper library and it shows up
the command-line for storm.

Change-Id: I764a3064003beec55f0e589272855dadfa0997e7

import logging
import os

import yaml

import monsetup.agent_config
import monsetup.detection

log = logging.getLogger(__name__)

class Zookeeper(monsetup.detection.Plugin):

    """Detect Zookeeper daemons and setup configuration to monitor them.

    """

    def _detect(self):
        """Run detection, set self.available True if the service is detected.

        """
        if monsetup.detection.find_process_cmdline('zookeeper') is not None:
            self.available = True

    def build_config(self):
        """Build the config as a Plugins object and return.

        """
        config = monsetup.agent_config.Plugins()
        # First watch the process
        log.info("\tWatching the zookeeper process.")
        config.merge(monsetup.detection.watch_process(['zookeeper']))

        log.info("\tEnabling the zookeeper plugin")
        with open(os.path.join(self.template_dir, 'conf.d/zk.yaml.example'), 'r') as zk_template:
            zk_config = yaml.load(zk_template.read())
        config['zk'] = zk_config

        return config

    def dependencies_installed(self):
        # The current plugin just does a simple socket connection to zookeeper and
        # parses the stat command
        return True


import django_filters
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _

try:
    from django_filters import rest_framework as filters
except ImportError:  # Back-ward compatible for django-rest-framework<3.7
    from rest_framework import filters
from rest_framework import viewsets
from teryt_tree.models import JednostkaAdministracyjna
from teryt_tree.rest_framework_ext.serializers import \
    JednostkaAdministracyjnaSerializer

def custom_area_filter(queryset, _, value):
    if not value:
        return queryset
    return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value))

class JednostkaAdministracyjnaFilter(filters.FilterSet):
    area = django_filters.CharFilter(
        method=custom_area_filter,
        label=_("Area")
    )

    class Meta:
        model = JednostkaAdministracyjna
        fields = ['name', 'category', 'category__level', 'area']

class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet):
    queryset = (JednostkaAdministracyjna.objects.
                select_related('category').
                prefetch_related('children').
                all())
    serializer_class = JednostkaAdministracyjnaSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = JednostkaAdministracyjnaFilter

Response:
<REPLACE_OLD> get_object_or_404
try:
 <REPLACE_NEW> get_object_or_404
from django.utils.translation import ugettext_lazy as _

try:
 <REPLACE_END> <INSERT> \
    <INSERT_END> <REPLACE_OLD> django_filters.CharFilter(action=custom_area_filter)

 <REPLACE_NEW> django_filters.CharFilter(
        method=custom_area_filter,
        label=_("Area")
    )

 <REPLACE_END> <|endoftext|> import django_filters
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _

try:
    from django_filters import rest_framework as filters
except ImportError:  # Back-ward compatible for django-rest-framework<3.7
    from rest_framework import filters
from rest_framework import viewsets
from teryt_tree.models import JednostkaAdministracyjna
from teryt_tree.rest_framework_ext.serializers import \
    JednostkaAdministracyjnaSerializer

def custom_area_filter(queryset, _, value):
    if not value:
        return queryset
    return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value))

class JednostkaAdministracyjnaFilter(filters.FilterSet):
    area = django_filters.CharFilter(
        method=custom_area_filter,
        label=_("Area")
    )

    class Meta:
        model = JednostkaAdministracyjna
        fields = ['name', 'category', 'category__level', 'area']

class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet):
    queryset = (JednostkaAdministracyjna.objects.
                select_related('category').
                prefetch_related('children').
                all())
    serializer_class = JednostkaAdministracyjnaSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = JednostkaAdministracyjnaFilter

Prompt:
Update JednostkaAdministracyjnaFilter for new django-filters

import django_filters
from django.shortcuts import get_object_or_404
try:
    from django_filters import rest_framework as filters
except ImportError:  # Back-ward compatible for django-rest-framework<3.7
    from rest_framework import filters
from rest_framework import viewsets
from teryt_tree.models import JednostkaAdministracyjna
from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer

def custom_area_filter(queryset, _, value):
    if not value:
        return queryset
    return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value))

class JednostkaAdministracyjnaFilter(filters.FilterSet):
    area = django_filters.CharFilter(action=custom_area_filter)

    class Meta:
        model = JednostkaAdministracyjna
        fields = ['name', 'category', 'category__level', 'area']

class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet):
    queryset = (JednostkaAdministracyjna.objects.
                select_related('category').
                prefetch_related('children').
                all())
    serializer_class = JednostkaAdministracyjnaSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = JednostkaAdministracyjnaFilter


 # -*- coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    # Drop view that inhibits changing field types. It will be recreated BTW
    cr.execute('drop view if exists report_document_user cascade')

[IMP] document: Remove annoying SQL view that prevents some operations

Response:
<INSERT> # -*- coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    # Drop view that inhibits changing field types. It will be recreated BTW
    cr.execute('drop view if exists report_document_user cascade')
 <INSERT_END> <|endoftext|>  # -*- coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    # Drop view that inhibits changing field types. It will be recreated BTW
    cr.execute('drop view if exists report_document_user cascade')

Prompt: [IMP] document: Remove annoying SQL view that prevents some operations


"""
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from django.views.generic import TemplateView as BaseTemplateView

from sentry.web.helpers import render_to_response

def static_media(request, **kwargs):
    """
    Serve static files below a given point in the directory structure.
    """
    from django.contrib.staticfiles.views import serve

    module = kwargs.get('module')
    path = kwargs.get('path', '')

    if module:
        path = '%s/%s' % (module, path)

    response = serve(request, path, insecure=True)

    # We need CORS for font files
    if path.endswith(('.eot', '.ttf', '.woff', '.js')):
        response['Access-Control-Allow-Origin'] = '*'
    return response

class TemplateView(BaseTemplateView):
    def render_to_response(self, context, **response_kwargs):
        return render_to_response(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            **response_kwargs
        )

Response:
<REPLACE_OLD> '.woff')):
 <REPLACE_NEW> '.woff', '.js')):
 <REPLACE_END> <|endoftext|> """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from django.views.generic import TemplateView as BaseTemplateView

from sentry.web.helpers import render_to_response

def static_media(request, **kwargs):
    """
    Serve static files below a given point in the directory structure.
    """
    from django.contrib.staticfiles.views import serve

    module = kwargs.get('module')
    path = kwargs.get('path', '')

    if module:
        path = '%s/%s' % (module, path)

    response = serve(request, path, insecure=True)

    # We need CORS for font files
    if path.endswith(('.eot', '.ttf', '.woff', '.js')):
        response['Access-Control-Allow-Origin'] = '*'
    return response

class TemplateView(BaseTemplateView):
    def render_to_response(self, context, **response_kwargs):
        return render_to_response(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            **response_kwargs
        )

Prompt:
Add CORS headers to js files for local dev

"""
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from django.views.generic import TemplateView as BaseTemplateView

from sentry.web.helpers import render_to_response

def static_media(request, **kwargs):
    """
    Serve static files below a given point in the directory structure.
    """
    from django.contrib.staticfiles.views import serve

    module = kwargs.get('module')
    path = kwargs.get('path', '')

    if module:
        path = '%s/%s' % (module, path)

    response = serve(request, path, insecure=True)

    # We need CORS for font files
    if path.endswith(('.eot', '.ttf', '.woff')):
        response['Access-Control-Allow-Origin'] = '*'
    return response

class TemplateView(BaseTemplateView):
    def render_to_response(self, context, **response_kwargs):
        return render_to_response(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            **response_kwargs
        )


# -*- coding: utf-8 -*-
import click

from jungle import __version__

class JungleCLI(click.MultiCommand):

    """Jangle CLI main class"""

    def list_commands(self, ctx):
        """return available modules"""
        return ['ec2', 'elb']

    def get_command(self, ctx, name):
        """get command"""
        mod = __import__('jungle.' + name, None, None, ['cli'])
        return mod.cli

cli = JungleCLI(help="aws operation cli (v{})".format(__version__))

if __name__ == '__main__':
    cli()

Add version number to help text

Add version number to help text

Response:
<REPLACE_OLD> click

class <REPLACE_NEW> click

from jungle import __version__

class <REPLACE_END> <REPLACE_OLD> JungleCLI(help='aws <REPLACE_NEW> JungleCLI(help="aws <REPLACE_END> <REPLACE_OLD> cli')

if <REPLACE_NEW> cli (v{})".format(__version__))

if <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import click

from jungle import __version__

class JungleCLI(click.MultiCommand):

    """Jangle CLI main class"""

    def list_commands(self, ctx):
        """return available modules"""
        return ['ec2', 'elb']

    def get_command(self, ctx, name):
        """get command"""
        mod = __import__('jungle.' + name, None, None, ['cli'])
        return mod.cli

cli = JungleCLI(help="aws operation cli (v{})".format(__version__))

if __name__ == '__main__':
    cli()

Prompt:
Add version number to help text

# -*- coding: utf-8 -*-
import click

class JungleCLI(click.MultiCommand):

    """Jangle CLI main class"""

    def list_commands(self, ctx):
        """return available modules"""
        return ['ec2', 'elb']

    def get_command(self, ctx, name):
        """get command"""
        mod = __import__('jungle.' + name, None, None, ['cli'])
        return mod.cli

cli = JungleCLI(help='aws operation cli')

if __name__ == '__main__':
    cli()


import functools

DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):

def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
    """
    A middleware that allow CORS calls, by adding the
    headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
    This middlware accepts two optional parameters `allow_origin` and
    `allow_headers` for customization of the headers values. By default
    will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]`
    respectively.
    """

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if not response.headers:
            response.headers = {}

        response.headers['Access-Control-Allow-Origin'] = allow_origin
        response.headers['Access-Control-Allow-Headers'] = ', '.join(allow_headers)
        return response

    return wrapper

Response:
<REPLACE_OLD> functools

def wrap_cors(
    func=None,
    *,
    allow_origin='*',
    allow_headers=set(["Origin", "X-Requested-With", "Content-Type", "Accept"])):
 <REPLACE_NEW> functools

DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):

def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
 <REPLACE_END> <|endoftext|> import functools

DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):

def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
    """
    A middleware that allow CORS calls, by adding the
    headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
    This middlware accepts two optional parameters `allow_origin` and
    `allow_headers` for customization of the headers values. By default
    will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]`
    respectively.
    """

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if not response.headers:
            response.headers = {}

        response.headers['Access-Control-Allow-Origin'] = allow_origin
        response.headers['Access-Control-Allow-Headers'] = ', '.join(allow_headers)
        return response

    return wrapper

Prompt:
Put default headers as constant and make it immutable.

With additional cosmetic fixes.

import functools

def wrap_cors(
    func=None,
    *,
    allow_origin='*',
    allow_headers=set(["Origin", "X-Requested-With", "Content-Type", "Accept"])):
    """
    A middleware that allow CORS calls, by adding the
    headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
    This middlware accepts two optional parameters `allow_origin` and
    `allow_headers` for customization of the headers values. By default
    will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]`
    respectively.
    """

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if not response.headers:
            response.headers = {}

        response.headers['Access-Control-Allow-Origin'] = allow_origin
        response.headers['Access-Control-Allow-Headers'] = ', '.join(allow_headers)
        return response

    return wrapper


#! /usr/bin/env python3
""" Helper functions to make our life easier.

Originally obtained from the 'pharm' repository, but modified.
"""

import fileinput
import json
import os.path
import sys

from dstruct.Sentence import Sentence

## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file__))
BASE_DIR = os.path.realpath(BASE_DIR + "/../..")

## Return the start and end indexes of all subsets of words in the sentence
## sent, with size at most max_phrase_length
def get_all_phrases_in_sentence(sent, max_phrase_length):
    for start in range(len(sent.words)):
        for end in reversed(range(start + 1, min(len(sent.words), start + 1 + max_phrase_length))):
            yield (start, end)

## Return Sentence objects from input lines
def get_input_sentences(input_files=sys.argv[1:]):
    with fileinput.input(files=input_files) as f:
        for line in f:
            sent_dict = json.loads(line)
            yield Sentence(sent_dict["doc_id"], sent_dict["sent_id"],
                    sent_dict["wordidxs"], sent_dict["words"],
                    sent_dict["poses"], sent_dict["ners"], sent_dict["lemmas"],
                    sent_dict["dep_paths"], sent_dict["dep_parents"],
                    sent_dict["bounding_boxes"])

Response:
<REPLACE_OLD> os.path

from dstruct <REPLACE_NEW> os.path
import sys

from dstruct.Sentence <REPLACE_END> <REPLACE_OLD> get_input_sentences(input_files=[]):
 <REPLACE_NEW> get_input_sentences(input_files=sys.argv[1:]):
    with fileinput.input(files=input_files) as f:
     <REPLACE_END> <REPLACE_OLD> fileinput.input(input_files):
 <REPLACE_NEW> f:
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> #! /usr/bin/env python3
""" Helper functions to make our life easier.

Originally obtained from the 'pharm' repository, but modified.
"""

import fileinput
import json
import os.path
import sys

from dstruct.Sentence import Sentence

## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file__))
BASE_DIR = os.path.realpath(BASE_DIR + "/../..")

## Return the start and end indexes of all subsets of words in the sentence
## sent, with size at most max_phrase_length
def get_all_phrases_in_sentence(sent, max_phrase_length):
    for start in range(len(sent.words)):
        for end in reversed(range(start + 1, min(len(sent.words), start + 1 + max_phrase_length))):
            yield (start, end)

## Return Sentence objects from input lines
def get_input_sentences(input_files=sys.argv[1:]):
    with fileinput.input(files=input_files) as f:
        for line in f:
            sent_dict = json.loads(line)
            yield Sentence(sent_dict["doc_id"], sent_dict["sent_id"],
                    sent_dict["wordidxs"], sent_dict["words"],
                    sent_dict["poses"], sent_dict["ners"], sent_dict["lemmas"],
                    sent_dict["dep_paths"], sent_dict["dep_parents"],
                    sent_dict["bounding_boxes"])

Prompt:
Fix import, use fileinput.iput as context, and fix its argument

#! /usr/bin/env python3
""" Helper functions to make our life easier.

Originally obtained from the 'pharm' repository, but modified.
"""

import fileinput
import json
import os.path

from dstruct import Sentence

## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file__))
BASE_DIR = os.path.realpath(BASE_DIR + "/../..")

## Return the start and end indexes of all subsets of words in the sentence
## sent, with size at most max_phrase_length
def get_all_phrases_in_sentence(sent, max_phrase_length):
    for start in range(len(sent.words)):
        for end in reversed(range(start + 1, min(len(sent.words), start + 1 + max_phrase_length))):
            yield (start, end)

## Return Sentence objects from input lines
def get_input_sentences(input_files=[]):
    for line in fileinput.input(input_files):
        sent_dict = json.loads(line)
        yield Sentence(sent_dict["doc_id"], sent_dict["sent_id"],
                sent_dict["wordidxs"], sent_dict["words"],
                sent_dict["poses"], sent_dict["ners"], sent_dict["lemmas"],
                sent_dict["dep_paths"], sent_dict["dep_parents"],
                sent_dict["bounding_boxes"])


"""Leetcode 246. Strobogrammatic Number
Easy

URL: https://leetcode.com/problems/strobogrammatic-number/A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Write a function to determine if a number is strobogrammatic. The number is
represented as a string.

Example 1:
Input:  "69"
Output: true

Example 2:
Input:  "88"
Output: true

Example 3:
Input:  "962"
Output: false
"""

class SolutionMapDictIter(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool

        Time complexity: O(n).
        Space complexity: O(n).
        """
        # Reverse num.
        rev_num = num[::-1]

        # Convert to mapped number or empty string.
        map_d = {
            '0': '0',
            '1': '1',
            '6': '9',
            '8': '8',
            '9': '6'
        }

        mapped_num_ls = []
        for n in rev_num:
            if n in map_d:
                mapped_num_ls.append(map_d[n])
            else:
                mapped_num_ls.append(' ')
        mapped_num = ''.join(mapped_num_ls)

        # Check if strobogrammatic.
        return mapped_num == num

def main():
    # Output: true
    num = "69"
    print SolutionMapDictIter().isStrobogrammatic(num)

    # Output: true
    num = "88"
    print SolutionMapDictIter().isStrobogrammatic(num)

    # Output: false
    num = "962"
    print SolutionMapDictIter().isStrobogrammatic(num)

    # Output: false
    num = "2"
    print SolutionMapDictIter().isStrobogrammatic(num)

if __name__ == '__main__':
    main()

Response:
<REPLACE_OLD> Solution(object):
 <REPLACE_NEW> SolutionMapDictIter(object):
 <REPLACE_END> <REPLACE_OLD> bool
 <REPLACE_NEW> bool

        Time complexity: O(n).
        Space complexity: O(n).
 <REPLACE_END> <REPLACE_OLD> pass

def <REPLACE_NEW> # Reverse num.
        rev_num = num[::-1]

        # Convert to mapped number or empty string.
        map_d = {
            '0': '0',
            '1': '1',
            '6': '9',
            '8': '8',
            '9': '6'
        }

        mapped_num_ls = []
        for n in rev_num:
            if n in map_d:
                mapped_num_ls.append(map_d[n])
            else:
                mapped_num_ls.append(' ')
        mapped_num = ''.join(mapped_num_ls)

        # Check if strobogrammatic.
        return mapped_num == num

def <REPLACE_END> <REPLACE_OLD> Solution().isStrobogrammatic(num)

 <REPLACE_NEW> SolutionMapDictIter().isStrobogrammatic(num)

 <REPLACE_END> <REPLACE_OLD> Solution().isStrobogrammatic(num)

 <REPLACE_NEW> SolutionMapDictIter().isStrobogrammatic(num)

 <REPLACE_END> <REPLACE_OLD> Solution().isStrobogrammatic(num)

if <REPLACE_NEW> SolutionMapDictIter().isStrobogrammatic(num)

    # Output: false
    num = "2"
    print SolutionMapDictIter().isStrobogrammatic(num)

if <REPLACE_END> <|endoftext|> """Leetcode 246. Strobogrammatic Number
Easy

URL: https://leetcode.com/problems/strobogrammatic-number/A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Write a function to determine if a number is strobogrammatic. The number is
represented as a string.

Example 1:
Input:  "69"
Output: true

Example 2:
Input:  "88"
Output: true

Example 3:
Input:  "962"
Output: false
"""

class SolutionMapDictIter(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool

        Time complexity: O(n).
        Space complexity: O(n).
        """
        # Reverse num.
        rev_num = num[::-1]

        # Convert to mapped number or empty string.
        map_d = {
            '0': '0',
            '1': '1',
            '6': '9',
            '8': '8',
            '9': '6'
        }

        mapped_num_ls = []
        for n in rev_num:
            if n in map_d:
                mapped_num_ls.append(map_d[n])
            else:
                mapped_num_ls.append(' ')
        mapped_num = ''.join(mapped_num_ls)

        # Check if strobogrammatic.
        return mapped_num == num

def main():
    # Output: true
    num = "69"
    print SolutionMapDictIter().isStrobogrammatic(num)

    # Output: true
    num = "88"
    print SolutionMapDictIter().isStrobogrammatic(num)

    # Output: false
    num = "962"
    print SolutionMapDictIter().isStrobogrammatic(num)

    # Output: false
    num = "2"
    print SolutionMapDictIter().isStrobogrammatic(num)

if __name__ == '__main__':
    main()

Prompt:
Complete map dict sol w/ time/space complexity

"""Leetcode 246. Strobogrammatic Number
Easy

URL: https://leetcode.com/problems/strobogrammatic-number/A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Write a function to determine if a number is strobogrammatic. The number is
represented as a string.

Example 1:
Input:  "69"
Output: true

Example 2:
Input:  "88"
Output: true

Example 3:
Input:  "962"
Output: false
"""

class Solution(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool
        """
        pass

def main():
    # Output: true
    num = "69"
    print Solution().isStrobogrammatic(num)

    # Output: true
    num = "88"
    print Solution().isStrobogrammatic(num)

    # Output: false
    num = "962"
    print Solution().isStrobogrammatic(num)

if __name__ == '__main__':
    main()


import logging
logger = logging.getLogger('djpg')

from django.dispatch import Signal
from .codes import codes

notification_received = Signal(providing_args=['notification'])
transaction_received = Signal(providing_args=['transaction'])

transaction_waiting = Signal()
transaction_analysis = Signal()
transaction_paid = Signal()
transaction_available = Signal()
transaction_dispute = Signal()
transaction_returned = Signal()
transaction_canceled = Signal()
transaction_unknown = Signal()

def dispatch_transaction(sender, **kwargs):
    transaction = kwargs.pop('transaction')
    code = transaction['code']
    status = int(transaction['status'])

    signals = {
        codes.waiting: transaction_waiting,
        codes.analysis: transaction_analysis,
        codes.paid: transaction_paid,
        codes.available: transaction_available,
        codes.dispute: transaction_dispute,
        codes.returned: transaction_returned,
        codes.canceled: transaction_canceled
    }

    signals \
        .get(status, transaction_unknown) \
        .send(sender=None, transaction=transaction)

    logger.info('Transaction with status "%s" and code "%s" dispatched'
                % (status, code))

transaction_received.connect(dispatch_transaction)

Response:
<REPLACE_OLD> int(transaction['code'])
 <REPLACE_NEW> transaction['code']
 <REPLACE_END> <|endoftext|> import logging
logger = logging.getLogger('djpg')

from django.dispatch import Signal
from .codes import codes

notification_received = Signal(providing_args=['notification'])
transaction_received = Signal(providing_args=['transaction'])

transaction_waiting = Signal()
transaction_analysis = Signal()
transaction_paid = Signal()
transaction_available = Signal()
transaction_dispute = Signal()
transaction_returned = Signal()
transaction_canceled = Signal()
transaction_unknown = Signal()

def dispatch_transaction(sender, **kwargs):
    transaction = kwargs.pop('transaction')
    code = transaction['code']
    status = int(transaction['status'])

    signals = {
        codes.waiting: transaction_waiting,
        codes.analysis: transaction_analysis,
        codes.paid: transaction_paid,
        codes.available: transaction_available,
        codes.dispute: transaction_dispute,
        codes.returned: transaction_returned,
        codes.canceled: transaction_canceled
    }

    signals \
        .get(status, transaction_unknown) \
        .send(sender=None, transaction=transaction)

    logger.info('Transaction with status "%s" and code "%s" dispatched'
                % (status, code))

transaction_received.connect(dispatch_transaction)

Prompt:
Fix bug when trying to convert transaction code to int

import logging
logger = logging.getLogger('djpg')

from django.dispatch import Signal
from .codes import codes

notification_received = Signal(providing_args=['notification'])
transaction_received = Signal(providing_args=['transaction'])

transaction_waiting = Signal()
transaction_analysis = Signal()
transaction_paid = Signal()
transaction_available = Signal()
transaction_dispute = Signal()
transaction_returned = Signal()
transaction_canceled = Signal()
transaction_unknown = Signal()

def dispatch_transaction(sender, **kwargs):
    transaction = kwargs.pop('transaction')
    code = int(transaction['code'])
    status = int(transaction['status'])

    signals = {
        codes.waiting: transaction_waiting,
        codes.analysis: transaction_analysis,
        codes.paid: transaction_paid,
        codes.available: transaction_available,
        codes.dispute: transaction_dispute,
        codes.returned: transaction_returned,
        codes.canceled: transaction_canceled
    }

    signals \
        .get(status, transaction_unknown) \
        .send(sender=None, transaction=transaction)

    logger.info('Transaction with status "%s" and code "%s" dispatched'
                % (status, code))

transaction_received.connect(dispatch_transaction)


"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck

TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}

def test_provider_healthcheck():
    """Make sure default Provider Health Check works."""
    health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
    assert health_checks.providers == []
    assert health_checks.has_healthcheck == False

Update Provider Health Check sanity

Response:
<REPLACE_OLD> provider_healthcheck, has_provider_healthcheck <REPLACE_NEW> health_checks <REPLACE_END> <REPLACE_OLD> provider_healthcheck <REPLACE_NEW> health_checks.providers <REPLACE_END> <REPLACE_OLD> has_provider_healthcheck <REPLACE_NEW> health_checks.has_healthcheck <REPLACE_END> <|endoftext|> """Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck

TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}

def test_provider_healthcheck():
    """Make sure default Provider Health Check works."""
    health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
    assert health_checks.providers == []
    assert health_checks.has_healthcheck == False

Prompt:
test: Update Provider Health Check sanity

See also: PSOBAT-2465

"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck

TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}

def test_provider_healthcheck():
    """Make sure default Provider Health Check works."""
    provider_healthcheck, has_provider_healthcheck = check_provider_healthcheck(settings=TEST_SETTINGS)
    assert provider_healthcheck == []
    assert has_provider_healthcheck == False


from sure import expect

from simpleflow import activity
from simpleflow.swf.task import ActivityTask

@activity.with_attributes()
def show_context_func():
    return show_context_func.context

@activity.with_attributes()
class ShowContextCls(object):
    def execute(self):
        return self.context

def test_task_has_an_empty_context_by_default():
    expect(ActivityTask(show_context_func).execute()).to.be.none
    expect(ActivityTask(ShowContextCls).execute()).to.be.none

def test_task_attaches_context_to_functions():
    ctx = {'foo': 'bar'}
    expect(ActivityTask(show_context_func, context=ctx).execute()).to.equal(ctx)
    expect(show_context_func.context).to.equal(ctx)

def test_task_attaches_context_to_object_instances():
    ctx = {'foo': 'bar'}
    expect(ActivityTask(ShowContextCls, context=ctx).execute()).to.equal(ctx)
    expect(ShowContextCls.context).to.be.none

Add tests to ensure ActivityTask attaches the context

Response:
<INSERT> from sure import expect

from simpleflow import activity
from simpleflow.swf.task import ActivityTask

@activity.with_attributes()
def show_context_func():
 <INSERT_END> <INSERT>   return show_context_func.context

@activity.with_attributes()
class ShowContextCls(object):
    def execute(self):
        return self.context

def test_task_has_an_empty_context_by_default():
    expect(ActivityTask(show_context_func).execute()).to.be.none
    expect(ActivityTask(ShowContextCls).execute()).to.be.none

def test_task_attaches_context_to_functions():
    ctx = {'foo': 'bar'}
    expect(ActivityTask(show_context_func, context=ctx).execute()).to.equal(ctx)
    expect(show_context_func.context).to.equal(ctx)

def test_task_attaches_context_to_object_instances():
    ctx = {'foo': 'bar'}
    expect(ActivityTask(ShowContextCls, context=ctx).execute()).to.equal(ctx)
    expect(ShowContextCls.context).to.be.none
 <INSERT_END> <|endoftext|> from sure import expect

from simpleflow import activity
from simpleflow.swf.task import ActivityTask

@activity.with_attributes()
def show_context_func():
    return show_context_func.context

@activity.with_attributes()
class ShowContextCls(object):
    def execute(self):
        return self.context

def test_task_has_an_empty_context_by_default():
    expect(ActivityTask(show_context_func).execute()).to.be.none
    expect(ActivityTask(ShowContextCls).execute()).to.be.none

def test_task_attaches_context_to_functions():
    ctx = {'foo': 'bar'}
    expect(ActivityTask(show_context_func, context=ctx).execute()).to.equal(ctx)
    expect(show_context_func.context).to.equal(ctx)

def test_task_attaches_context_to_object_instances():
    ctx = {'foo': 'bar'}
    expect(ActivityTask(ShowContextCls, context=ctx).execute()).to.equal(ctx)
    expect(ShowContextCls.context).to.be.none

Prompt: Add tests to ensure ActivityTask attaches the context


import asyncio
import logging

import os

from warreport import battle_monitor, battle_reporting

logger = logging.getLogger("warreport")

def main():
    logger.info("Starting main loop.")
    logger.debug("Debug logging enabled.")
    loop = asyncio.get_event_loop()
    gathered_future = asyncio.gather(
        battle_monitor.grab_new_battles(loop),
        battle_monitor.process_battles(loop),
        battle_reporting.report_battles(loop),
        loop=loop,
    )
    try:
        loop.run_until_complete(gathered_future)
    except KeyboardInterrupt:
        logger.info("Caught KeyboardInterrupt: Ending main loop.")
        gathered_future.cancel()
        loop.run_forever()
        gathered_future.exception()
    finally:
        loop.close()
    logger.info("Ended successfully.")
    # TODO: this is basically so I don't have to Ctrl+C twice to exit. I don't know what holds up the process, and it
    # would definitely be a good idea to find out!
    os._exit(0)

if __name__ == '__main__':
    main()

Make another try at graceful exiting.

Response:
<REPLACE_OLD> logging

from <REPLACE_NEW> logging

import os

from <REPLACE_END> <REPLACE_OLD> loop.run_until_complete(asyncio.gather(
 <REPLACE_NEW> gathered_future = asyncio.gather(
 <REPLACE_END> <REPLACE_OLD> ))

if <REPLACE_NEW>     loop=loop,
    )
    try:
        loop.run_until_complete(gathered_future)
    except KeyboardInterrupt:
        logger.info("Caught KeyboardInterrupt: Ending main loop.")
        gathered_future.cancel()
        loop.run_forever()
        gathered_future.exception()
    finally:
        loop.close()
    logger.info("Ended successfully.")
    # TODO: this is basically so I don't have to Ctrl+C twice to exit. I don't know what holds up the process, and it
    # would definitely be a good idea to find out!
    os._exit(0)

if <REPLACE_END> <|endoftext|> import asyncio
import logging

import os

from warreport import battle_monitor, battle_reporting

logger = logging.getLogger("warreport")

def main():
    logger.info("Starting main loop.")
    logger.debug("Debug logging enabled.")
    loop = asyncio.get_event_loop()
    gathered_future = asyncio.gather(
        battle_monitor.grab_new_battles(loop),
        battle_monitor.process_battles(loop),
        battle_reporting.report_battles(loop),
        loop=loop,
    )
    try:
        loop.run_until_complete(gathered_future)
    except KeyboardInterrupt:
        logger.info("Caught KeyboardInterrupt: Ending main loop.")
        gathered_future.cancel()
        loop.run_forever()
        gathered_future.exception()
    finally:
        loop.close()
    logger.info("Ended successfully.")
    # TODO: this is basically so I don't have to Ctrl+C twice to exit. I don't know what holds up the process, and it
    # would definitely be a good idea to find out!
    os._exit(0)

if __name__ == '__main__':
    main()

Prompt:
Make another try at graceful exiting.

This still does use os._exit() after all coroutines have finished, but it's significantly less spaghetti code, and it makes it nicer to exit the program.

import asyncio
import logging

from warreport import battle_monitor, battle_reporting

logger = logging.getLogger("warreport")

def main():
    logger.info("Starting main loop.")
    logger.debug("Debug logging enabled.")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(
        battle_monitor.grab_new_battles(loop),
        battle_monitor.process_battles(loop),
        battle_reporting.report_battles(loop),
    ))

if __name__ == '__main__':
    main()


from django.core.management.base import NoArgsCommand
import os
import shutil

class Command(NoArgsCommand):
    help = "Copy the satchmo static directory and files to the local project."

    def handle_noargs(self, **options):
        import satchmo
        static_src = os.path.join(satchmo.__path__[0],'static')
        static_dest = os.path.join(os.getcwd(), 'static')
        if os.path.exists(static_dest):
            print "Static directory exists. You must manually copy the files you need."
        else:
            shutil.copytree(static_src, static_dest)
            print "Copied %s to %s" % (static_src, static_dest)

Add an error check to static copying

Add an error check to static copying

Response:
<INSERT> if os.path.exists(static_dest):
            print "Static directory exists. You must manually copy the files you need."
        else:
            <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> from django.core.management.base import NoArgsCommand
import os
import shutil

class Command(NoArgsCommand):
    help = "Copy the satchmo static directory and files to the local project."

    def handle_noargs(self, **options):
        import satchmo
        static_src = os.path.join(satchmo.__path__[0],'static')
        static_dest = os.path.join(os.getcwd(), 'static')
        if os.path.exists(static_dest):
            print "Static directory exists. You must manually copy the files you need."
        else:
            shutil.copytree(static_src, static_dest)
            print "Copied %s to %s" % (static_src, static_dest)

Prompt:
Add an error check to static copying

from django.core.management.base import NoArgsCommand
import os
import shutil

class Command(NoArgsCommand):
    help = "Copy the satchmo static directory and files to the local project."

    def handle_noargs(self, **options):
        import satchmo
        static_src = os.path.join(satchmo.__path__[0],'static')
        static_dest = os.path.join(os.getcwd(), 'static')
        shutil.copytree(static_src, static_dest)
        print "Copied %s to %s" % (static_src, static_dest)


from conans import ConanFile, CMake

class ArgsConan(ConanFile):
    name = "cfgfile"
    version = "0.2.8.2"
    url = "https://github.com/igormironchik/cfgfile.git"
    license = "MIT"
    description = "Header-only library for reading/saving configuration files with schema defined in sources."
    exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp"

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder="generator")
        cmake.build()

    def package(self):
        self.copy("COPYING", src=".", dst=".")
        self.copy("*", src="cfgfile", dst="cfgfile")
        self.copy("*", src="generator", dst="generator")
        self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args")

    def package_info(self):
        self.cpp_info.includedirs = ["."]

Add build step into Conan recipe.

Add build step into Conan recipe.

Response:
<REPLACE_OLD> ConanFile

class <REPLACE_NEW> ConanFile, CMake

class <REPLACE_END> <REPLACE_OLD> "3rdparty/Args/Args/*.hpp"

 <REPLACE_NEW> "3rdparty/Args/Args/*.hpp"

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder="generator")
        cmake.build()

 <REPLACE_END> <|endoftext|> from conans import ConanFile, CMake

class ArgsConan(ConanFile):
    name = "cfgfile"
    version = "0.2.8.2"
    url = "https://github.com/igormironchik/cfgfile.git"
    license = "MIT"
    description = "Header-only library for reading/saving configuration files with schema defined in sources."
    exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp"

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder="generator")
        cmake.build()

    def package(self):
        self.copy("COPYING", src=".", dst=".")
        self.copy("*", src="cfgfile", dst="cfgfile")
        self.copy("*", src="generator", dst="generator")
        self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args")

    def package_info(self):
        self.cpp_info.includedirs = ["."]

Prompt:
Add build step into Conan recipe.

from conans import ConanFile

class ArgsConan(ConanFile):
    name = "cfgfile"
    version = "0.2.8.2"
    url = "https://github.com/igormironchik/cfgfile.git"
    license = "MIT"
    description = "Header-only library for reading/saving configuration files with schema defined in sources."
    exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp"

    def package(self):
        self.copy("COPYING", src=".", dst=".")
        self.copy("*", src="cfgfile", dst="cfgfile")
        self.copy("*", src="generator", dst="generator")
        self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args")

    def package_info(self):
        self.cpp_info.includedirs = ["."]


from setuptools import setup, find_packages

setup(
    name='django-force-logout',

    url="https://chris-lamb.co.uk/projects/django-force-logout",
    version='2.0.0',
    description="Framework to be able to forcibly log users out of Django projects",

    author="Chris Lamb",
    author_email='chris@chris-lamb.co.uk',
    license="BSD",

    packages=find_packages(),

    install_requires=(
        'Django>=1.8',
    ),
)

Update Django requirement to latest LTS

Update Django requirement to latest LTS

Response:
<REPLACE_OLD> packages=find_packages(),
)
 <REPLACE_NEW> packages=find_packages(),

    install_requires=(
        'Django>=1.8',
    ),
)
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='django-force-logout',

    url="https://chris-lamb.co.uk/projects/django-force-logout",
    version='2.0.0',
    description="Framework to be able to forcibly log users out of Django projects",

    author="Chris Lamb",
    author_email='chris@chris-lamb.co.uk',
    license="BSD",

    packages=find_packages(),

    install_requires=(
        'Django>=1.8',
    ),
)

Prompt:
Update Django requirement to latest LTS

from setuptools import setup, find_packages

setup(
    name='django-force-logout',

    url="https://chris-lamb.co.uk/projects/django-force-logout",
    version='2.0.0',
    description="Framework to be able to forcibly log users out of Django projects",

    author="Chris Lamb",
    author_email='chris@chris-lamb.co.uk',
    license="BSD",

    packages=find_packages(),
)


import codecs
from lxml import etree
from bs4 import BeautifulSoup
from emotools.bs4_helpers import act, sentence, word, speaker_turn, note
import argparse
import os
import re
import sys

if __name__ == '__main__':
    folia = '/home/jvdzwaan/data/embem-annotatie/vinc001pefr02_01.xml'
    tag = '/home/jvdzwaan/data/embem-annotatie-tag-fix/vinc001pefr02/vinc001pefr02_01__act-01.tag'
    #tag = '/home/jvdzwaan/data/kaf2folia/vinc001pefr02/vinc001pefr02_01__act-01.tag'
    out_dir = '/home/jvdzwaan/data/embem-annotatie-tag-fix/'

    d, file_name = os.path.split(tag)
    out_file = os.path.join(out_dir, file_name)

    print 'Saving file to', out_file

    # lees tag file in geheugen
    with codecs.open(tag, 'rb', 'utf-8') as f:
        tag_lines = f.readlines()
    print 'Found {} tags'.format(len(tag_lines))
    tags = iter(tag_lines)

    curr_tag = None
    # word ids that start with lg-added must be replaced
    reg = r'^lg-added-\d+'

    word_tag = '{http://ilk.uvt.nl/folia}w'

    # Load folia document
    context = etree.iterparse(folia, events=('end',), tag=word_tag)

    # open file for output
    with codecs.open(out_file, 'wb', 'utf-8') as f:
        for event, elem in context:
            if not curr_tag:
                try:
                    curr_tag = tags.next()

                    parts = curr_tag.split('\t')
                    tag_id = parts[0]
                    tag_word = parts[1]

                    print 'looking for', tag_id
                except StopIteration:
                    sys.exit()

            if event == 'end':
                word_xml = BeautifulSoup(etree.tostring(elem), 'xml')
                w = word_xml.find(word)
                w_id = w.attrs.get('xml:id')
                w_word = w.t.string

                match_part = re.sub(reg, '', tag_id)
                #if re.match(reg, tag_id):
                #    print 'tag_id matches regex', tag_id, w_id
                if w_id.endswith(match_part) and w_word == tag_word:
                    print 'found match:'
                    print w_id, w_word
                    print tag_id, tag_word
                    #print '{}\t{}'.format(w_id, '\t'.join(parts[1:]).encode('utf-8'))
                    f.write('{}\t{}'.format(w_id, '\t'.join(parts[1:]).encode('utf-8')).decode('utf-8'))
                    curr_tag = None

Add a script that fixes tag files

Add a script that fixes tag files

The kaf files used for annotation were generated using folia files
contain strange ids (starting with lg-added). Unfortunately, these
folia files were not saved. Therefore, the word ids in the kaf files
must be updated to the word ids in the new folia files. This script does
that for hardcoded input.
The next step is to turn these parameters into command line arguments
and to call this script with a bash script that runs the fix_tags script
for all tag files in a directory.

Response:
<REPLACE_OLD>  <REPLACE_NEW> import codecs
from lxml import etree
from bs4 import BeautifulSoup
from emotools.bs4_helpers import act, sentence, word, speaker_turn, note
import argparse
import os
import re
import sys

if __name__ == '__main__':
    folia = '/home/jvdzwaan/data/embem-annotatie/vinc001pefr02_01.xml'
    tag = '/home/jvdzwaan/data/embem-annotatie-tag-fix/vinc001pefr02/vinc001pefr02_01__act-01.tag'
    #tag = '/home/jvdzwaan/data/kaf2folia/vinc001pefr02/vinc001pefr02_01__act-01.tag'
    out_dir = '/home/jvdzwaan/data/embem-annotatie-tag-fix/'

    d, file_name = os.path.split(tag)
    out_file = os.path.join(out_dir, file_name)

    print 'Saving file to', out_file

    # lees tag file in geheugen
    with codecs.open(tag, 'rb', 'utf-8') as f:
        tag_lines = f.readlines()
    print 'Found {} tags'.format(len(tag_lines))
    tags = iter(tag_lines)

    curr_tag = None
    # word ids that start with lg-added must be replaced
    reg = r'^lg-added-\d+'

    word_tag = '{http://ilk.uvt.nl/folia}w'

    # Load folia document
    context = etree.iterparse(folia, events=('end',), tag=word_tag)

    # open file for output
    with codecs.open(out_file, 'wb', 'utf-8') as f:
        for event, elem in context:
            if not curr_tag:
                try:
                    curr_tag = tags.next()

                    parts = curr_tag.split('\t')
                    tag_id = parts[0]
                    tag_word = parts[1]

                    print 'looking for', tag_id
                except StopIteration:
                    sys.exit()

            if event == 'end':
                word_xml = BeautifulSoup(etree.tostring(elem), 'xml')
                w = word_xml.find(word)
                w_id = w.attrs.get('xml:id')
                w_word = w.t.string

                match_part = re.sub(reg, '', tag_id)
                #if re.match(reg, tag_id):
                #    print 'tag_id matches regex', tag_id, w_id
                if w_id.endswith(match_part) and w_word == tag_word:
                    print 'found match:'
                    print w_id, w_word
                    print tag_id, tag_word
                    #print '{}\t{}'.format(w_id, '\t'.join(parts[1:]).encode('utf-8'))
                    f.write('{}\t{}'.format(w_id, '\t'.join(parts[1:]).encode('utf-8')).decode('utf-8'))
                    curr_tag = None
 <REPLACE_END> <|endoftext|> import codecs
from lxml import etree
from bs4 import BeautifulSoup
from emotools.bs4_helpers import act, sentence, word, speaker_turn, note
import argparse
import os
import re
import sys

if __name__ == '__main__':
    folia = '/home/jvdzwaan/data/embem-annotatie/vinc001pefr02_01.xml'
    tag = '/home/jvdzwaan/data/embem-annotatie-tag-fix/vinc001pefr02/vinc001pefr02_01__act-01.tag'
    #tag = '/home/jvdzwaan/data/kaf2folia/vinc001pefr02/vinc001pefr02_01__act-01.tag'
    out_dir = '/home/jvdzwaan/data/embem-annotatie-tag-fix/'

    d, file_name = os.path.split(tag)
    out_file = os.path.join(out_dir, file_name)

    print 'Saving file to', out_file

    # lees tag file in geheugen
    with codecs.open(tag, 'rb', 'utf-8') as f:
        tag_lines = f.readlines()
    print 'Found {} tags'.format(len(tag_lines))
    tags = iter(tag_lines)

    curr_tag = None
    # word ids that start with lg-added must be replaced
    reg = r'^lg-added-\d+'

    word_tag = '{http://ilk.uvt.nl/folia}w'

    # Load folia document
    context = etree.iterparse(folia, events=('end',), tag=word_tag)

    # open file for output
    with codecs.open(out_file, 'wb', 'utf-8') as f:
        for event, elem in context:
            if not curr_tag:
                try:
                    curr_tag = tags.next()

                    parts = curr_tag.split('\t')
                    tag_id = parts[0]
                    tag_word = parts[1]

                    print 'looking for', tag_id
                except StopIteration:
                    sys.exit()

            if event == 'end':
                word_xml = BeautifulSoup(etree.tostring(elem), 'xml')
                w = word_xml.find(word)
                w_id = w.attrs.get('xml:id')
                w_word = w.t.string

                match_part = re.sub(reg, '', tag_id)
                #if re.match(reg, tag_id):
                #    print 'tag_id matches regex', tag_id, w_id
                if w_id.endswith(match_part) and w_word == tag_word:
                    print 'found match:'
                    print w_id, w_word
                    print tag_id, tag_word
                    #print '{}\t{}'.format(w_id, '\t'.join(parts[1:]).encode('utf-8'))
                    f.write('{}\t{}'.format(w_id, '\t'.join(parts[1:]).encode('utf-8')).decode('utf-8'))
                    curr_tag = None

Prompt:
Add a script that fixes tag files

The kaf files used for annotation were generated using folia files
contain strange ids (starting with lg-added). Unfortunately, these
folia files were not saved. Therefore, the word ids in the kaf files
must be updated to the word ids in the new folia files. This script does
that for hardcoded input.
The next step is to turn these parameters into command line arguments
and to call this script with a bash script that runs the fix_tags script
for all tag files in a directory.


import igraph

def packing_graph(tets, vx, vy, vz, independent = 0):
    N = len(tets)
    for i in range(N-1, independent-1, -1):
      for s in tets[i].get_symetry(vx, vy, vz, include_self=False):
          if tets[i].collision(s):
              del tets[i]
              break

    N = len(tets)
    g = igraph.Graph()
    g.add_vertices(N)
    for i in range(N):
        for j in range(max(i, independent),N):
            for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)):
                if tets[i].collision(s):
                    g.add_edge(i,j)
                    break

    return g

Response:
<INSERT>    N = len(tets)
    for i in range(N-1, independent-1, -1):
      for s in tets[i].get_symetry(vx, vy, vz, include_self=False):
          if tets[i].collision(s):
              del tets[i]
              break

 <INSERT_END> <REPLACE_OLD> break
    edges = g.get_edgelist()
    for i in range(N, -1, -1):
        if (i,i) in edges:
            g.delete_vertices(g.vs[i])
            del tets[i]
 <REPLACE_NEW> break

 <REPLACE_END> <|endoftext|> import igraph

def packing_graph(tets, vx, vy, vz, independent = 0):
    N = len(tets)
    for i in range(N-1, independent-1, -1):
      for s in tets[i].get_symetry(vx, vy, vz, include_self=False):
          if tets[i].collision(s):
              del tets[i]
              break

    N = len(tets)
    g = igraph.Graph()
    g.add_vertices(N)
    for i in range(N):
        for j in range(max(i, independent),N):
            for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)):
                if tets[i].collision(s):
                    g.add_edge(i,j)
                    break

    return g

Prompt:
Remove self-touching tets first to reduce collision load.

import igraph

def packing_graph(tets, vx, vy, vz, independent = 0):
    N = len(tets)
    g = igraph.Graph()
    g.add_vertices(N)
    for i in range(N):
        for j in range(max(i, independent),N):
            for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)):
                if tets[i].collision(s):
                    g.add_edge(i,j)
                    break
    edges = g.get_edgelist()
    for i in range(N, -1, -1):
        if (i,i) in edges:
            g.delete_vertices(g.vs[i])
            del tets[i]
    return g


# -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms

from parler.admin import TranslatableTabularInline
from adminsortable.admin import SortableTabularInline
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from allink_core.allink_base.admin import AllinkBaseAdminSortable

from allink_apps.work.models import Work, Highlights

class HighlightsInline(SortableTabularInline, TranslatableTabularInline):
    model = Highlights
    extra = 1
    max_num = 10
    verbose_name = _(u'Highlight')
    verbose_name_plural = _(u'Highlights')

@admin.register(Work)
class WorkAdmin(PlaceholderAdminMixin, AllinkBaseAdminSortable):
    inlines = [HighlightsInline, ]
    list_filter = ('is_active', 'categories',)

    def get_fieldsets(self, request, obj=None):
        fieldsets = (
            (None, {
                'fields': (
                    'is_active',
                    'title',
                    'slug',
                    'lead',
                    'preview_image',
                ),
            }),
        )

        fieldsets += self.get_base_fieldsets()

        return fieldsets

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'lead':
            kwargs['widget'] = forms.Textarea
        return super(WorkAdmin, self).formfield_for_dbfield(db_field, **kwargs)

TEST allink_apps subtree - pulling

TEST allink_apps subtree - pulling

Response:
<REPLACE_OLD> forms
from django.utils.translation import ugettext_lazy as _

from <REPLACE_NEW> forms

from <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms

from parler.admin import TranslatableTabularInline
from adminsortable.admin import SortableTabularInline
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from allink_core.allink_base.admin import AllinkBaseAdminSortable

from allink_apps.work.models import Work, Highlights

class HighlightsInline(SortableTabularInline, TranslatableTabularInline):
    model = Highlights
    extra = 1
    max_num = 10
    verbose_name = _(u'Highlight')
    verbose_name_plural = _(u'Highlights')

@admin.register(Work)
class WorkAdmin(PlaceholderAdminMixin, AllinkBaseAdminSortable):
    inlines = [HighlightsInline, ]
    list_filter = ('is_active', 'categories',)

    def get_fieldsets(self, request, obj=None):
        fieldsets = (
            (None, {
                'fields': (
                    'is_active',
                    'title',
                    'slug',
                    'lead',
                    'preview_image',
                ),
            }),
        )

        fieldsets += self.get_base_fieldsets()

        return fieldsets

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'lead':
            kwargs['widget'] = forms.Textarea
        return super(WorkAdmin, self).formfield_for_dbfield(db_field, **kwargs)

Prompt:
TEST allink_apps subtree - pulling

# -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.utils.translation import ugettext_lazy as _

from parler.admin import TranslatableTabularInline
from adminsortable.admin import SortableTabularInline
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from allink_core.allink_base.admin import AllinkBaseAdminSortable

from allink_apps.work.models import Work, Highlights

class HighlightsInline(SortableTabularInline, TranslatableTabularInline):
    model = Highlights
    extra = 1
    max_num = 10
    verbose_name = _(u'Highlight')
    verbose_name_plural = _(u'Highlights')

@admin.register(Work)
class WorkAdmin(PlaceholderAdminMixin, AllinkBaseAdminSortable):
    inlines = [HighlightsInline, ]
    list_filter = ('is_active', 'categories',)

    def get_fieldsets(self, request, obj=None):
        fieldsets = (
            (None, {
                'fields': (
                    'is_active',
                    'title',
                    'slug',
                    'lead',
                    'preview_image',
                ),
            }),
        )

        fieldsets += self.get_base_fieldsets()

        return fieldsets

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'lead':
            kwargs['widget'] = forms.Textarea
        return super(WorkAdmin, self).formfield_for_dbfield(db_field, **kwargs)


#!/usr/bin/env python

try:
    from setuptools import setup
    extra = dict(test_suite="tests.test.suite", include_package_data=True)
except ImportError:
    from distutils.core import setup
    extra = {}

long_description = \
'''
A python library for console-based raw input-based questions with answers and
extensive and extensible validation for answers.
'''

from qav import __version__

setup(
    name='qav',
    version=__version__,
    author='Derek Yarnell',
    author_email='derek@umiacs.umd.edu',
    packages=['qav'],
    url='https://github.com/UMIACS/qav',
    license='MIT',
    description='Question Answer Validation',
    long_description=long_description,
    **extra
)

Response:
<REPLACE_OLD> url='https://gitlab.umiacs.umd.edu/staff/qav',
 <REPLACE_NEW> url='https://github.com/UMIACS/qav',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

try:
    from setuptools import setup
    extra = dict(test_suite="tests.test.suite", include_package_data=True)
except ImportError:
    from distutils.core import setup
    extra = {}

long_description = \
'''
A python library for console-based raw input-based questions with answers and
extensive and extensible validation for answers.
'''

from qav import __version__

setup(
    name='qav',
    version=__version__,
    author='Derek Yarnell',
    author_email='derek@umiacs.umd.edu',
    packages=['qav'],
    url='https://github.com/UMIACS/qav',
    license='MIT',
    description='Question Answer Validation',
    long_description=long_description,
    **extra
)

Prompt:
Update the project URL to point to github.

#!/usr/bin/env python

try:
    from setuptools import setup
    extra = dict(test_suite="tests.test.suite", include_package_data=True)
except ImportError:
    from distutils.core import setup
    extra = {}

long_description = \
'''
A python library for console-based raw input-based questions with answers and
extensive and extensible validation for answers.
'''

from qav import __version__

setup(
    name='qav',
    version=__version__,
    author='Derek Yarnell',
    author_email='derek@umiacs.umd.edu',
    packages=['qav'],
    url='https://gitlab.umiacs.umd.edu/staff/qav',
    license='MIT',
    description='Question Answer Validation',
    long_description=long_description,
    **extra
)


from django.contrib import admin

from .models import Person, Residence, RelationshipType, Relationship

class ResidenceInline(admin.TabularInline):
    '''Inline class for Residence'''
    model = Residence

class PersonAdmin(admin.ModelAdmin):
    inlines = [
        ResidenceInline
    ]

admin.site.register(Person, PersonAdmin)
admin.site.register(RelationshipType)
admin.site.register(Relationship)

Response:
<REPLACE_OLD> Relationship

admin.site.register(Person)
admin.site.register(Residence)
admin.site.register(RelationshipType)
admin.site.register(Relationship)

 <REPLACE_NEW> Relationship

class ResidenceInline(admin.TabularInline):
    '''Inline class for Residence'''
    model = Residence

class PersonAdmin(admin.ModelAdmin):
    inlines = [
        ResidenceInline
    ]

admin.site.register(Person, PersonAdmin)
admin.site.register(RelationshipType)
admin.site.register(Relationship)
 <REPLACE_END> <|endoftext|> from django.contrib import admin

from .models import Person, Residence, RelationshipType, Relationship

class ResidenceInline(admin.TabularInline):
    '''Inline class for Residence'''
    model = Residence

class PersonAdmin(admin.ModelAdmin):
    inlines = [
        ResidenceInline
    ]

admin.site.register(Person, PersonAdmin)
admin.site.register(RelationshipType)
admin.site.register(Relationship)

Prompt:
Add residence as an inline to person/people

from django.contrib import admin

from .models import Person, Residence, RelationshipType, Relationship

admin.site.register(Person)
admin.site.register(Residence)
admin.site.register(RelationshipType)
admin.site.register(Relationship)


from django.contrib import admin

from import_export.admin import ImportExportMixin

from .models import Book, Category, Author

class BookAdmin(ImportExportMixin, admin.ModelAdmin):
    list_filter = ['categories', 'author']

admin.site.register(Book, BookAdmin)
admin.site.register(Category)
admin.site.register(Author)

Add BookAdmin options in test app

Add BookAdmin options in test app

Response:
<REPLACE_OLD> pass

admin.site.register(Book, <REPLACE_NEW> list_filter = ['categories', 'author']

admin.site.register(Book, <REPLACE_END> <|endoftext|> from django.contrib import admin

from import_export.admin import ImportExportMixin

from .models import Book, Category, Author

class BookAdmin(ImportExportMixin, admin.ModelAdmin):
    list_filter = ['categories', 'author']

admin.site.register(Book, BookAdmin)
admin.site.register(Category)
admin.site.register(Author)

Prompt:
Add BookAdmin options in test app

from django.contrib import admin

from import_export.admin import ImportExportMixin

from .models import Book, Category, Author

class BookAdmin(ImportExportMixin, admin.ModelAdmin):
    pass

admin.site.register(Book, BookAdmin)
admin.site.register(Category)
admin.site.register(Author)


# -*- coding: utf-8 -*-
from pygtkhelpers.utils import refresh_gui
import uuid

def gtk_wait(wait_duration_s):
    refresh_gui()

def generate_plugin_name(prefix='plugin-'):
    '''
    Generate unique plugin name.
    '''
    return prefix + str(uuid.uuid4()).split('-')[0]

Response:
<REPLACE_OLD> -*-
import gtk
import <REPLACE_NEW> -*-
from pygtkhelpers.utils import refresh_gui
import <REPLACE_END> <REPLACE_OLD> gtk.main_iteration_do()

def <REPLACE_NEW> refresh_gui()

def <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from pygtkhelpers.utils import refresh_gui
import uuid

def gtk_wait(wait_duration_s):
    refresh_gui()

def generate_plugin_name(prefix='plugin-'):
    '''
    Generate unique plugin name.
    '''
    return prefix + str(uuid.uuid4()).split('-')[0]

Prompt:
Use pygtkhelpers refresh_gui in gtk_wait

# -*- coding: utf-8 -*-
import gtk
import uuid

def gtk_wait(wait_duration_s):
    gtk.main_iteration_do()

def generate_plugin_name(prefix='plugin-'):
    '''
    Generate unique plugin name.
    '''
    return prefix + str(uuid.uuid4()).split('-')[0]


import collections
import math
import unittest

import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json

class MyrialTestCase(unittest.TestCase):

    def setUp(self):
        self.db = raco.fakedb.FakeDatabase()
        self.parser = parser.Parser()
        self.processor = interpreter.StatementProcessor(self.db)

    def execute_query(self, query, test_logical=False):
        '''Run a test query against the fake database'''
        statements = self.parser.parse(query)
        self.processor.evaluate(statements)

        if test_logical:
            plan = self.processor.get_logical_plan()
        else:
            plan = self.processor.get_physical_plan()
            json = compile_to_json(query, '', [('A', plan)])

        self.db.evaluate(plan)

        return self.db.get_temp_table('__OUTPUT0__')

    def run_test(self, query, expected, test_logical=False):
        '''Execute a test query with an expected output'''
        actual = self.execute_query(query, test_logical)
        self.assertEquals(actual, expected)

Response:
<REPLACE_OLD> parser

class <REPLACE_NEW> parser
from raco.myrialang import compile_to_json

class <REPLACE_END> <REPLACE_OLD> self.db.evaluate(plan)

 <REPLACE_NEW>     json = compile_to_json(query, '', [('A', plan)])

        self.db.evaluate(plan)

 <REPLACE_END> <|endoftext|>
import collections
import math
import unittest

import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json

class MyrialTestCase(unittest.TestCase):

    def setUp(self):
        self.db = raco.fakedb.FakeDatabase()
        self.parser = parser.Parser()
        self.processor = interpreter.StatementProcessor(self.db)

    def execute_query(self, query, test_logical=False):
        '''Run a test query against the fake database'''
        statements = self.parser.parse(query)
        self.processor.evaluate(statements)

        if test_logical:
            plan = self.processor.get_logical_plan()
        else:
            plan = self.processor.get_physical_plan()
            json = compile_to_json(query, '', [('A', plan)])

        self.db.evaluate(plan)

        return self.db.get_temp_table('__OUTPUT0__')

    def run_test(self, query, expected, test_logical=False):
        '''Execute a test query with an expected output'''
        actual = self.execute_query(query, test_logical)
        self.assertEquals(actual, expected)

Prompt:
Add compile_to_json invocation in Myrial test fixture

import collections
import math
import unittest

import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser

class MyrialTestCase(unittest.TestCase):

    def setUp(self):
        self.db = raco.fakedb.FakeDatabase()
        self.parser = parser.Parser()
        self.processor = interpreter.StatementProcessor(self.db)

    def execute_query(self, query, test_logical=False):
        '''Run a test query against the fake database'''
        statements = self.parser.parse(query)
        self.processor.evaluate(statements)

        if test_logical:
            plan = self.processor.get_logical_plan()
        else:
            plan = self.processor.get_physical_plan()
        self.db.evaluate(plan)

        return self.db.get_temp_table('__OUTPUT0__')

    def run_test(self, query, expected, test_logical=False):
        '''Execute a test query with an expected output'''
        actual = self.execute_query(query, test_logical)
        self.assertEquals(actual, expected)


import os
import subprocess

name = "gobuildmaster"

current_hash = ""
if os.path.isfile('hash'):
    current_hash = open('hash').readlines()[0]
new_hash = os.popen('git rev-parse HEAD').readlines()[0]
open('hash','w').write(new_hash)

# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
    print line.strip()

# Rebuild
for line in os.popen('go build').readlines():
    print line.strip()

size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)

lines = os.popen('ps -ef | grep ' + name).readlines()
running = False
for line in lines:
    if "./" + name in line:
        running = True

if size_1 != size_2 or new_hash != current_hash or not running:
    if not running:
        for line in os.popen('cat out.txt | mail -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines():
            pass
    for line in os.popen('echo "" > out.txt').readlines():
        pass
    for line in os.popen('killall ' + name).readlines():
        pass
    subprocess.Popen(['./' + name, "--quiet=false"])

Fix running detection for master

Fix running detection for master

Response:
<REPLACE_OLD> name)

running = len(os.popen('ps <REPLACE_NEW> name)

lines = os.popen('ps <REPLACE_END> <REPLACE_OLD> name).readlines()) > 3

 <REPLACE_NEW> name).readlines()
running = False
for line in lines:
    if "./" + name in line:
        running = True

 <REPLACE_END> <|endoftext|> import os
import subprocess

name = "gobuildmaster"

current_hash = ""
if os.path.isfile('hash'):
    current_hash = open('hash').readlines()[0]
new_hash = os.popen('git rev-parse HEAD').readlines()[0]
open('hash','w').write(new_hash)

# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
    print line.strip()

# Rebuild
for line in os.popen('go build').readlines():
    print line.strip()

size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)

lines = os.popen('ps -ef | grep ' + name).readlines()
running = False
for line in lines:
    if "./" + name in line:
        running = True

if size_1 != size_2 or new_hash != current_hash or not running:
    if not running:
        for line in os.popen('cat out.txt | mail -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines():
            pass
    for line in os.popen('echo "" > out.txt').readlines():
        pass
    for line in os.popen('killall ' + name).readlines():
        pass
    subprocess.Popen(['./' + name, "--quiet=false"])

Prompt:
Fix running detection for master

import os
import subprocess

name = "gobuildmaster"

current_hash = ""
if os.path.isfile('hash'):
    current_hash = open('hash').readlines()[0]
new_hash = os.popen('git rev-parse HEAD').readlines()[0]
open('hash','w').write(new_hash)

# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
    print line.strip()

# Rebuild
for line in os.popen('go build').readlines():
    print line.strip()

size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)

running = len(os.popen('ps -ef | grep ' + name).readlines()) > 3

if size_1 != size_2 or new_hash != current_hash or not running:
    if not running:
        for line in os.popen('cat out.txt | mail -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines():
            pass
    for line in os.popen('echo "" > out.txt').readlines():
        pass
    for line in os.popen('killall ' + name).readlines():
        pass
    subprocess.Popen(['./' + name, "--quiet=false"])


"""
Package configuration
"""
# pylint:disable=no-name-in-module, import-error
from distutils.core import setup
from setuptools import find_packages

setup(
    name='IXWSAuth',
    version='0.1.1',
    author='Infoxchanhe Australia dev team',
    author_email='devs@infoxchange.net.au',
    packages=find_packages(),
    url='http://pypi.python.org/pypi/IXWSAuth/',
    license='MIT',
    description='Authentication libraries for IX web services',
    long_description=open('README').read(),
    install_requires=(
        'Django >= 1.4.0',
        'IXDjango >= 0.1.1',
    ),
    tests_require=(
        'aloe',
        'django-tastypie',
        'mock',
        'pep8',
        'pylint',
        'pylint-mccabe',
    )
)

Response:
<DELETE> 'django-tastypie',
        <DELETE_END> <INSERT>        'django-tastypie',
 <INSERT_END> <|endoftext|> """
Package configuration
"""
# pylint:disable=no-name-in-module, import-error
from distutils.core import setup
from setuptools import find_packages

setup(
    name='IXWSAuth',
    version='0.1.1',
    author='Infoxchanhe Australia dev team',
    author_email='devs@infoxchange.net.au',
    packages=find_packages(),
    url='http://pypi.python.org/pypi/IXWSAuth/',
    license='MIT',
    description='Authentication libraries for IX web services',
    long_description=open('README').read(),
    install_requires=(
        'Django >= 1.4.0',
        'IXDjango >= 0.1.1',
    ),
    tests_require=(
        'aloe',
        'django-tastypie',
        'mock',
        'pep8',
        'pylint',
        'pylint-mccabe',
    )
)

Prompt:
Downgrade tastypie to test-only dependency

"""
Package configuration
"""
# pylint:disable=no-name-in-module, import-error
from distutils.core import setup
from setuptools import find_packages

setup(
    name='IXWSAuth',
    version='0.1.1',
    author='Infoxchanhe Australia dev team',
    author_email='devs@infoxchange.net.au',
    packages=find_packages(),
    url='http://pypi.python.org/pypi/IXWSAuth/',
    license='MIT',
    description='Authentication libraries for IX web services',
    long_description=open('README').read(),
    install_requires=(
        'Django >= 1.4.0',
        'django-tastypie',
        'IXDjango >= 0.1.1',
    ),
    tests_require=(
        'aloe',
        'mock',
        'pep8',
        'pylint',
        'pylint-mccabe',
    )
)


import time

def timed_func(func):
    """Decorator for timing our traversal methods."""
    def timed(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        # print "time expired: %s" % elapsed
        return (result, elapsed)
    return timed

@timed_func
def insertion(_list):
    '''Sorts a list via the insertion method.'''
    if type(_list) is not list:
        raise TypeError('Entire list must be numbers')
    for i in range(1, len(_list)):

        key = _list[i]
        if not isinstance(key, int):
            raise TypeError('Entire list must be numbers')
        position = i

        while position > 0 and _list[position-1] > key:
            _list[position] = _list[position-1]
            position = position-1

        _list[position] = key

    return _list

if __name__ == '__main__':
    lengths = [10, 100, 1000, 10000]
    times = []
    for x in lengths:
        output = insertion(range(x))
        times.append(output[1])
    print 'Best case scenario:'
    for length, tim in zip(lengths, times):
        print 'a list of length {} was sorted in {}'.format(length, tim)
    diff = []
    for x in range(len(times)-2):
        diff.append(times[x+1]/times[x])
    average = reduce(lambda x, y: x+y, diff) / len(diff)
    print 'As length increases by 10, time increases by {}'.format(average)

    lengths = [10, 100, 1000, 10000]
    times = []
    for x in lengths:
        output = insertion(range(x)[::-1])
        times.append(output[1])
    print 'Worse case scenario:'
    for length, tim in zip(lengths, times):
        print 'a list of length {} was sorted in {}'.format(length, tim)
    diff = []
    for x in range(len(times)-2):
        diff.append(times[x+1]/times[x])
    average = reduce(lambda x, y: x+y, diff) / len(diff)
    print 'As length increases by 10, time increases by {}'.format(average)

Add timing to show time complexity.

Add timing to show time complexity.

Response:
<REPLACE_OLD> timeit

def <REPLACE_NEW> time

def timed_func(func):
    """Decorator for timing our traversal methods."""
    def timed(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        # print "time expired: %s" % elapsed
        return (result, elapsed)
    return timed

@timed_func
def <REPLACE_END> <REPLACE_OLD> _list

if <REPLACE_NEW> _list

if <REPLACE_END> <REPLACE_OLD> input = [1, 3, 2]
 <REPLACE_NEW> lengths = [10, 100, 1000, 10000]
    times = []
    for x in lengths:
     <REPLACE_END> <REPLACE_OLD> insertion(input)
    print output

    timeit.timeit(insertion(input))
 <REPLACE_NEW> insertion(range(x))
        times.append(output[1])
    print 'Best case scenario:'
    for length, tim in zip(lengths, times):
        print 'a list of length {} was sorted in {}'.format(length, tim)
    diff = []
    for x in range(len(times)-2):
        diff.append(times[x+1]/times[x])
    average = reduce(lambda x, y: x+y, diff) / len(diff)
    print 'As length increases by 10, time increases by {}'.format(average)

    lengths = [10, 100, 1000, 10000]
    times = []
    for x in lengths:
        output = insertion(range(x)[::-1])
        times.append(output[1])
    print 'Worse case scenario:'
    for length, tim in zip(lengths, times):
        print 'a list of length {} was sorted in {}'.format(length, tim)
    diff = []
    for x in range(len(times)-2):
        diff.append(times[x+1]/times[x])
    average = reduce(lambda x, y: x+y, diff) / len(diff)
    print 'As length increases by 10, time increases by {}'.format(average)

 <REPLACE_END> <|endoftext|> import time

def timed_func(func):
    """Decorator for timing our traversal methods."""
    def timed(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        # print "time expired: %s" % elapsed
        return (result, elapsed)
    return timed

@timed_func
def insertion(_list):
    '''Sorts a list via the insertion method.'''
    if type(_list) is not list:
        raise TypeError('Entire list must be numbers')
    for i in range(1, len(_list)):

        key = _list[i]
        if not isinstance(key, int):
            raise TypeError('Entire list must be numbers')
        position = i

        while position > 0 and _list[position-1] > key:
            _list[position] = _list[position-1]
            position = position-1

        _list[position] = key

    return _list

if __name__ == '__main__':
    lengths = [10, 100, 1000, 10000]
    times = []
    for x in lengths:
        output = insertion(range(x))
        times.append(output[1])
    print 'Best case scenario:'
    for length, tim in zip(lengths, times):
        print 'a list of length {} was sorted in {}'.format(length, tim)
    diff = []
    for x in range(len(times)-2):
        diff.append(times[x+1]/times[x])
    average = reduce(lambda x, y: x+y, diff) / len(diff)
    print 'As length increases by 10, time increases by {}'.format(average)

    lengths = [10, 100, 1000, 10000]
    times = []
    for x in lengths:
        output = insertion(range(x)[::-1])
        times.append(output[1])
    print 'Worse case scenario:'
    for length, tim in zip(lengths, times):
        print 'a list of length {} was sorted in {}'.format(length, tim)
    diff = []
    for x in range(len(times)-2):
        diff.append(times[x+1]/times[x])
    average = reduce(lambda x, y: x+y, diff) / len(diff)
    print 'As length increases by 10, time increases by {}'.format(average)

Prompt:
Add timing to show time complexity.

import timeit

def insertion(_list):
    '''Sorts a list via the insertion method.'''
    if type(_list) is not list:
        raise TypeError('Entire list must be numbers')
    for i in range(1, len(_list)):

        key = _list[i]
        if not isinstance(key, int):
            raise TypeError('Entire list must be numbers')
        position = i

        while position > 0 and _list[position-1] > key:
            _list[position] = _list[position-1]
            position = position-1

        _list[position] = key

    return _list

if __name__ == '__main__':
    input = [1, 3, 2]
    output = insertion(input)
    print output

    timeit.timeit(insertion(input))


# Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: andraz@reciprocitylabs.com
# Maintained By: andraz@reciprocitylabs.com

"""
Test that some objects cannot be deleted by anyone.
"""

from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.generator import ObjectGenerator

class TestReader(TestCase):
  """Test that some objects cannot be deleted by anyone."""

  def setUp(self):
    TestCase.setUp(self)
    self.api = Api()
    self.object_generator = ObjectGenerator()
    self.init_users()
    self.init_objects()

  def init_users(self):
    """ Init users needed by the test cases """
    users = [("creator", "Creator"), ("reader", "Reader"),
             ("editor", "Editor"), ("admin", "gGRC Admin")]
    self.users = {}
    for (name, role) in users:
      _, user = self.object_generator.generate_person(
          data={"name": name}, user_role=role)
      self.users[name] = user

  def init_objects(self):
    """Creates the objects used by all the tests"""
    self.api.set_user(self.users["admin"])
    _, person = self.object_generator.generate_person()

    self.objects = [person]

  def test_undeletable_objects(self):
    """No user shoud be allowed to delete these objects."""
    for role, user in self.users.iteritems():
      self.api.set_user(user)
      for obj in self.objects:
        response = self.api.delete(obj)
        self.assertEqual(response.status_code, 403,
                         "{} can delete {}".format(role, obj.type))

Add a test for objects that cannot be deleted

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: andraz@reciprocitylabs.com
# Maintained By: andraz@reciprocitylabs.com

"""
Test that some objects cannot be deleted by anyone.
"""

from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.generator import ObjectGenerator

class TestReader(TestCase):
  """Test that some objects cannot be deleted by anyone."""

  def setUp(self):
    TestCase.setUp(self)
    self.api = Api()
    self.object_generator = ObjectGenerator()
    self.init_users()
    self.init_objects()

  def init_users(self):
    """ Init users needed by the test cases """
    users = [("creator", "Creator"), ("reader", "Reader"),
             ("editor", "Editor"), ("admin", "gGRC Admin")]
    self.users = {}
    for (name, role) in users:
      _, user = self.object_generator.generate_person(
          data={"name": name}, user_role=role)
      self.users[name] = user

  def init_objects(self):
    """Creates the objects used by all the tests"""
    self.api.set_user(self.users["admin"])
    _, person = self.object_generator.generate_person()

    self.objects = [person]

  def test_undeletable_objects(self):
    """No user shoud be allowed to delete these objects."""
    for role, user in self.users.iteritems():
      self.api.set_user(user)
      for obj in self.objects:
        response = self.api.delete(obj)
        self.assertEqual(response.status_code, 403,
                         "{} can delete {}".format(role, obj.type))
 <REPLACE_END> <|endoftext|> # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: andraz@reciprocitylabs.com
# Maintained By: andraz@reciprocitylabs.com

"""
Test that some objects cannot be deleted by anyone.
"""

from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.generator import ObjectGenerator

class TestReader(TestCase):
  """Test that some objects cannot be deleted by anyone."""

  def setUp(self):
    TestCase.setUp(self)
    self.api = Api()
    self.object_generator = ObjectGenerator()
    self.init_users()
    self.init_objects()

  def init_users(self):
    """ Init users needed by the test cases """
    users = [("creator", "Creator"), ("reader", "Reader"),
             ("editor", "Editor"), ("admin", "gGRC Admin")]
    self.users = {}
    for (name, role) in users:
      _, user = self.object_generator.generate_person(
          data={"name": name}, user_role=role)
      self.users[name] = user

  def init_objects(self):
    """Creates the objects used by all the tests"""
    self.api.set_user(self.users["admin"])
    _, person = self.object_generator.generate_person()

    self.objects = [person]

  def test_undeletable_objects(self):
    """No user shoud be allowed to delete these objects."""
    for role, user in self.users.iteritems():
      self.api.set_user(user)
      for obj in self.objects:
        response = self.api.delete(obj)
        self.assertEqual(response.status_code, 403,
                         "{} can delete {}".format(role, obj.type))

Prompt: Add a test for objects that cannot be deleted