#!/usr/bin/env python

import removinator
import subprocess

# This example cycles through each card slot in the Removinator.  Any
# slots that have a card present will then have the certificates on the
# card printed out using the pkcs15-tool utility, which is provided by
# the OpenSC project.
#
# Examples of parsing the Removinator status output and enabling debug
# output from the firmware are also provided.

print('--- Connecting to Removinator ---')
ctl = removinator.Removinator()

print('--- Cycling through cards ---')
for card in range(1, 9):
    try:
        ctl.insert_card(card)
        print('Inserted card {0}'.format(card))
        print('{0}'.format(subprocess.check_output(['pkcs15-tool',
                                                   '--list-certificates'])
                           .rstrip()))
    except removinator.SlotError:
        print('Card {0} is not inserted'.format(card))

print('--- Checking Removinator status ---')
status = ctl.get_status()
print('Current card: {0}'.format(status['current']))
for card in status['present']:
    print('Card {0} is present'.format(card))

print('--- Debug output for re-insertion of current card ---')
ctl.set_debug(True)
ctl.insert_card(status['current'])
print('{0}'.format(ctl.last_response.rstrip()))
ctl.set_debug(False)

print('--- Remove current card ---')
ctl.remove_card()

Use python from env in example script

Response:
<REPLACE_OLD> #!/bin/python

import <REPLACE_NEW> #!/usr/bin/env python

import <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import removinator
import subprocess

# This example cycles through each card slot in the Removinator.  Any
# slots that have a card present will then have the certificates on the
# card printed out using the pkcs15-tool utility, which is provided by
# the OpenSC project.
#
# Examples of parsing the Removinator status output and enabling debug
# output from the firmware are also provided.

print('--- Connecting to Removinator ---')
ctl = removinator.Removinator()

print('--- Cycling through cards ---')
for card in range(1, 9):
    try:
        ctl.insert_card(card)
        print('Inserted card {0}'.format(card))
        print('{0}'.format(subprocess.check_output(['pkcs15-tool',
                                                   '--list-certificates'])
                           .rstrip()))
    except removinator.SlotError:
        print('Card {0} is not inserted'.format(card))

print('--- Checking Removinator status ---')
status = ctl.get_status()
print('Current card: {0}'.format(status['current']))
for card in status['present']:
    print('Card {0} is present'.format(card))

print('--- Debug output for re-insertion of current card ---')
ctl.set_debug(True)
ctl.insert_card(status['current'])
print('{0}'.format(ctl.last_response.rstrip()))
ctl.set_debug(False)

print('--- Remove current card ---')
ctl.remove_card()

Prompt:
Use python from env in example script

This makes the cycle-cards example script use python from the env
instead of harcoding the location.  This allows a virtualenv to be
easily used.

#!/bin/python

import removinator
import subprocess

# This example cycles through each card slot in the Removinator.  Any
# slots that have a card present will then have the certificates on the
# card printed out using the pkcs15-tool utility, which is provided by
# the OpenSC project.
#
# Examples of parsing the Removinator status output and enabling debug
# output from the firmware are also provided.

print('--- Connecting to Removinator ---')
ctl = removinator.Removinator()

print('--- Cycling through cards ---')
for card in range(1, 9):
    try:
        ctl.insert_card(card)
        print('Inserted card {0}'.format(card))
        print('{0}'.format(subprocess.check_output(['pkcs15-tool',
                                                   '--list-certificates'])
                           .rstrip()))
    except removinator.SlotError:
        print('Card {0} is not inserted'.format(card))

print('--- Checking Removinator status ---')
status = ctl.get_status()
print('Current card: {0}'.format(status['current']))
for card in status['present']:
    print('Card {0} is present'.format(card))

print('--- Debug output for re-insertion of current card ---')
ctl.set_debug(True)
ctl.insert_card(status['current'])
print('{0}'.format(ctl.last_response.rstrip()))
ctl.set_debug(False)

print('--- Remove current card ---')
ctl.remove_card()


from mock import Mock

from main.management.commands.merge_coverage_files import Command
from main.tests.helper_methods import mock_out_unwanted_methods

def test_merge_coverage_handle_calls_parse_options():
    merge_coverage_files_command = Command()

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['prepare_packagefilters', 'write_filtered_data', 'write_merged_data'])

    merge_coverage_files_command.parse_options = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.parse_options.called

def test_merge_coverage_handle_calls_prepare_packagefilters():
    merge_coverage_files_command = Command()

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'write_filtered_data', 'write_merged_data'])

    merge_coverage_files_command.prepare_packagefilters = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.prepare_packagefilters.called

def test_write_filtered_data_called_when_filteronly_is_true():
    merge_coverage_files_command = Command()
    merge_coverage_files_command.filteronly = True

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'prepare_packagefilters', 'write_merged_data'])

    merge_coverage_files_command.write_filtered_data = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.write_filtered_data.called

def test_write_merged_data_called_when_filteronly_is_false():
    merge_coverage_files_command = Command()
    merge_coverage_files_command.filteronly = False

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'prepare_packagefilters', 'write_filtered_data'])

    merge_coverage_files_command.write_merged_data = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.write_merged_data.called

Add tests to run command to merge content

Response:
<INSERT> from mock import Mock

from main.management.commands.merge_coverage_files import Command
from main.tests.helper_methods import mock_out_unwanted_methods

def test_merge_coverage_handle_calls_parse_options():
 <INSERT_END> <INSERT>   merge_coverage_files_command = Command()

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['prepare_packagefilters', 'write_filtered_data', 'write_merged_data'])

    merge_coverage_files_command.parse_options = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.parse_options.called

def test_merge_coverage_handle_calls_prepare_packagefilters():
    merge_coverage_files_command = Command()

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'write_filtered_data', 'write_merged_data'])

    merge_coverage_files_command.prepare_packagefilters = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.prepare_packagefilters.called

def test_write_filtered_data_called_when_filteronly_is_true():
    merge_coverage_files_command = Command()
    merge_coverage_files_command.filteronly = True

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'prepare_packagefilters', 'write_merged_data'])

    merge_coverage_files_command.write_filtered_data = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.write_filtered_data.called

def test_write_merged_data_called_when_filteronly_is_false():
    merge_coverage_files_command = Command()
    merge_coverage_files_command.filteronly = False

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'prepare_packagefilters', 'write_filtered_data'])

    merge_coverage_files_command.write_merged_data = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.write_merged_data.called
 <INSERT_END> <|endoftext|> from mock import Mock

from main.management.commands.merge_coverage_files import Command
from main.tests.helper_methods import mock_out_unwanted_methods

def test_merge_coverage_handle_calls_parse_options():
    merge_coverage_files_command = Command()

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['prepare_packagefilters', 'write_filtered_data', 'write_merged_data'])

    merge_coverage_files_command.parse_options = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.parse_options.called

def test_merge_coverage_handle_calls_prepare_packagefilters():
    merge_coverage_files_command = Command()

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'write_filtered_data', 'write_merged_data'])

    merge_coverage_files_command.prepare_packagefilters = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.prepare_packagefilters.called

def test_write_filtered_data_called_when_filteronly_is_true():
    merge_coverage_files_command = Command()
    merge_coverage_files_command.filteronly = True

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'prepare_packagefilters', 'write_merged_data'])

    merge_coverage_files_command.write_filtered_data = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.write_filtered_data.called

def test_write_merged_data_called_when_filteronly_is_false():
    merge_coverage_files_command = Command()
    merge_coverage_files_command.filteronly = False

    # We don't want these methods to run
    mock_out_unwanted_methods(merge_coverage_files_command, ['parse_options', 'prepare_packagefilters', 'write_filtered_data'])

    merge_coverage_files_command.write_merged_data = Mock()

    merge_coverage_files_command.handle()

    assert merge_coverage_files_command.write_merged_data.called

Prompt: Add tests to run command to merge content


import sublime, sublime_plugin

class SumCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    new_view = self.view.window().new_file()
    new_view.set_name('Sum')
    new_view.insert(edit, 0, '42')
    new_view.set_read_only(True)
    new_view.set_scratch(True)

Set new file to read-only

Response:
<INSERT> new_view.set_read_only(True)
    <INSERT_END> <|endoftext|> import sublime, sublime_plugin

class SumCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    new_view = self.view.window().new_file()
    new_view.set_name('Sum')
    new_view.insert(edit, 0, '42')
    new_view.set_read_only(True)
    new_view.set_scratch(True)

Prompt:
Set new file to read-only

Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.

import sublime, sublime_plugin

class SumCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    new_view = self.view.window().new_file()
    new_view.set_name('Sum')
    new_view.insert(edit, 0, '42')
    new_view.set_scratch(True)


# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-24 19:33
from __future__ import unicode_literals

import logging

from django.db import migrations

from osf.models import MetaSchema
from website.project.metadata.schemas import OSF_META_SCHEMAS

logger = logging.getLogger(__file__)

def add_schemas(*args):
    """Import meta-data schemas from JSON to database if not already loaded
    """
    schema_count = 0
    for schema in OSF_META_SCHEMAS:
        schema_obj, created = MetaSchema.objects.get_or_create(
            name=schema['name'],
            schema_version=schema.get('version', 1)
        )
        schema_obj.schema = schema
        schema_obj.save()
        schema_count += 1

        if created:
            logger.info('Added schema {} to the database'.format(schema['name']))

    logger.info('Ensured {} schemas are in the database'.format(schema_count))

def remove_schemas(*args):
    removed_schemas = 0
    for schema in OSF_META_SCHEMAS:
        schema_obj = MetaSchema.objects.get(
            schema=schema,
            name=schema['name'],
            schema_version=schema.get('version', 1)
        )
        schema_obj.delete()
        removed_schemas += 1

    logger.info('Removed {} schemas from the database'.format(removed_schemas))

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0035_ensure_licenses'),
    ]

    operations = [
        migrations.RunPython(add_schemas, remove_schemas),
    ]

Add migration for ensure schemas

Add migration for ensure schemas

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-24 19:33
from __future__ import unicode_literals

import logging

from django.db import migrations

from osf.models import MetaSchema
from website.project.metadata.schemas import OSF_META_SCHEMAS

logger = logging.getLogger(__file__)

def add_schemas(*args):
    """Import meta-data schemas from JSON to database if not already loaded
    """
    schema_count = 0
    for schema in OSF_META_SCHEMAS:
        schema_obj, created = MetaSchema.objects.get_or_create(
            name=schema['name'],
            schema_version=schema.get('version', 1)
        )
        schema_obj.schema = schema
        schema_obj.save()
        schema_count += 1

        if created:
            logger.info('Added schema {} to the database'.format(schema['name']))

    logger.info('Ensured {} schemas are in the database'.format(schema_count))

def remove_schemas(*args):
    removed_schemas = 0
    for schema in OSF_META_SCHEMAS:
        schema_obj = MetaSchema.objects.get(
            schema=schema,
            name=schema['name'],
            schema_version=schema.get('version', 1)
        )
        schema_obj.delete()
        removed_schemas += 1

    logger.info('Removed {} schemas from the database'.format(removed_schemas))

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0035_ensure_licenses'),
    ]

    operations = [
        migrations.RunPython(add_schemas, remove_schemas),
    ]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-24 19:33
from __future__ import unicode_literals

import logging

from django.db import migrations

from osf.models import MetaSchema
from website.project.metadata.schemas import OSF_META_SCHEMAS

logger = logging.getLogger(__file__)

def add_schemas(*args):
    """Import meta-data schemas from JSON to database if not already loaded
    """
    schema_count = 0
    for schema in OSF_META_SCHEMAS:
        schema_obj, created = MetaSchema.objects.get_or_create(
            name=schema['name'],
            schema_version=schema.get('version', 1)
        )
        schema_obj.schema = schema
        schema_obj.save()
        schema_count += 1

        if created:
            logger.info('Added schema {} to the database'.format(schema['name']))

    logger.info('Ensured {} schemas are in the database'.format(schema_count))

def remove_schemas(*args):
    removed_schemas = 0
    for schema in OSF_META_SCHEMAS:
        schema_obj = MetaSchema.objects.get(
            schema=schema,
            name=schema['name'],
            schema_version=schema.get('version', 1)
        )
        schema_obj.delete()
        removed_schemas += 1

    logger.info('Removed {} schemas from the database'.format(removed_schemas))

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0035_ensure_licenses'),
    ]

    operations = [
        migrations.RunPython(add_schemas, remove_schemas),
    ]

Prompt: Add migration for ensure schemas


# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

AUTOMERGER_NAME = 'Chromium+Blink automerger'
AUTOMERGER_EMAIL = 'chrome-blink-automerger@chromium.org'

BLINK_REPO_URL = 'https://chromium.googlesource.com/chromium/blink.git'
CHROMIUM_REPO_URL = 'https://chromium.googlesource.com/chromium/src.git'

# 'ref/in/chromium' -> 'ref/in/blink'
BRANCHES_TO_MERGE = [
    ('refs/heads/master', 'refs/heads/master'),
    ('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
    ('refs/branch-heads/2357', 'refs/branch-heads/chromium/2357'),
]

MERGE_MSG = """Merge Chromium + Blink git repositories

Chromium SHA1: %(chromium_sha)s
Chromium position: %(chromium_branch)s@{#%(chromium_pos)s}
Blink SHA1: %(blink_sha)s
Blink revision: %(blink_branch)s@%(blink_rev)s

BUG=431458

Cr-Commit-Position: %(chromium_branch)s@{#%(chromium_next_pos)s}
"""

Switch to 2311 + 2357 branches

Switch to 2311 + 2357 branches

Response:
<REPLACE_OLD> ('refs/branch-heads/2214', 'refs/branch-heads/chromium/2214'),
 <REPLACE_NEW> ('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
 <REPLACE_END> <REPLACE_OLD> ('refs/branch-heads/2272', 'refs/branch-heads/chromium/2272'),
    ('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
]

MERGE_MSG <REPLACE_NEW> ('refs/branch-heads/2357', 'refs/branch-heads/chromium/2357'),
]

MERGE_MSG <REPLACE_END> <|endoftext|> # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

AUTOMERGER_NAME = 'Chromium+Blink automerger'
AUTOMERGER_EMAIL = 'chrome-blink-automerger@chromium.org'

BLINK_REPO_URL = 'https://chromium.googlesource.com/chromium/blink.git'
CHROMIUM_REPO_URL = 'https://chromium.googlesource.com/chromium/src.git'

# 'ref/in/chromium' -> 'ref/in/blink'
BRANCHES_TO_MERGE = [
    ('refs/heads/master', 'refs/heads/master'),
    ('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
    ('refs/branch-heads/2357', 'refs/branch-heads/chromium/2357'),
]

MERGE_MSG = """Merge Chromium + Blink git repositories

Chromium SHA1: %(chromium_sha)s
Chromium position: %(chromium_branch)s@{#%(chromium_pos)s}
Blink SHA1: %(blink_sha)s
Blink revision: %(blink_branch)s@%(blink_rev)s

BUG=431458

Cr-Commit-Position: %(chromium_branch)s@{#%(chromium_next_pos)s}
"""

Prompt:
Switch to 2311 + 2357 branches

# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

AUTOMERGER_NAME = 'Chromium+Blink automerger'
AUTOMERGER_EMAIL = 'chrome-blink-automerger@chromium.org'

BLINK_REPO_URL = 'https://chromium.googlesource.com/chromium/blink.git'
CHROMIUM_REPO_URL = 'https://chromium.googlesource.com/chromium/src.git'

# 'ref/in/chromium' -> 'ref/in/blink'
BRANCHES_TO_MERGE = [
    ('refs/heads/master', 'refs/heads/master'),
    ('refs/branch-heads/2214', 'refs/branch-heads/chromium/2214'),
    ('refs/branch-heads/2272', 'refs/branch-heads/chromium/2272'),
    ('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
]

MERGE_MSG = """Merge Chromium + Blink git repositories

Chromium SHA1: %(chromium_sha)s
Chromium position: %(chromium_branch)s@{#%(chromium_pos)s}
Blink SHA1: %(blink_sha)s
Blink revision: %(blink_branch)s@%(blink_rev)s

BUG=431458

Cr-Commit-Position: %(chromium_branch)s@{#%(chromium_next_pos)s}
"""


from p1tr.test import *

class HelloTest(PluginTestCase):

    @test
    def hello_test(self):
        for data in self.dummy_data:
            self.assertEqual(self.plugin.hello(data.server, data.channel,
                        data.nick, data.params),
                    'Hello, %s!' % data.nick.split('!')[0])

Add test case for hello plugin

Add test case for hello plugin

Response:
<INSERT> from p1tr.test import *

class HelloTest(PluginTestCase):

 <INSERT_END> <INSERT>   @test
    def hello_test(self):
        for data in self.dummy_data:
            self.assertEqual(self.plugin.hello(data.server, data.channel,
                        data.nick, data.params),
                    'Hello, %s!' % data.nick.split('!')[0])
 <INSERT_END> <|endoftext|> from p1tr.test import *

class HelloTest(PluginTestCase):

    @test
    def hello_test(self):
        for data in self.dummy_data:
            self.assertEqual(self.plugin.hello(data.server, data.channel,
                        data.nick, data.params),
                    'Hello, %s!' % data.nick.split('!')[0])

Prompt: Add test case for hello plugin


from __future__ import absolute_import
from __future__ import unicode_literals

from django.conf.urls import patterns, include, url

from .views import *

urlpatterns = patterns('',
    url(r'^pjson/push$', pjson_provider_push,  name="pjson_provider_push"),
    url(r'^fhir/practioner/push$', fhir_practitioner_push,  name="fhir_practitioner_push"),
    url(r'^fhir/organization/push$', fhir_organization_push,  name="fhir_organization_push"),

)

Response:
<REPLACE_OLD> url(r'^fhir/push$', <REPLACE_NEW> url(r'^fhir/practioner/push$', <REPLACE_END> <REPLACE_OLD> name="fhir_practitioner_push"),

) <REPLACE_NEW> name="fhir_practitioner_push"),
    url(r'^fhir/organization/push$', fhir_organization_push,  name="fhir_organization_push"),

)
 <REPLACE_END> <|endoftext|> from __future__ import absolute_import
from __future__ import unicode_literals

from django.conf.urls import patterns, include, url

from .views import *

urlpatterns = patterns('',
    url(r'^pjson/push$', pjson_provider_push,  name="pjson_provider_push"),
    url(r'^fhir/practioner/push$', fhir_practitioner_push,  name="fhir_practitioner_push"),
    url(r'^fhir/organization/push$', fhir_organization_push,  name="fhir_organization_push"),

)

Prompt:
Change fhir practitioner url and add organization url

from __future__ import absolute_import
from __future__ import unicode_literals

from django.conf.urls import patterns, include, url

from .views import *

urlpatterns = patterns('',
    url(r'^pjson/push$', pjson_provider_push,  name="pjson_provider_push"),
    url(r'^fhir/push$', fhir_practitioner_push,  name="fhir_practitioner_push"),

)


from ..aecdata.utils import ticket_sort_key

def apply_ticket_sort(items):
    return list(sorted(items, key=ticket_sort_key))

def test_a_c_already_sorted():
    assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])

def test_a_c_reversed():
    assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])

def test_a_c_aa_reversed():
    assert(apply_ticket_sort(['AA', 'C', 'B', 'A']) == ['A', 'B', 'C', 'AA'])

def test_a_c_aa_already_sorted():
    assert(apply_ticket_sort(['A', 'B', 'C', 'AA']) == ['A', 'B', 'C', 'AA'])

Fix import in ticket_sort_key tests.

Fix import in ticket_sort_key tests.

Response:
<REPLACE_OLD> ..aecdata <REPLACE_NEW> ..aecdata.utils <REPLACE_END> <|endoftext|> from ..aecdata.utils import ticket_sort_key

def apply_ticket_sort(items):
    return list(sorted(items, key=ticket_sort_key))

def test_a_c_already_sorted():
    assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])

def test_a_c_reversed():
    assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])

def test_a_c_aa_reversed():
    assert(apply_ticket_sort(['AA', 'C', 'B', 'A']) == ['A', 'B', 'C', 'AA'])

def test_a_c_aa_already_sorted():
    assert(apply_ticket_sort(['A', 'B', 'C', 'AA']) == ['A', 'B', 'C', 'AA'])

Prompt:
Fix import in ticket_sort_key tests.

from ..aecdata import ticket_sort_key

def apply_ticket_sort(items):
    return list(sorted(items, key=ticket_sort_key))

def test_a_c_already_sorted():
    assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])

def test_a_c_reversed():
    assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])

def test_a_c_aa_reversed():
    assert(apply_ticket_sort(['AA', 'C', 'B', 'A']) == ['A', 'B', 'C', 'AA'])

def test_a_c_aa_already_sorted():
    assert(apply_ticket_sort(['A', 'B', 'C', 'AA']) == ['A', 'B', 'C', 'AA'])


from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb

def create_demo_user(app, created_models, verbosity, **kwargs):
    if settings.DEBUG and User in created_models:
        if verbosity >= 2:
            print "Creating demo User object"
        User.objects.create_superuser("demo", "example@example.com", "demo")

post_syncdb.connect(create_demo_user, sender=auth_app)

Response:
<DELETE> db, <DELETE_END> <|endoftext|>
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb

def create_demo_user(app, created_models, verbosity, **kwargs):
    if settings.DEBUG and User in created_models:
        if verbosity >= 2:
            print "Creating demo User object"
        User.objects.create_superuser("demo", "example@example.com", "demo")

post_syncdb.connect(create_demo_user, sender=auth_app)

Prompt:
Fix post_syncdb signal for demo user to work with Django 1.1

from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb

def create_demo_user(app, created_models, verbosity, db, **kwargs):
    if settings.DEBUG and User in created_models:
        if verbosity >= 2:
            print "Creating demo User object"
        User.objects.create_superuser("demo", "example@example.com", "demo")

post_syncdb.connect(create_demo_user, sender=auth_app)


from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save

app = Flask(__name__)

@app.route('/')
def main():
    return redirect('/index')

@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        pitcher = request.form['pitcher']
        image_file = pitcher.lower()
        image_file = image_file.split()
        image_file = '_'.join(image_file) + '.png'

        return render_template('results.html', image_file = image_file)

if __name__ == '__main__':
    app.run(port=33508)

Response:
<REPLACE_OLD> Flask(__name__)

# @app.route('/')
# def main():
#  <REPLACE_NEW> Flask(__name__)

@app.route('/')
def main():
 <REPLACE_END> <REPLACE_OLD> redirect('/index')

@app.route('/', <REPLACE_NEW> redirect('/index')

@app.route('/index', <REPLACE_END> <|endoftext|> from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save

app = Flask(__name__)

@app.route('/')
def main():
    return redirect('/index')

@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        pitcher = request.form['pitcher']
        image_file = pitcher.lower()
        image_file = image_file.split()
        image_file = '_'.join(image_file) + '.png'

        return render_template('results.html', image_file = image_file)

if __name__ == '__main__':
    app.run(port=33508)

Prompt:
Revert "Remove redirect to avoid Chrome privacy error"

This reverts commit e5322958f14b2428b74de726476fd98adae8c454.

from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save

app = Flask(__name__)

# @app.route('/')
# def main():
#     return redirect('/index')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        pitcher = request.form['pitcher']
        image_file = pitcher.lower()
        image_file = image_file.split()
        image_file = '_'.join(image_file) + '.png'

        return render_template('results.html', image_file = image_file)

if __name__ == '__main__':
    app.run(port=33508)


from context import models

from models import model

import unittest

class test_model(unittest.TestCase):
    def setUp(self):
        self.room = model.Room(20, 'new_room')
        self.room1 = model.Room(6, 'new_room1')
        self.livingspace = model.LivingSpace('orange')
        self.office = model.Office('manjaro')

    def test_Room_instance(self):
        self.assertIsInstance(self.room, model.Room)
        self.assertIsInstance(self.room1, model.Room)

    def test_Room_max_occupation(self):
        self.assertEqual(20, self.room.max_occupants)

    def test_Room_name(self):
        self.assertEqual('new_room1', self.room1.name)
        self.room1.name = "changedname"
        self.assertEqual('changedname', self.room1.name)

    def test_office_ocupants(self):
        self.assertEqual(6, self.office.max_occupants)

    def test_livingspace_ocupants(self):
        self.assertEqual(4, self.livingspace.max_occupants)

    def test_sublclass_Room(self):
        self.assertTrue(issubclass(model.Office, model.Room))
        self.assertTrue(issubclass(model.LivingSpace, model.Room))

    def test_room_current_population(self):
        self.assertEqual(self.room.current_population, 0)

Response:
<REPLACE_OLD> test_logic_core(unittest.TestCase):
 <REPLACE_NEW> test_model(unittest.TestCase):
 <REPLACE_END> <INSERT> self.room1.name)
        self.room1.name = "changedname"
        self.assertEqual('changedname', <INSERT_END> <REPLACE_OLD> model.Room))
 <REPLACE_NEW> model.Room))

    def test_room_current_population(self):
        self.assertEqual(self.room.current_population, 0)
 <REPLACE_END> <|endoftext|> from context import models

from models import model

import unittest

class test_model(unittest.TestCase):
    def setUp(self):
        self.room = model.Room(20, 'new_room')
        self.room1 = model.Room(6, 'new_room1')
        self.livingspace = model.LivingSpace('orange')
        self.office = model.Office('manjaro')

    def test_Room_instance(self):
        self.assertIsInstance(self.room, model.Room)
        self.assertIsInstance(self.room1, model.Room)

    def test_Room_max_occupation(self):
        self.assertEqual(20, self.room.max_occupants)

    def test_Room_name(self):
        self.assertEqual('new_room1', self.room1.name)
        self.room1.name = "changedname"
        self.assertEqual('changedname', self.room1.name)

    def test_office_ocupants(self):
        self.assertEqual(6, self.office.max_occupants)

    def test_livingspace_ocupants(self):
        self.assertEqual(4, self.livingspace.max_occupants)

    def test_sublclass_Room(self):
        self.assertTrue(issubclass(model.Office, model.Room))
        self.assertTrue(issubclass(model.LivingSpace, model.Room))

    def test_room_current_population(self):
        self.assertEqual(self.room.current_population, 0)

Prompt:
Refactor model test to test added properties

from context import models

from models import model

import unittest

class test_logic_core(unittest.TestCase):
    def setUp(self):
        self.room = model.Room(20, 'new_room')
        self.room1 = model.Room(6, 'new_room1')
        self.livingspace = model.LivingSpace('orange')
        self.office = model.Office('manjaro')

    def test_Room_instance(self):
        self.assertIsInstance(self.room, model.Room)
        self.assertIsInstance(self.room1, model.Room)

    def test_Room_max_occupation(self):
        self.assertEqual(20, self.room.max_occupants)

    def test_Room_name(self):
        self.assertEqual('new_room1', self.room1.name)

    def test_office_ocupants(self):
        self.assertEqual(6, self.office.max_occupants)

    def test_livingspace_ocupants(self):
        self.assertEqual(4, self.livingspace.max_occupants)

    def test_sublclass_Room(self):
        self.assertTrue(issubclass(model.Office, model.Room))
        self.assertTrue(issubclass(model.LivingSpace, model.Room))


import unittest
from charset_normalizer.normalizer import CharsetNormalizerMatches as CnM
from glob import glob
from os.path import basename

class TestLanguageDetection(unittest.TestCase):
    SHOULD_BE = {
        'sample.1.ar.srt': 'Arabic',
        'sample.1.fr.srt': 'French',
        'sample.1.gr.srt': 'Greek',
        'sample.1.he.srt': 'Hebrew',
        'sample.1.hi.srt': 'English',
        'sample.1.ru.srt': 'Russian',
        'sample.1.tu.srt': 'Turkish',
        'sample.2.ar.srt': 'Arabic',
        'sample.3.ar.srt': 'Arabic',
        'sample.4.ar.srt': 'Arabic',
        'sample.5.ar.srt': 'Arabic',
        'sample-chinese.txt': 'Classical Chinese',
        'sample-greek.txt': 'Greek',
        'sample-greek-2.txt': 'Greek',
        'sample-hebrew.txt': 'English',
        'sample-hebrew-2.txt': 'Hebrew',
        'sample-hebrew-3.txt': 'Hebrew',
        'sample-russian.txt': 'Russian',
        'sample-russian-2.txt': 'Russian',
        'sample-turkish.txt': 'Turkish',
        'sample-korean.txt': 'Korean',
        'sample-spanish.txt': 'Spanish',
        'sample-bulgarian.txt': 'Bulgarian',
        'sample-english.bom.txt': 'English'
    }

    def test_language_detection(self):

        for path_name in glob('./data/*.srt') + glob('./data/*.txt'):
            with self.subTest(path_name):
                r_ = CnM.from_path(path_name).best().first()

                self.assertEqual(
                    TestLanguageDetection.SHOULD_BE[basename(path_name)],
                    r_.language
                )

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

Add test to verify if language was detected properly

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest
from charset_normalizer.normalizer import CharsetNormalizerMatches as CnM
from glob import glob
from os.path import basename

class TestLanguageDetection(unittest.TestCase):
    SHOULD_BE = {
        'sample.1.ar.srt': 'Arabic',
        'sample.1.fr.srt': 'French',
        'sample.1.gr.srt': 'Greek',
        'sample.1.he.srt': 'Hebrew',
        'sample.1.hi.srt': 'English',
        'sample.1.ru.srt': 'Russian',
        'sample.1.tu.srt': 'Turkish',
        'sample.2.ar.srt': 'Arabic',
        'sample.3.ar.srt': 'Arabic',
        'sample.4.ar.srt': 'Arabic',
        'sample.5.ar.srt': 'Arabic',
        'sample-chinese.txt': 'Classical Chinese',
        'sample-greek.txt': 'Greek',
        'sample-greek-2.txt': 'Greek',
        'sample-hebrew.txt': 'English',
        'sample-hebrew-2.txt': 'Hebrew',
        'sample-hebrew-3.txt': 'Hebrew',
        'sample-russian.txt': 'Russian',
        'sample-russian-2.txt': 'Russian',
        'sample-turkish.txt': 'Turkish',
        'sample-korean.txt': 'Korean',
        'sample-spanish.txt': 'Spanish',
        'sample-bulgarian.txt': 'Bulgarian',
        'sample-english.bom.txt': 'English'
    }

    def test_language_detection(self):

        for path_name in glob('./data/*.srt') + glob('./data/*.txt'):
            with self.subTest(path_name):
                r_ = CnM.from_path(path_name).best().first()

                self.assertEqual(
                    TestLanguageDetection.SHOULD_BE[basename(path_name)],
                    r_.language
                )

if __name__ == '__main__':
    unittest.main()
 <REPLACE_END> <|endoftext|> import unittest
from charset_normalizer.normalizer import CharsetNormalizerMatches as CnM
from glob import glob
from os.path import basename

class TestLanguageDetection(unittest.TestCase):
    SHOULD_BE = {
        'sample.1.ar.srt': 'Arabic',
        'sample.1.fr.srt': 'French',
        'sample.1.gr.srt': 'Greek',
        'sample.1.he.srt': 'Hebrew',
        'sample.1.hi.srt': 'English',
        'sample.1.ru.srt': 'Russian',
        'sample.1.tu.srt': 'Turkish',
        'sample.2.ar.srt': 'Arabic',
        'sample.3.ar.srt': 'Arabic',
        'sample.4.ar.srt': 'Arabic',
        'sample.5.ar.srt': 'Arabic',
        'sample-chinese.txt': 'Classical Chinese',
        'sample-greek.txt': 'Greek',
        'sample-greek-2.txt': 'Greek',
        'sample-hebrew.txt': 'English',
        'sample-hebrew-2.txt': 'Hebrew',
        'sample-hebrew-3.txt': 'Hebrew',
        'sample-russian.txt': 'Russian',
        'sample-russian-2.txt': 'Russian',
        'sample-turkish.txt': 'Turkish',
        'sample-korean.txt': 'Korean',
        'sample-spanish.txt': 'Spanish',
        'sample-bulgarian.txt': 'Bulgarian',
        'sample-english.bom.txt': 'English'
    }

    def test_language_detection(self):

        for path_name in glob('./data/*.srt') + glob('./data/*.txt'):
            with self.subTest(path_name):
                r_ = CnM.from_path(path_name).best().first()

                self.assertEqual(
                    TestLanguageDetection.SHOULD_BE[basename(path_name)],
                    r_.language
                )

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

Prompt: Add test to verify if language was detected properly


import sys, unittest, os
import bmc_test
import power_test
import xmlrunner

tests = []
tests.extend(bmc_test.tests)
#tests.extend(power_test.tests)

if __name__ == '__main__':
    for test in tests:
        test.system = sys.argv[1]
        suite = unittest.TestLoader().loadTestsFromTestCase(test)
        result = xmlrunner.XMLTestRunner(verbose = 1, output='test-reports').run(suite)
        if result.failures or result.errors:
            os.sys.exit(1)

Response:
<REPLACE_OLD> unittest
import <REPLACE_NEW> unittest, os
import <REPLACE_END> <INSERT> result = <INSERT_END> <INSERT>        if result.failures or result.errors:
            os.sys.exit(1)
 <INSERT_END> <|endoftext|> import sys, unittest, os
import bmc_test
import power_test
import xmlrunner

tests = []
tests.extend(bmc_test.tests)
#tests.extend(power_test.tests)

if __name__ == '__main__':
    for test in tests:
        test.system = sys.argv[1]
        suite = unittest.TestLoader().loadTestsFromTestCase(test)
        result = xmlrunner.XMLTestRunner(verbose = 1, output='test-reports').run(suite)
        if result.failures or result.errors:
            os.sys.exit(1)

Prompt:
Return a bad error code when a test fails

import sys, unittest
import bmc_test
import power_test
import xmlrunner

tests = []
tests.extend(bmc_test.tests)
#tests.extend(power_test.tests)

if __name__ == '__main__':
    for test in tests:
        test.system = sys.argv[1]
        suite = unittest.TestLoader().loadTestsFromTestCase(test)
        xmlrunner.XMLTestRunner(verbose = 1, output='test-reports').run(suite)


# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###

from pyramid.events import NewRequest

def add_cors_headers(request, response):
    settings = request.registry.settings
    acac = settings['cors.access_control_allow_credentials']
    acao = settings['cors.access_control_allow_origin'].split()
    acah = settings['cors.access_control_allow_headers']
    acam = settings['cors.access_control_allow_methods']
    if acac:
        response.headerlist.append(
                ('Access-Control-Allow-Credentials', acac))
    if acao:
        if request.headers.get('Origin') in acao:
            response.headerlist.append(
                ('Access-Control-Allow-Origin', request.headers.get('Origin')))
        else:
            response.headerlist.append(
                ('Access-Control-Allow-Origin', acao[0]))
    if acah:
        response.headerlist.append(
                ('Access-Control-Allow-Headers', acah))
    if acam:
        response.headerlist.append(
                ('Access-Control-Allow-Methods', acam))

def new_request_subscriber(event):
    request = event.request
    request.add_response_callback(add_cors_headers)

def main(config):
    config.add_subscriber(new_request_subscriber, NewRequest)

Response:
<REPLACE_OLD> request.host <REPLACE_NEW> request.headers.get('Origin') <REPLACE_END> <REPLACE_OLD> request.host))
 <REPLACE_NEW> request.headers.get('Origin')))
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###

from pyramid.events import NewRequest

def add_cors_headers(request, response):
    settings = request.registry.settings
    acac = settings['cors.access_control_allow_credentials']
    acao = settings['cors.access_control_allow_origin'].split()
    acah = settings['cors.access_control_allow_headers']
    acam = settings['cors.access_control_allow_methods']
    if acac:
        response.headerlist.append(
                ('Access-Control-Allow-Credentials', acac))
    if acao:
        if request.headers.get('Origin') in acao:
            response.headerlist.append(
                ('Access-Control-Allow-Origin', request.headers.get('Origin')))
        else:
            response.headerlist.append(
                ('Access-Control-Allow-Origin', acao[0]))
    if acah:
        response.headerlist.append(
                ('Access-Control-Allow-Headers', acah))
    if acam:
        response.headerlist.append(
                ('Access-Control-Allow-Methods', acam))

def new_request_subscriber(event):
    request = event.request
    request.add_response_callback(add_cors_headers)

def main(config):
    config.add_subscriber(new_request_subscriber, NewRequest)

Prompt:
Fix Access-Control-Allow-Origin to return the request origin

request.host is the host part of the request url.  For example, if
webview is trying to access http://localhost:8080/users/profile,
request.  It's the Origin field in the headers that we should be
matching.

# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###

from pyramid.events import NewRequest

def add_cors_headers(request, response):
    settings = request.registry.settings
    acac = settings['cors.access_control_allow_credentials']
    acao = settings['cors.access_control_allow_origin'].split()
    acah = settings['cors.access_control_allow_headers']
    acam = settings['cors.access_control_allow_methods']
    if acac:
        response.headerlist.append(
                ('Access-Control-Allow-Credentials', acac))
    if acao:
        if request.host in acao:
            response.headerlist.append(
                ('Access-Control-Allow-Origin', request.host))
        else:
            response.headerlist.append(
                ('Access-Control-Allow-Origin', acao[0]))
    if acah:
        response.headerlist.append(
                ('Access-Control-Allow-Headers', acah))
    if acam:
        response.headerlist.append(
                ('Access-Control-Allow-Methods', acam))

def new_request_subscriber(event):
    request = event.request
    request.add_response_callback(add_cors_headers)

def main(config):
    config.add_subscriber(new_request_subscriber, NewRequest)


"""
Task runner using IPython parallel interface.

See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.

.. _The IPython task interface:
   http://ipython.org/ipython-doc/dev/parallel/parallel_task.html

.. _DAG Dependencies:
   http://ipython.org/ipython-doc/dev/parallel/dag_dependencies.html

.. _IPython Documentation:
   http://ipython.org/ipython-doc/dev/

"""

import IPython.parallel

from .simple import SimpleRunner
from .mixinparallel import MixInParallelRunner

class IPythonParallelRunner(MixInParallelRunner, SimpleRunner):

    def submit_tasks(self):
        self.client = IPython.parallel.Client()
        self.view = view = self.client.load_balanced_view()
        self.results = results = {}
        for node in self.sorted_nodes():
            deps = [results[n] for n in self.graph.predecessors(node)]
            with view.temp_flags(after=deps):
                results[node] = view.apply_async(self.run_func,
                                                 self.nodetaskmap[node])

    def wait_tasks(self):
        for r in self.results.values():
            r.get()

Response:
<REPLACE_OLD> self.view.wait(self.results.values())
 <REPLACE_NEW> for r in self.results.values():
            r.get()
 <REPLACE_END> <|endoftext|> """
Task runner using IPython parallel interface.

See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.

.. _The IPython task interface:
   http://ipython.org/ipython-doc/dev/parallel/parallel_task.html

.. _DAG Dependencies:
   http://ipython.org/ipython-doc/dev/parallel/dag_dependencies.html

.. _IPython Documentation:
   http://ipython.org/ipython-doc/dev/

"""

import IPython.parallel

from .simple import SimpleRunner
from .mixinparallel import MixInParallelRunner

class IPythonParallelRunner(MixInParallelRunner, SimpleRunner):

    def submit_tasks(self):
        self.client = IPython.parallel.Client()
        self.view = view = self.client.load_balanced_view()
        self.results = results = {}
        for node in self.sorted_nodes():
            deps = [results[n] for n in self.graph.predecessors(node)]
            with view.temp_flags(after=deps):
                results[node] = view.apply_async(self.run_func,
                                                 self.nodetaskmap[node])

    def wait_tasks(self):
        for r in self.results.values():
            r.get()

Prompt:
Raise error if any in IPythonParallelRunner.wait_tasks

"""
Task runner using IPython parallel interface.

See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.

.. _The IPython task interface:
   http://ipython.org/ipython-doc/dev/parallel/parallel_task.html

.. _DAG Dependencies:
   http://ipython.org/ipython-doc/dev/parallel/dag_dependencies.html

.. _IPython Documentation:
   http://ipython.org/ipython-doc/dev/

"""

import IPython.parallel

from .simple import SimpleRunner
from .mixinparallel import MixInParallelRunner

class IPythonParallelRunner(MixInParallelRunner, SimpleRunner):

    def submit_tasks(self):
        self.client = IPython.parallel.Client()
        self.view = view = self.client.load_balanced_view()
        self.results = results = {}
        for node in self.sorted_nodes():
            deps = [results[n] for n in self.graph.predecessors(node)]
            with view.temp_flags(after=deps):
                results[node] = view.apply_async(self.run_func,
                                                 self.nodetaskmap[node])

    def wait_tasks(self):
        self.view.wait(self.results.values())


from vim_turing_machine.machines.merge_business_hours.merge_business_hours import merge_business_hours_transitions
from vim_turing_machine.vim_machine import VimTuringMachine

if __name__ == '__main__':
    merge_business_hours = VimTuringMachine(merge_business_hours_transitions(), debug=True)
    merge_business_hours.run(initial_tape=sys.argv[1], max_steps=50)

Add a vim version of merge business hours

Response:
<INSERT> from vim_turing_machine.machines.merge_business_hours.merge_business_hours import merge_business_hours_transitions
from vim_turing_machine.vim_machine import VimTuringMachine

if __name__ == '__main__':
 <INSERT_END> <INSERT>   merge_business_hours = VimTuringMachine(merge_business_hours_transitions(), debug=True)
    merge_business_hours.run(initial_tape=sys.argv[1], max_steps=50)
 <INSERT_END> <|endoftext|> from vim_turing_machine.machines.merge_business_hours.merge_business_hours import merge_business_hours_transitions
from vim_turing_machine.vim_machine import VimTuringMachine

if __name__ == '__main__':
    merge_business_hours = VimTuringMachine(merge_business_hours_transitions(), debug=True)
    merge_business_hours.run(initial_tape=sys.argv[1], max_steps=50)

Prompt: Add a vim version of merge business hours


import requests
import csv
from datetime import datetime
import ics_parser

URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'

def fetch_and_parse(url):
    return ics_parser.parse(requests.get(url).text)

# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities

# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])

# Write csv
with open('timeedit.csv', 'w') as csvfile:
    fieldnames = set()
    for e in events: fieldnames = fieldnames | set(e.keys())
    writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
    writer.writeheader()
    for e in events:
        for key, value in e.items():
            if isinstance(value, datetime): e[key] = value.isoformat()
        writer.writerow(e)

Response:
<REPLACE_OLD> csv
import <REPLACE_NEW> csv
from datetime import datetime
import <REPLACE_END> <REPLACE_OLD> duplicate events
events <REPLACE_NEW> duplicates and sort
events <REPLACE_END> <REPLACE_OLD> events}.values()

# <REPLACE_NEW> events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])

# <REPLACE_END> <REPLACE_OLD> events: <REPLACE_NEW> events:
        for key, value in e.items():
            if isinstance(value, datetime): e[key] = value.isoformat()
        <REPLACE_END> <|endoftext|> import requests
import csv
from datetime import datetime
import ics_parser

URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'

def fetch_and_parse(url):
    return ics_parser.parse(requests.get(url).text)

# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities

# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])

# Write csv
with open('timeedit.csv', 'w') as csvfile:
    fieldnames = set()
    for e in events: fieldnames = fieldnames | set(e.keys())
    writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
    writer.writeheader()
    for e in events:
        for key, value in e.items():
            if isinstance(value, datetime): e[key] = value.isoformat()
        writer.writerow(e)

Prompt:
Sort events by start and iso format datetimes

import requests
import csv
import ics_parser

URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'

def fetch_and_parse(url):
    return ics_parser.parse(requests.get(url).text)

# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities

# Remove duplicate events
events = {e['UID']: e for e in events}.values()

# Write csv
with open('timeedit.csv', 'w') as csvfile:
    fieldnames = set()
    for e in events: fieldnames = fieldnames | set(e.keys())
    writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
    writer.writeheader()
    for e in events: writer.writerow(e)


import io
import os
from textwrap import dedent

from pg_bawler import bawlerd

class TestBawlerdConfig:

    def test_build_config_location_list(self):
        assert not bawlerd.conf.build_config_location_list(locations=())

        user_conf = os.path.join(
            os.path.expanduser('~'),
            bawlerd.conf.DEFAULT_CONFIG_FILENAME)

        system_conf = os.path.join(
            '/etc/pg_bawler',
            bawlerd.conf.DEFAULT_CONFIG_FILENAME)

        assert user_conf in bawlerd.conf.build_config_location_list()
        assert system_conf in bawlerd.conf.build_config_location_list()

    def test__load_file(self):
        config = bawlerd.conf._load_file(io.StringIO(dedent("""\
            logging:
              formatters:
                standard:
                  format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
              handlers:
                default:
                  level: "INFO"
                  formatter: standard
                  class: logging.StreamHandler
              loggers:
                "":
                  handlers: ["default"]
                  level: INFO
                  propagate: True
        """)))
        assert 'logging' in config

    def test_read_config_files(self):
        config_base = os.path.join(
            os.path.abspath(os.path.dirname(__file__)), 'configs')
        locations = [
            os.path.join(config_base, 'etc'),
            os.path.join(config_base, 'home'),
        ]
        config = bawlerd.conf.read_config_files(
            bawlerd.conf.build_config_location_list(locations=locations))

        assert config['common']['listen_timeout'] == 40
        assert 'logging' in config

Add simple test for config builder

Response:
<INSERT> config

    def test_read_config_files(self):
        config_base = os.path.join(
            os.path.abspath(os.path.dirname(__file__)), 'configs')
        locations = [
            os.path.join(config_base, 'etc'),
            os.path.join(config_base, 'home'),
        ]
        config = bawlerd.conf.read_config_files(
            bawlerd.conf.build_config_location_list(locations=locations))

        assert config['common']['listen_timeout'] == 40
        assert 'logging' in <INSERT_END> <|endoftext|> import io
import os
from textwrap import dedent

from pg_bawler import bawlerd

class TestBawlerdConfig:

    def test_build_config_location_list(self):
        assert not bawlerd.conf.build_config_location_list(locations=())

        user_conf = os.path.join(
            os.path.expanduser('~'),
            bawlerd.conf.DEFAULT_CONFIG_FILENAME)

        system_conf = os.path.join(
            '/etc/pg_bawler',
            bawlerd.conf.DEFAULT_CONFIG_FILENAME)

        assert user_conf in bawlerd.conf.build_config_location_list()
        assert system_conf in bawlerd.conf.build_config_location_list()

    def test__load_file(self):
        config = bawlerd.conf._load_file(io.StringIO(dedent("""\
            logging:
              formatters:
                standard:
                  format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
              handlers:
                default:
                  level: "INFO"
                  formatter: standard
                  class: logging.StreamHandler
              loggers:
                "":
                  handlers: ["default"]
                  level: INFO
                  propagate: True
        """)))
        assert 'logging' in config

    def test_read_config_files(self):
        config_base = os.path.join(
            os.path.abspath(os.path.dirname(__file__)), 'configs')
        locations = [
            os.path.join(config_base, 'etc'),
            os.path.join(config_base, 'home'),
        ]
        config = bawlerd.conf.read_config_files(
            bawlerd.conf.build_config_location_list(locations=locations))

        assert config['common']['listen_timeout'] == 40
        assert 'logging' in config

Prompt:
Add simple test for config builder

Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>

import io
import os
from textwrap import dedent

from pg_bawler import bawlerd

class TestBawlerdConfig:

    def test_build_config_location_list(self):
        assert not bawlerd.conf.build_config_location_list(locations=())

        user_conf = os.path.join(
            os.path.expanduser('~'),
            bawlerd.conf.DEFAULT_CONFIG_FILENAME)

        system_conf = os.path.join(
            '/etc/pg_bawler',
            bawlerd.conf.DEFAULT_CONFIG_FILENAME)

        assert user_conf in bawlerd.conf.build_config_location_list()
        assert system_conf in bawlerd.conf.build_config_location_list()

    def test__load_file(self):
        config = bawlerd.conf._load_file(io.StringIO(dedent("""\
            logging:
              formatters:
                standard:
                  format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
              handlers:
                default:
                  level: "INFO"
                  formatter: standard
                  class: logging.StreamHandler
              loggers:
                "":
                  handlers: ["default"]
                  level: INFO
                  propagate: True
        """)))
        assert 'logging' in config


import asyncio

import aiohttp

from waterbutler import settings

IDENTITY_METHODS = {}

def get_identity_func(name):
    try:
        return IDENTITY_METHODS[name]
    except KeyError:
        raise NotImplementedError('No identity getter for {0}'.format(name))

def register_identity(name):
    def _register_identity(func):
        IDENTITY_METHODS[name] = func
        return func
    return _register_identity

def get_identity(name, **kwargs):
    return get_identity_func(name)(**kwargs)

@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
    response = yield from aiohttp.request(
        'get',
        settings.IDENTITY_API_URL,
        params=params,
        headers={'Content-Type': 'application/json'},
    )

    # TOOD Handle Errors nicely
    if response.status != 200:
        data = yield from response.read()
        raise web.HTTPError(response.status)

    data = yield from response.json()
    return data

Make use of a register decorator

Make use of a register decorator

Response:
<REPLACE_OLD> asyncio

from <REPLACE_NEW> asyncio

import aiohttp

from <REPLACE_END> <REPLACE_OLD> settings

@asyncio.coroutine
def fetch_rest_identity(params):
 <REPLACE_NEW> settings

IDENTITY_METHODS = {}

def get_identity_func(name):
    try:
        return IDENTITY_METHODS[name]
    except KeyError:
        raise NotImplementedError('No identity getter for {0}'.format(name))

def register_identity(name):
    def _register_identity(func):
        IDENTITY_METHODS[name] = func
        return func
    return _register_identity

def get_identity(name, **kwargs):
    return get_identity_func(name)(**kwargs)

@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
 <REPLACE_END> <REPLACE_OLD> data

IDENTITY_METHODS = {
    'rest': fetch_rest_identity
}

get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
 <REPLACE_NEW> data
 <REPLACE_END> <|endoftext|> import asyncio

import aiohttp

from waterbutler import settings

IDENTITY_METHODS = {}

def get_identity_func(name):
    try:
        return IDENTITY_METHODS[name]
    except KeyError:
        raise NotImplementedError('No identity getter for {0}'.format(name))

def register_identity(name):
    def _register_identity(func):
        IDENTITY_METHODS[name] = func
        return func
    return _register_identity

def get_identity(name, **kwargs):
    return get_identity_func(name)(**kwargs)

@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
    response = yield from aiohttp.request(
        'get',
        settings.IDENTITY_API_URL,
        params=params,
        headers={'Content-Type': 'application/json'},
    )

    # TOOD Handle Errors nicely
    if response.status != 200:
        data = yield from response.read()
        raise web.HTTPError(response.status)

    data = yield from response.json()
    return data

Prompt:
Make use of a register decorator

import asyncio

from waterbutler import settings

@asyncio.coroutine
def fetch_rest_identity(params):
    response = yield from aiohttp.request(
        'get',
        settings.IDENTITY_API_URL,
        params=params,
        headers={'Content-Type': 'application/json'},
    )

    # TOOD Handle Errors nicely
    if response.status != 200:
        data = yield from response.read()
        raise web.HTTPError(response.status)

    data = yield from response.json()
    return data

IDENTITY_METHODS = {
    'rest': fetch_rest_identity
}

get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]


import string

UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase

def rotate(s, n):
    rules = shift_rules(n)
    return "".join(rules.get(ch, ch) for ch in s)

def shift_rules(n):
    shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
    return {k:v for k,v in zip(UPPER+LOWER, shifted)}

Response:
<REPLACE_OLD> "".join(map(lambda k: rules.get(k, k), s))

def <REPLACE_NEW> "".join(rules.get(ch, ch) for ch in s)

def <REPLACE_END> <|endoftext|> import string

UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase

def rotate(s, n):
    rules = shift_rules(n)
    return "".join(rules.get(ch, ch) for ch in s)

def shift_rules(n):
    shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
    return {k:v for k,v in zip(UPPER+LOWER, shifted)}

Prompt:
Use a comprehension instead of a lambda function

import string

UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase

def rotate(s, n):
    rules = shift_rules(n)
    return "".join(map(lambda k: rules.get(k, k), s))

def shift_rules(n):
    shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
    return {k:v for k,v in zip(UPPER+LOWER, shifted)}


from django.conf import settings
from django.http import HttpResponseRedirect

DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'

class DetachMiddleware(object):
    def process_request(self, request):
        if not request.path == '/login/' \
                and not request.path.startswith('/api')  \
                and not request.user.is_anonymous:

            if not request.user.is_native:
                if not request.path == DETACH_PATH:
                    return HttpResponseRedirect(DETACH_PATH)
            elif not request.user.is_mail_verified \
                    and not request.path.startswith(ACTIVATE_PATH):
                return HttpResponseRedirect(ACTIVATE_PATH)

Response:
<REPLACE_OLD> request.path.startswith('/api'):

 <REPLACE_NEW> request.path.startswith('/api')  \
                and not request.user.is_anonymous:

 <REPLACE_END> <REPLACE_OLD> request.user.is_anonymous \
 <REPLACE_NEW> request.user.is_native:
                if not request.path == DETACH_PATH:
 <REPLACE_END> <REPLACE_OLD> and not request.user.is_native \
 <REPLACE_NEW> return HttpResponseRedirect(DETACH_PATH)
 <REPLACE_END> <REPLACE_OLD>         and not request.path == DETACH_PATH:
                return HttpResponseRedirect(DETACH_PATH)

            if not request.user.is_anonymous \
                    and <REPLACE_NEW> elif <REPLACE_END> <|endoftext|> from django.conf import settings
from django.http import HttpResponseRedirect

DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'

class DetachMiddleware(object):
    def process_request(self, request):
        if not request.path == '/login/' \
                and not request.path.startswith('/api')  \
                and not request.user.is_anonymous:

            if not request.user.is_native:
                if not request.path == DETACH_PATH:
                    return HttpResponseRedirect(DETACH_PATH)
            elif not request.user.is_mail_verified \
                    and not request.path.startswith(ACTIVATE_PATH):
                return HttpResponseRedirect(ACTIVATE_PATH)

Prompt:
Remove infinite loop if user is neither native nor verified

from django.conf import settings
from django.http import HttpResponseRedirect

DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'

class DetachMiddleware(object):
    def process_request(self, request):
        if not request.path == '/login/' \
                and not request.path.startswith('/api'):

            if not request.user.is_anonymous \
                    and not request.user.is_native \
                    and not request.path == DETACH_PATH:
                return HttpResponseRedirect(DETACH_PATH)

            if not request.user.is_anonymous \
                    and not request.user.is_mail_verified \
                    and not request.path.startswith(ACTIVATE_PATH):
                return HttpResponseRedirect(ACTIVATE_PATH)


import array
import math
import sys

n = int(sys.argv[1])
nums = array.array('i', [False] * 2 + [True] * (n - 2))

upper_lim = int(math.sqrt(n))
i = 2
while i <= upper_lim:
    if nums[i]:
        m = i**2
        while m < n:
            nums[m] = False
            m += i
    i += 1

print(len([x for x in nums if nums]))

Make Python code equivalent to Ruby

Response:
<REPLACE_OLD> sys
Max=int(sys.argv[1])					# get Max from command line args
P <REPLACE_NEW> array
import math
import sys

n <REPLACE_END> <REPLACE_OLD> {x: True <REPLACE_NEW> int(sys.argv[1])
nums = array.array('i', [False] * 2 + [True] * (n - 2))

upper_lim = int(math.sqrt(n))
i = 2
while i <= upper_lim:
    if nums[i]:
        m = i**2
        while m < n:
            nums[m] = False
            m += i
    i += 1

print(len([x <REPLACE_END> <REPLACE_OLD> range(2,Max)}		# first assume numbers are prime
for i in range(2, int(Max** (0.5))):	# until square root of Max
	if P[i]:							#
		for j in range(i*i, Max, i):	# mark all multiples of a prime
			P[j]=False					# as not beeing a prime

numprimes = 0;							# Count all primes
for i,isprime in P.items():
	if isprime:
		numprimes=numprimes+1

print(numprimes) 						# print number of primes
 <REPLACE_NEW> nums if nums]))
 <REPLACE_END> <|endoftext|> import array
import math
import sys

n = int(sys.argv[1])
nums = array.array('i', [False] * 2 + [True] * (n - 2))

upper_lim = int(math.sqrt(n))
i = 2
while i <= upper_lim:
    if nums[i]:
        m = i**2
        while m < n:
            nums[m] = False
            m += i
    i += 1

print(len([x for x in nums if nums]))

Prompt:
Make Python code equivalent to Ruby

Using a dictionary instead is really unfair.

Small variation: m must not be equal to n. Not sure how the algorithm is meant is exactly...

import sys
Max=int(sys.argv[1])					# get Max from command line args
P = {x: True for x in range(2,Max)}		# first assume numbers are prime
for i in range(2, int(Max** (0.5))):	# until square root of Max
	if P[i]:							#
		for j in range(i*i, Max, i):	# mark all multiples of a prime
			P[j]=False					# as not beeing a prime

numprimes = 0;							# Count all primes
for i,isprime in P.items():
	if isprime:
		numprimes=numprimes+1

print(numprimes) 						# print number of primes


#!/usr/bin/env python

from telnetlib import Telnet
import time
import sys

tn = Telnet('192.168.1.15', 13666, None)
pipe_contents = sys.stdin.read()
pipe_contents = pipe_contents.replace('\n', ' ')

tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 string\n")
tn.write("widget_add s1 w2 string\n")

def lcd_string(x, telnet_obj, delay=2):
    L = []
    for i in range(len(x)):
        if i % (15+16) == 0:
            L.append(x[i:i+15+16])
    for s in L:
        s1 = s[0:15]
        s2 = s[15:]
        telnet_obj.write("widget_set s1 w1 1 1 {" + s1 + "}\n")
        telnet_obj.write("widget_set s1 w2 1 2 {" + s2 + "}\n")
        time.sleep(delay)

lcd_string(pipe_contents, tn)

Response:
<REPLACE_OLD> from <REPLACE_NEW> #!/usr/bin/env python

from <REPLACE_END> <REPLACE_OLD> time
tn <REPLACE_NEW> time
import sys

tn <REPLACE_END> <REPLACE_OLD> None)

#tn.interact()

tn.write("hello\n")
tn.write("screen_add <REPLACE_NEW> None)
pipe_contents = sys.stdin.read()
pipe_contents = pipe_contents.replace('\n', ' ')

tn.write("hello\n")
tn.write("screen_add <REPLACE_END> <REPLACE_OLD> string\n")
tn.write("widget_set s1 w1 1 1 {It is a truth u}\n")
tn.write("widget_set s1 w2 1 2 {niversally ackno}\n")
print "sleeping"
time.sleep(5)

def <REPLACE_NEW> string\n")

def <REPLACE_END> <REPLACE_OLD> delay=5):
 <REPLACE_NEW> delay=2):
 <REPLACE_END> <REPLACE_OLD> time.sleep(delay)

lcd_string('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', <REPLACE_NEW> time.sleep(delay)

lcd_string(pipe_contents, <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from telnetlib import Telnet
import time
import sys

tn = Telnet('192.168.1.15', 13666, None)
pipe_contents = sys.stdin.read()
pipe_contents = pipe_contents.replace('\n', ' ')

tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 string\n")
tn.write("widget_add s1 w2 string\n")

def lcd_string(x, telnet_obj, delay=2):
    L = []
    for i in range(len(x)):
        if i % (15+16) == 0:
            L.append(x[i:i+15+16])
    for s in L:
        s1 = s[0:15]
        s2 = s[15:]
        telnet_obj.write("widget_set s1 w1 1 1 {" + s1 + "}\n")
        telnet_obj.write("widget_set s1 w2 1 2 {" + s2 + "}\n")
        time.sleep(delay)

lcd_string(pipe_contents, tn)

Prompt:
Read standard input instead of hard-coded strings.

from telnetlib import Telnet
import time
tn = Telnet('192.168.1.15', 13666, None)

#tn.interact()

tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 string\n")
tn.write("widget_add s1 w2 string\n")
tn.write("widget_set s1 w1 1 1 {It is a truth u}\n")
tn.write("widget_set s1 w2 1 2 {niversally ackno}\n")
print "sleeping"
time.sleep(5)

def lcd_string(x, telnet_obj, delay=5):
    L = []
    for i in range(len(x)):
        if i % (15+16) == 0:
            L.append(x[i:i+15+16])
    for s in L:
        s1 = s[0:15]
        s2 = s[15:]
        telnet_obj.write("widget_set s1 w1 1 1 {" + s1 + "}\n")
        telnet_obj.write("widget_set s1 w2 1 2 {" + s2 + "}\n")
        time.sleep(delay)

lcd_string('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', tn)


# -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io

import pep8
import pep257

__version__ = '0.2.1.post1'

class pep257Checker(object):

    """flake8 needs a class to check python file."""

    name = 'pep257'
    version = __version__

    STDIN_NAMES = set(['stdin', '-', '(none)', None])

    def __init__(self, tree, filename='(none)', builtins=None):
        self.tree = tree
        self.filename = filename
        self.source = self.load_source()
        self.checker = pep257.PEP257Checker()

    def run(self):
        """Use directly check() api from pep257."""
        for error in self.checker.check_source(self.source, self.filename):
            # Ignore AllError, Environment error.
            if isinstance(error, pep257.Error):
                yield (error.line, 0, error.message, type(self))

    def load_source(self):
        if self.filename in self.STDIN_NAMES:
            self.filename = 'stdin'
            self.source = pep8.stdin_get_value()
        else:
            with io.open(self.filename, encoding='utf-8') as fd:
                self.source = fd.read()

Handle stdin in the plugin

Handle stdin in the plugin

Closes #2

Response:
<INSERT> io

import pep8
import <INSERT_END> <INSERT> STDIN_NAMES = set(['stdin', '-', '(none)', None])

    <INSERT_END> <REPLACE_OLD> filename

 <REPLACE_NEW> filename
        self.source = self.load_source()
        self.checker = pep257.PEP257Checker()

 <REPLACE_END> <REPLACE_OLD> pep257.check([self.filename]):
 <REPLACE_NEW> self.checker.check_source(self.source, self.filename):
 <REPLACE_END> <REPLACE_OLD> type(self))
 <REPLACE_NEW> type(self))

    def load_source(self):
        if self.filename in self.STDIN_NAMES:
            self.filename = 'stdin'
            self.source = pep8.stdin_get_value()
        else:
            with io.open(self.filename, encoding='utf-8') as fd:
                self.source = fd.read()
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io

import pep8
import pep257

__version__ = '0.2.1.post1'

class pep257Checker(object):

    """flake8 needs a class to check python file."""

    name = 'pep257'
    version = __version__

    STDIN_NAMES = set(['stdin', '-', '(none)', None])

    def __init__(self, tree, filename='(none)', builtins=None):
        self.tree = tree
        self.filename = filename
        self.source = self.load_source()
        self.checker = pep257.PEP257Checker()

    def run(self):
        """Use directly check() api from pep257."""
        for error in self.checker.check_source(self.source, self.filename):
            # Ignore AllError, Environment error.
            if isinstance(error, pep257.Error):
                yield (error.line, 0, error.message, type(self))

    def load_source(self):
        if self.filename in self.STDIN_NAMES:
            self.filename = 'stdin'
            self.source = pep8.stdin_get_value()
        else:
            with io.open(self.filename, encoding='utf-8') as fd:
                self.source = fd.read()

Prompt:
Handle stdin in the plugin

Closes #2

# -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import pep257

__version__ = '0.2.1.post1'

class pep257Checker(object):

    """flake8 needs a class to check python file."""

    name = 'pep257'
    version = __version__

    def __init__(self, tree, filename='(none)', builtins=None):
        self.tree = tree
        self.filename = filename

    def run(self):
        """Use directly check() api from pep257."""
        for error in pep257.check([self.filename]):
            # Ignore AllError, Environment error.
            if isinstance(error, pep257.Error):
                yield (error.line, 0, error.message, type(self))


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

from tests_aio.unit._test_base import AioTestBase

class TestInit(AioTestBase):

    async def test_grpc(self):
        import grpc  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_grpc_dot_aio(self):
        import grpc.aio  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_aio_from_grpc(self):
        from grpc import aio  # pylint: disable=wrong-import-position
        channel = aio.insecure_channel('dummy')
        self.assertIsInstance(channel, aio.Channel)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)

Response:
<REPLACE_OLD> unittest

import grpc

from <REPLACE_NEW> unittest

from <REPLACE_END> <INSERT>    async def test_grpc(self):
        import grpc  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

 <INSERT_END> <INSERT> import grpc.aio  # pylint: disable=wrong-import-position
        <INSERT_END> <REPLACE_OLD> grpc.aio.Channel)

if <REPLACE_NEW> grpc.aio.Channel)

    async def test_aio_from_grpc(self):
        from grpc import aio  # pylint: disable=wrong-import-position
        channel = aio.insecure_channel('dummy')
        self.assertIsInstance(channel, aio.Channel)

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

from tests_aio.unit._test_base import AioTestBase

class TestInit(AioTestBase):

    async def test_grpc(self):
        import grpc  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_grpc_dot_aio(self):
        import grpc.aio  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_aio_from_grpc(self):
        from grpc import aio  # pylint: disable=wrong-import-position
        channel = aio.insecure_channel('dummy')
        self.assertIsInstance(channel, aio.Channel)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)

Prompt:
Expand alternatives to import aio module

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

import grpc

from tests_aio.unit._test_base import AioTestBase

class TestInit(AioTestBase):

    async def test_grpc_dot_aio(self):
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)


from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):

    '''
    <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
    </ack>

    <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}">
    </ack>

    '''

    def __init__(self, _id, _class, _type, _to, _participant = None):
        super(OutgoingAckProtocolEntity, self).__init__(_id, _class)
        self.setOutgoingData(_type, _to, _participant)

    def setOutgoingData(self, _type, _to, _participant):
        self._type = _type
        self._to = _to
        self._participant = _participant

    def toProtocolTreeNode(self):
        node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode()
        if self._type:
            node.setAttribute("type", self._type)
        node.setAttribute("to", self._to)
        if self._participant:
            node.setAttribute("participant", self._participant)
        return node

    def __str__(self):
        out  = super(OutgoingAckProtocolEntity, self).__str__()
        out += "Type: %s\n" % self._type
        out += "To: %s\n" % self._to
        if self._participant:
            out += "Participant: %s\n" % self._participant
        return out

    @staticmethod
    def fromProtocolTreeNode(node):
        entity = AckProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = OutgoingAckProtocolEntity
        entity.setOutgoingData(
            node.getAttributeValue("type"),
            node.getAttributeValue("to"),
            node.getAttributeValue("participant")
        )
        return entity

Include participant in outgoing ack

Include participant in outgoing ack

Response:
<REPLACE_OLD> </ack>
 <REPLACE_NEW> </ack>

    <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}">
    </ack>

 <REPLACE_END> <REPLACE_OLD> _to):
 <REPLACE_NEW> _to, _participant = None):
 <REPLACE_END> <REPLACE_OLD> _to)

 <REPLACE_NEW> _to, _participant)

 <REPLACE_END> <REPLACE_OLD> _to):
 <REPLACE_NEW> _to, _participant):
 <REPLACE_END> <INSERT>        self._participant = _participant
 <INSERT_END> <INSERT>        if self._participant:
            node.setAttribute("participant", self._participant)
 <INSERT_END> <INSERT> if self._participant:
            out += "Participant: %s\n" % self._participant
        <INSERT_END> <REPLACE_OLD> node.getAttributeValue("to")
 <REPLACE_NEW> node.getAttributeValue("to"),
            node.getAttributeValue("participant")
 <REPLACE_END> <|endoftext|> from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):

    '''
    <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
    </ack>

    <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}">
    </ack>

    '''

    def __init__(self, _id, _class, _type, _to, _participant = None):
        super(OutgoingAckProtocolEntity, self).__init__(_id, _class)
        self.setOutgoingData(_type, _to, _participant)

    def setOutgoingData(self, _type, _to, _participant):
        self._type = _type
        self._to = _to
        self._participant = _participant

    def toProtocolTreeNode(self):
        node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode()
        if self._type:
            node.setAttribute("type", self._type)
        node.setAttribute("to", self._to)
        if self._participant:
            node.setAttribute("participant", self._participant)
        return node

    def __str__(self):
        out  = super(OutgoingAckProtocolEntity, self).__str__()
        out += "Type: %s\n" % self._type
        out += "To: %s\n" % self._to
        if self._participant:
            out += "Participant: %s\n" % self._participant
        return out

    @staticmethod
    def fromProtocolTreeNode(node):
        entity = AckProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = OutgoingAckProtocolEntity
        entity.setOutgoingData(
            node.getAttributeValue("type"),
            node.getAttributeValue("to"),
            node.getAttributeValue("participant")
        )
        return entity

Prompt:
Include participant in outgoing ack

from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):

    '''
    <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
    </ack>
    '''

    def __init__(self, _id, _class, _type, _to):
        super(OutgoingAckProtocolEntity, self).__init__(_id, _class)
        self.setOutgoingData(_type, _to)

    def setOutgoingData(self, _type, _to):
        self._type = _type
        self._to = _to

    def toProtocolTreeNode(self):
        node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode()
        if self._type:
            node.setAttribute("type", self._type)
        node.setAttribute("to", self._to)
        return node

    def __str__(self):
        out  = super(OutgoingAckProtocolEntity, self).__str__()
        out += "Type: %s\n" % self._type
        out += "To: %s\n" % self._to
        return out

    @staticmethod
    def fromProtocolTreeNode(node):
        entity = AckProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = OutgoingAckProtocolEntity
        entity.setOutgoingData(
            node.getAttributeValue("type"),
            node.getAttributeValue("to")
        )
        return entity


import unittest, argparse
from echolalia.formatter.csver import Formatter

class CsverTestCase(unittest.TestCase):

  def setUp(self):
    self.parser = argparse.ArgumentParser()
    self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
    self.formatter = Formatter()

  def test_add_args(self):
    new_parser = self.formatter.add_args(self.parser)
    self.assertEqual(new_parser, self.parser)
    args = new_parser.parse_args(['--with_header'])
    self.assertTrue(args.with_header)
    args = new_parser.parse_args([])
    self.assertFalse(args.with_header)

  def test_marshall_no_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args([])
    result = self.formatter.marshall(args, self.data)
    expect = "a,1\r\nb,2\r\nc,3\r\n"
    self.assertEqual(result, expect)

  def test_marshall_with_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args(['--with_header'])
    result = self.formatter.marshall(args, self.data)
    expect = "char,order\r\na,1\r\nb,2\r\nc,3\r\n"
    self.assertEqual(result, expect)

Fix no header test for csv formatter

Fix no header test for csv formatter

Response:
<REPLACE_OLD> "a,1\r\nb,2\r\nc,3\r\n"

 <REPLACE_NEW> "a,1\r\nb,2\r\nc,3\r\n"
    self.assertEqual(result, expect)

 <REPLACE_END> <|endoftext|> import unittest, argparse
from echolalia.formatter.csver import Formatter

class CsverTestCase(unittest.TestCase):

  def setUp(self):
    self.parser = argparse.ArgumentParser()
    self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
    self.formatter = Formatter()

  def test_add_args(self):
    new_parser = self.formatter.add_args(self.parser)
    self.assertEqual(new_parser, self.parser)
    args = new_parser.parse_args(['--with_header'])
    self.assertTrue(args.with_header)
    args = new_parser.parse_args([])
    self.assertFalse(args.with_header)

  def test_marshall_no_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args([])
    result = self.formatter.marshall(args, self.data)
    expect = "a,1\r\nb,2\r\nc,3\r\n"
    self.assertEqual(result, expect)

  def test_marshall_with_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args(['--with_header'])
    result = self.formatter.marshall(args, self.data)
    expect = "char,order\r\na,1\r\nb,2\r\nc,3\r\n"
    self.assertEqual(result, expect)

Prompt:
Fix no header test for csv formatter

import unittest, argparse
from echolalia.formatter.csver import Formatter

class CsverTestCase(unittest.TestCase):

  def setUp(self):
    self.parser = argparse.ArgumentParser()
    self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
    self.formatter = Formatter()

  def test_add_args(self):
    new_parser = self.formatter.add_args(self.parser)
    self.assertEqual(new_parser, self.parser)
    args = new_parser.parse_args(['--with_header'])
    self.assertTrue(args.with_header)
    args = new_parser.parse_args([])
    self.assertFalse(args.with_header)

  def test_marshall_no_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args([])
    result = self.formatter.marshall(args, self.data)
    expect = "a,1\r\nb,2\r\nc,3\r\n"

  def test_marshall_with_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args(['--with_header'])
    result = self.formatter.marshall(args, self.data)
    expect = "char,order\r\na,1\r\nb,2\r\nc,3\r\n"
    self.assertEqual(result, expect)


import factory
from factory import fuzzy

from datetime import date, datetime, timezone

from dataactcore.models import jobModels

class SubmissionFactory(factory.Factory):
    class Meta:
        model = jobModels.Submission

    submission_id = None
    datetime_utc = fuzzy.FuzzyDateTime(
        datetime(2010, 1, 1, tzinfo=timezone.utc))
    user_id = fuzzy.FuzzyInteger(1, 9999)
    cgac_code = fuzzy.FuzzyText()
    reporting_start_date = fuzzy.FuzzyDate(date(2010, 1, 1))
    reporting_end_date = fuzzy.FuzzyDate(date(2010, 1, 1))
    reporting_fiscal_year = fuzzy.FuzzyInteger(2010, 2040)
    reporting_fiscal_period = fuzzy.FuzzyInteger(1, 4)
    is_quarter_format = False
    publishable = False
    number_of_errors = 0
    number_of_warnings = 0

Add factory for Submission model

Add factory for Submission model

Response:
<INSERT> import factory
from factory import fuzzy

from datetime import date, datetime, timezone

from dataactcore.models import jobModels

class SubmissionFactory(factory.Factory):
 <INSERT_END> <INSERT>   class Meta:
        model = jobModels.Submission

    submission_id = None
    datetime_utc = fuzzy.FuzzyDateTime(
        datetime(2010, 1, 1, tzinfo=timezone.utc))
    user_id = fuzzy.FuzzyInteger(1, 9999)
    cgac_code = fuzzy.FuzzyText()
    reporting_start_date = fuzzy.FuzzyDate(date(2010, 1, 1))
    reporting_end_date = fuzzy.FuzzyDate(date(2010, 1, 1))
    reporting_fiscal_year = fuzzy.FuzzyInteger(2010, 2040)
    reporting_fiscal_period = fuzzy.FuzzyInteger(1, 4)
    is_quarter_format = False
    publishable = False
    number_of_errors = 0
    number_of_warnings = 0
 <INSERT_END> <|endoftext|> import factory
from factory import fuzzy

from datetime import date, datetime, timezone

from dataactcore.models import jobModels

class SubmissionFactory(factory.Factory):
    class Meta:
        model = jobModels.Submission

    submission_id = None
    datetime_utc = fuzzy.FuzzyDateTime(
        datetime(2010, 1, 1, tzinfo=timezone.utc))
    user_id = fuzzy.FuzzyInteger(1, 9999)
    cgac_code = fuzzy.FuzzyText()
    reporting_start_date = fuzzy.FuzzyDate(date(2010, 1, 1))
    reporting_end_date = fuzzy.FuzzyDate(date(2010, 1, 1))
    reporting_fiscal_year = fuzzy.FuzzyInteger(2010, 2040)
    reporting_fiscal_period = fuzzy.FuzzyInteger(1, 4)
    is_quarter_format = False
    publishable = False
    number_of_errors = 0
    number_of_warnings = 0

Prompt: Add factory for Submission model


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

'''
Tests for the salt-run command
'''

# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')

# Import salt libs
import integration

class ManageTest(integration.ShellCase):
    '''
    Test the manage runner
    '''
    def test_active(self):
        '''
        jobs.active
        '''
        ret = self.run_run_plus('jobs.active')
        self.assertEqual(ret['fun'], {})
        self.assertEqual(ret['out'], [])

    def test_lookup_jid(self):
        '''
        jobs.lookup_jid
        '''
        ret = self.run_run_plus('jobs.lookup_jid', '', '23974239742394')
        self.assertEqual(ret['fun'], {})
        self.assertEqual(ret['out'], [])

    def test_list_jobs(self):
        '''
        jobs.list_jobs
        '''
        ret = self.run_run_plus('jobs.list_jobs')
        self.assertIsInstance(ret['fun'], dict)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ManageTest)

Response:
<REPLACE_OLD> ['{}'])

 <REPLACE_NEW> [])

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

'''
Tests for the salt-run command
'''

# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')

# Import salt libs
import integration

class ManageTest(integration.ShellCase):
    '''
    Test the manage runner
    '''
    def test_active(self):
        '''
        jobs.active
        '''
        ret = self.run_run_plus('jobs.active')
        self.assertEqual(ret['fun'], {})
        self.assertEqual(ret['out'], [])

    def test_lookup_jid(self):
        '''
        jobs.lookup_jid
        '''
        ret = self.run_run_plus('jobs.lookup_jid', '', '23974239742394')
        self.assertEqual(ret['fun'], {})
        self.assertEqual(ret['out'], [])

    def test_list_jobs(self):
        '''
        jobs.list_jobs
        '''
        ret = self.run_run_plus('jobs.list_jobs')
        self.assertIsInstance(ret['fun'], dict)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ManageTest)

Prompt:
Fix the output now that we are using the default output (nested) instead of hard coding it to yaml

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

'''
Tests for the salt-run command
'''

# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')

# Import salt libs
import integration

class ManageTest(integration.ShellCase):
    '''
    Test the manage runner
    '''
    def test_active(self):
        '''
        jobs.active
        '''
        ret = self.run_run_plus('jobs.active')
        self.assertEqual(ret['fun'], {})
        self.assertEqual(ret['out'], ['{}'])

    def test_lookup_jid(self):
        '''
        jobs.lookup_jid
        '''
        ret = self.run_run_plus('jobs.lookup_jid', '', '23974239742394')
        self.assertEqual(ret['fun'], {})
        self.assertEqual(ret['out'], [])

    def test_list_jobs(self):
        '''
        jobs.list_jobs
        '''
        ret = self.run_run_plus('jobs.list_jobs')
        self.assertIsInstance(ret['fun'], dict)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ManageTest)


# coding: utf-8

from decouple import config
from findaconf.tests.fake_data import fake_conference, seed

def set_app(app, db=False):

    # set test vars
    app.config['TESTING'] = True
    app.config['WTF_CSRF_ENABLED'] = False

    # set test db
    if db:
        app.config['SQLALCHEMY_DATABASE_URI'] = config(
            'DATABASE_URL_TEST',
            default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
                                                               'tests',
                                                               'tests.db')
        )

    # create test app
    test_app = app.test_client()

    # create and feed db tables
    if db:

        # start from a clean db
        db.session.remove()
        db.drop_all()

        # create tables and feed them
        db.create_all()
        seed(app, db)
        [db.session.add(fake_conference(db)) for i in range(1, 43)]
        db.session.commit()

    # return test app
    return test_app

def unset_app(db=False):
    if db:
        db.session.remove()
        db.drop_all()

Response:
<REPLACE_OLD> unset_app(db)
 <REPLACE_NEW>
    # set test vars
 <REPLACE_END> <INSERT>
    # set test db
    <INSERT_END> <INSERT>
    # create test app
    <INSERT_END> <INSERT>
    # create and feed db tables
    <INSERT_END> <INSERT>
        # start from a clean db
        db.session.remove()
        db.drop_all()

        # create tables and feed them
 <INSERT_END> <INSERT>
    # return test app
    <INSERT_END> <|endoftext|> # coding: utf-8

from decouple import config
from findaconf.tests.fake_data import fake_conference, seed

def set_app(app, db=False):

    # set test vars
    app.config['TESTING'] = True
    app.config['WTF_CSRF_ENABLED'] = False

    # set test db
    if db:
        app.config['SQLALCHEMY_DATABASE_URI'] = config(
            'DATABASE_URL_TEST',
            default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
                                                               'tests',
                                                               'tests.db')
        )

    # create test app
    test_app = app.test_client()

    # create and feed db tables
    if db:

        # start from a clean db
        db.session.remove()
        db.drop_all()

        # create tables and feed them
        db.create_all()
        seed(app, db)
        [db.session.add(fake_conference(db)) for i in range(1, 43)]
        db.session.commit()

    # return test app
    return test_app

def unset_app(db=False):
    if db:
        db.session.remove()
        db.drop_all()

Prompt:
Fix bug that used dev db instead of test db

# coding: utf-8

from decouple import config
from findaconf.tests.fake_data import fake_conference, seed

def set_app(app, db=False):
    unset_app(db)
    app.config['TESTING'] = True
    app.config['WTF_CSRF_ENABLED'] = False
    if db:
        app.config['SQLALCHEMY_DATABASE_URI'] = config(
            'DATABASE_URL_TEST',
            default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
                                                               'tests',
                                                               'tests.db')
        )
    test_app = app.test_client()
    if db:
        db.create_all()
        seed(app, db)
        [db.session.add(fake_conference(db)) for i in range(1, 43)]
        db.session.commit()
    return test_app

def unset_app(db=False):
    if db:
        db.session.remove()
        db.drop_all()