from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language

from simpleseo import settings
from simpleseo.models import SeoMetadata

register = Library()

@register.filter
def single_quotes(description):
    return description.replace('\"', '\'')

@register.inclusion_tag('simpleseo/metadata.html', takes_context=True)
def get_seo(context, **kwargs):
    path = context['request'].path
    lang_code = get_language()[:2]
    try:
        metadata = model_to_dict(SeoMetadata.objects.get(path=path,
                                                         lang_code=lang_code))
    except SeoMetadata.DoesNotExist:
        metadata = {}
    result = {}
    for item in ['title', 'description']:
        result[item] = (metadata.get(item) or
                        kwargs.get(item) or
                        getattr(settings, 'FALLBACK_{0}'.format(item.upper())))
    return result

@register.simple_tag(takes_context=True)
def get_seo_title(context, default=''):
    return get_seo(context, title=default).get('title')

@register.simple_tag(takes_context=True)
def get_seo_description(context, default=''):
    return get_seo(context, description=default).get('description')

Allow to set default value in template

Allow to set default value in template

Response:
<INSERT> django.forms.models import model_to_dict
from <INSERT_END> <REPLACE_OLD> get_seo(context):
 <REPLACE_NEW> get_seo(context, **kwargs):
    path = context['request'].path
 <REPLACE_END> <DELETE> path = context['request'].path
    <DELETE_END> <REPLACE_OLD> SeoMetadata.objects.get(path=path, lang_code=lang_code)
 <REPLACE_NEW> model_to_dict(SeoMetadata.objects.get(path=path,
                                                         lang_code=lang_code))
 <REPLACE_END> <REPLACE_OLD> None
    if metadata is None:
        return {'title': settings.FALLBACK_TITLE,
                'description': settings.FALLBACK_DESCRIPTION}
    return {'title': metadata.title, 'description': metadata.description}

@register.simple_tag(takes_context=True)
def get_seo_title(context):
    return get_seo(context)['title']

@register.simple_tag(takes_context=True)
def get_seo_description(context):
    return get_seo(context)['description']
 <REPLACE_NEW> {}
    result = {}
    for item in ['title', 'description']:
        result[item] = (metadata.get(item) or
                        kwargs.get(item) or
                        getattr(settings, 'FALLBACK_{0}'.format(item.upper())))
    return result

@register.simple_tag(takes_context=True)
def get_seo_title(context, default=''):
    return get_seo(context, title=default).get('title')

@register.simple_tag(takes_context=True)
def get_seo_description(context, default=''):
    return get_seo(context, description=default).get('description')
 <REPLACE_END> <|endoftext|> from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language

from simpleseo import settings
from simpleseo.models import SeoMetadata

register = Library()

@register.filter
def single_quotes(description):
    return description.replace('\"', '\'')

@register.inclusion_tag('simpleseo/metadata.html', takes_context=True)
def get_seo(context, **kwargs):
    path = context['request'].path
    lang_code = get_language()[:2]
    try:
        metadata = model_to_dict(SeoMetadata.objects.get(path=path,
                                                         lang_code=lang_code))
    except SeoMetadata.DoesNotExist:
        metadata = {}
    result = {}
    for item in ['title', 'description']:
        result[item] = (metadata.get(item) or
                        kwargs.get(item) or
                        getattr(settings, 'FALLBACK_{0}'.format(item.upper())))
    return result

@register.simple_tag(takes_context=True)
def get_seo_title(context, default=''):
    return get_seo(context, title=default).get('title')

@register.simple_tag(takes_context=True)
def get_seo_description(context, default=''):
    return get_seo(context, description=default).get('description')

Prompt:
Allow to set default value in template

from django.template import Library
from django.utils.translation import get_language

from simpleseo import settings
from simpleseo.models import SeoMetadata

register = Library()

@register.filter
def single_quotes(description):
    return description.replace('\"', '\'')

@register.inclusion_tag('simpleseo/metadata.html', takes_context=True)
def get_seo(context):
    lang_code = get_language()[:2]
    path = context['request'].path
    try:
        metadata = SeoMetadata.objects.get(path=path, lang_code=lang_code)
    except SeoMetadata.DoesNotExist:
        metadata = None
    if metadata is None:
        return {'title': settings.FALLBACK_TITLE,
                'description': settings.FALLBACK_DESCRIPTION}
    return {'title': metadata.title, 'description': metadata.description}

@register.simple_tag(takes_context=True)
def get_seo_title(context):
    return get_seo(context)['title']

@register.simple_tag(takes_context=True)
def get_seo_description(context):
    return get_seo(context)['description']


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

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('git_externals/__init__.py') as fp:
    exec(fp.read())

classifiers = [
    'Development Status :: 4 - Beta',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='git-externals',
    version=__version__,
    description='utility to manage svn externals',
    long_description='',
    packages=['git_externals'],
    install_requires=['click',
                      'pathlib'],
    entry_points={
        'console_scripts': [
            'git-externals = git_externals.git_externals:cli',
            'gittify-cleanup = git_externals.cleanup_repo:main',
            'svn-externals-info = git_externals.process_externals:main',
            'gittify = git_externals.gittify:main',
            'gittify-gen = git_externals.makefiles:cli',
        ],
    },
    author=__author__,
    author_email=__email__,
    license='MIT',
    classifiers=classifiers,
)

Remove version requirement, add pathlib

Remove version requirement, add pathlib

Response:
<REPLACE_OLD> install_requires=['click>=6.0'],
 <REPLACE_NEW> install_requires=['click',
                      'pathlib'],
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('git_externals/__init__.py') as fp:
    exec(fp.read())

classifiers = [
    'Development Status :: 4 - Beta',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='git-externals',
    version=__version__,
    description='utility to manage svn externals',
    long_description='',
    packages=['git_externals'],
    install_requires=['click',
                      'pathlib'],
    entry_points={
        'console_scripts': [
            'git-externals = git_externals.git_externals:cli',
            'gittify-cleanup = git_externals.cleanup_repo:main',
            'svn-externals-info = git_externals.process_externals:main',
            'gittify = git_externals.gittify:main',
            'gittify-gen = git_externals.makefiles:cli',
        ],
    },
    author=__author__,
    author_email=__email__,
    license='MIT',
    classifiers=classifiers,
)

Prompt:
Remove version requirement, add pathlib

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

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('git_externals/__init__.py') as fp:
    exec(fp.read())

classifiers = [
    'Development Status :: 4 - Beta',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='git-externals',
    version=__version__,
    description='utility to manage svn externals',
    long_description='',
    packages=['git_externals'],
    install_requires=['click>=6.0'],
    entry_points={
        'console_scripts': [
            'git-externals = git_externals.git_externals:cli',
            'gittify-cleanup = git_externals.cleanup_repo:main',
            'svn-externals-info = git_externals.process_externals:main',
            'gittify = git_externals.gittify:main',
            'gittify-gen = git_externals.makefiles:cli',
        ],
    },
    author=__author__,
    author_email=__email__,
    license='MIT',
    classifiers=classifiers,
)


from unittest import TestCase

from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier

class ConstructIGTTests(TestCase):

    def setUp(self):
        self.lines = [{'text':'This is a test','tag':'L'},
                      {'text':'blah blah blah blah','tag':'G'}]

    def test_add_raw_lines(self):
        inst = Igt(id='i1')
        add_raw_tier(inst, self.lines)
        self.assertEqual(len(raw_tier(inst)), 2)

    def test_add_clean_lines(self):
        inst = Igt(id='i1')
        add_clean_tier(inst, self.lines)
        self.assertEqual(len(cleaned_tier(inst)), 2)

    def test_add_norm_lines(self):
        inst = Igt(id='i1')
        add_normal_tier(inst, self.lines)
        self.assertEqual(len(normalized_tier(inst)), 2)

Move testcases here from INTENT.

Move testcases here from INTENT.

Response:
<INSERT> from unittest import TestCase

from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier

class ConstructIGTTests(TestCase):

 <INSERT_END> <INSERT>   def setUp(self):
        self.lines = [{'text':'This is a test','tag':'L'},
                      {'text':'blah blah blah blah','tag':'G'}]

    def test_add_raw_lines(self):
        inst = Igt(id='i1')
        add_raw_tier(inst, self.lines)
        self.assertEqual(len(raw_tier(inst)), 2)

    def test_add_clean_lines(self):
        inst = Igt(id='i1')
        add_clean_tier(inst, self.lines)
        self.assertEqual(len(cleaned_tier(inst)), 2)

    def test_add_norm_lines(self):
        inst = Igt(id='i1')
        add_normal_tier(inst, self.lines)
        self.assertEqual(len(normalized_tier(inst)), 2) <INSERT_END> <|endoftext|> from unittest import TestCase

from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier

class ConstructIGTTests(TestCase):

    def setUp(self):
        self.lines = [{'text':'This is a test','tag':'L'},
                      {'text':'blah blah blah blah','tag':'G'}]

    def test_add_raw_lines(self):
        inst = Igt(id='i1')
        add_raw_tier(inst, self.lines)
        self.assertEqual(len(raw_tier(inst)), 2)

    def test_add_clean_lines(self):
        inst = Igt(id='i1')
        add_clean_tier(inst, self.lines)
        self.assertEqual(len(cleaned_tier(inst)), 2)

    def test_add_norm_lines(self):
        inst = Igt(id='i1')
        add_normal_tier(inst, self.lines)
        self.assertEqual(len(normalized_tier(inst)), 2)

Prompt: Move testcases here from INTENT.


# -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel

def channel_context(request):
    """ Channel context processors
    """
    opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
                                       published=True)

    return {'opps_menu': opps_menu}

Response:
<INSERT> django.utils import timezone
from <INSERT_END> <INSERT> """ Channel context processors
    """
    opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
                                       published=True)

    <INSERT_END> <REPLACE_OLD> Channel.objects.all()}
 <REPLACE_NEW> opps_menu}
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel

def channel_context(request):
    """ Channel context processors
    """
    opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
                                       published=True)

    return {'opps_menu': opps_menu}

Prompt:
Apply filter channel published on menu list (channel context processors)

# -*- coding: utf-8 -*-
from .models import Channel

def channel_context(request):
    return {'opps_menu': Channel.objects.all()}


import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.requestdata.model import setup as model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth

class RequestdataPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IConfigurable)
    plugins.implements(plugins.IActions)
    plugins.implements(plugins.IAuthFunctions)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'requestdata')

    # IMapper

    def before_map(self, map):
        controller =\
            'ckanext.requestdata.controllers.package:PackageController'

        map.connect('/dataset/make_active/{pkg_name}', controller=controller,
                    action='make_active')

        return map

    # IConfigurable

    def configure(self, config):

        # Setup requestdata model
        model_setup()

    # IActions

    def get_actions(self):
        return {
            'requestdata_request_create': actions.request_create,
            'requestdata_request_show': actions.request_show,
            'requestdata_request_list': actions.request_list,
            'requestdata_request_patch': actions.request_patch,
            'requestdata_request_update': actions.request_update,
            'requestdata_request_delete': actions.request_delete
        }

    # IAuthFunctions

    def get_auth_functions(self):
        return {
            'requestdata_request_create': auth.request_create
        }

Define actions and auth functions

Define actions and auth functions

Response:
<REPLACE_OLD> model_setup

class <REPLACE_NEW> model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth

class <REPLACE_END> <REPLACE_OLD> plugins.implements(plugins.IConfigurable)

 <REPLACE_NEW> plugins.implements(plugins.IConfigurable)
    plugins.implements(plugins.IActions)
    plugins.implements(plugins.IAuthFunctions)

 <REPLACE_END> <REPLACE_OLD> model_setup()
 <REPLACE_NEW> model_setup()

    # IActions

    def get_actions(self):
        return {
            'requestdata_request_create': actions.request_create,
            'requestdata_request_show': actions.request_show,
            'requestdata_request_list': actions.request_list,
            'requestdata_request_patch': actions.request_patch,
            'requestdata_request_update': actions.request_update,
            'requestdata_request_delete': actions.request_delete
        }

    # IAuthFunctions

    def get_auth_functions(self):
        return {
            'requestdata_request_create': auth.request_create
        }
 <REPLACE_END> <|endoftext|> import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.requestdata.model import setup as model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth

class RequestdataPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IConfigurable)
    plugins.implements(plugins.IActions)
    plugins.implements(plugins.IAuthFunctions)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'requestdata')

    # IMapper

    def before_map(self, map):
        controller =\
            'ckanext.requestdata.controllers.package:PackageController'

        map.connect('/dataset/make_active/{pkg_name}', controller=controller,
                    action='make_active')

        return map

    # IConfigurable

    def configure(self, config):

        # Setup requestdata model
        model_setup()

    # IActions

    def get_actions(self):
        return {
            'requestdata_request_create': actions.request_create,
            'requestdata_request_show': actions.request_show,
            'requestdata_request_list': actions.request_list,
            'requestdata_request_patch': actions.request_patch,
            'requestdata_request_update': actions.request_update,
            'requestdata_request_delete': actions.request_delete
        }

    # IAuthFunctions

    def get_auth_functions(self):
        return {
            'requestdata_request_create': auth.request_create
        }

Prompt:
Define actions and auth functions

import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.requestdata.model import setup as model_setup

class RequestdataPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IConfigurable)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'requestdata')

    # IMapper

    def before_map(self, map):
        controller =\
            'ckanext.requestdata.controllers.package:PackageController'

        map.connect('/dataset/make_active/{pkg_name}', controller=controller,
                    action='make_active')

        return map

    # IConfigurable

    def configure(self, config):

        # Setup requestdata model
        model_setup()


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

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = False
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = False

Disable SQL logging in appengine

Disable SQL logging in appengine

Response:
<REPLACE_OLD> True
MEMCACHE_MECHANISM <REPLACE_NEW> False
MEMCACHE_MECHANISM <REPLACE_END> <|endoftext|> # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = False
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = False

Prompt:
Disable SQL logging in appengine

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

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = True
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = False


from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_test_srs = g.live_config.get("adzerk_test_srs")
        if adzerk_test_srs and c.site.name in adzerk_test_srs:
            self.ad_url = g.config["adzerk_url"]
            self.frame_id = "ad_main"

Set the frame id to what aderk expects.

Response:
<INSERT>            self.frame_id = "ad_main"
 <INSERT_END> <|endoftext|> from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_test_srs = g.live_config.get("adzerk_test_srs")
        if adzerk_test_srs and c.site.name in adzerk_test_srs:
            self.ad_url = g.config["adzerk_url"]
            self.frame_id = "ad_main"

Prompt:
Set the frame id to what aderk expects.

(See a corresponding change to ads.html in reddit)

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_test_srs = g.live_config.get("adzerk_test_srs")
        if adzerk_test_srs and c.site.name in adzerk_test_srs:
            self.ad_url = g.config["adzerk_url"]


"""Test IAM Policy templates are valid JSON."""
import jinja2

from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES

def iam_templates():
    """Generate list of IAM templates."""
    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))

    iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
        x.startswith('infrastructure/iam/'),
        'trust' not in x,
        'wrapper' not in x, ]))

    for iam_template_name in iam_template_names:
        yield iam_template_name

        items = ['resource1', 'resource2']

        if service == 'rds-db':
            items = {
                'resource1': 'user1',
                'resource2': 'user2',
            }

        rendered = render_policy_template(
            account_number='',
            app='coreforrest',
            env='dev',
            group='forrest',
            items=items,
            pipeline_settings={
                'lambda': {
                    'vpc_enabled': False,
                },
            },
            region='us-east-1',
            service=service)

        assert isinstance(rendered, list)

Use generator for IAM template names

Response:
<REPLACE_OLD> test_all_iam_templates():
    """Verify all <REPLACE_NEW> iam_templates():
    """Generate list of <REPLACE_END> <REPLACE_OLD> templates render as proper JSON."""
 <REPLACE_NEW> templates."""
 <REPLACE_END> <REPLACE_OLD> iam_templates <REPLACE_NEW> iam_template_names <REPLACE_END> <REPLACE_OLD> template <REPLACE_NEW> iam_template_name <REPLACE_END> <REPLACE_OLD> iam_templates:
        *_, service_json = template.split('/')
        service, *_ = service_json.split('.')

 <REPLACE_NEW> iam_template_names:
        yield iam_template_name

 <REPLACE_END> <|endoftext|> """Test IAM Policy templates are valid JSON."""
import jinja2

from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES

def iam_templates():
    """Generate list of IAM templates."""
    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))

    iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
        x.startswith('infrastructure/iam/'),
        'trust' not in x,
        'wrapper' not in x, ]))

    for iam_template_name in iam_template_names:
        yield iam_template_name

        items = ['resource1', 'resource2']

        if service == 'rds-db':
            items = {
                'resource1': 'user1',
                'resource2': 'user2',
            }

        rendered = render_policy_template(
            account_number='',
            app='coreforrest',
            env='dev',
            group='forrest',
            items=items,
            pipeline_settings={
                'lambda': {
                    'vpc_enabled': False,
                },
            },
            region='us-east-1',
            service=service)

        assert isinstance(rendered, list)

Prompt:
test: Use generator for IAM template names

See also: #208

"""Test IAM Policy templates are valid JSON."""
import jinja2

from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES

def test_all_iam_templates():
    """Verify all IAM templates render as proper JSON."""
    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))

    iam_templates = jinjaenv.list_templates(filter_func=lambda x: all([
        x.startswith('infrastructure/iam/'),
        'trust' not in x,
        'wrapper' not in x, ]))

    for template in iam_templates:
        *_, service_json = template.split('/')
        service, *_ = service_json.split('.')

        items = ['resource1', 'resource2']

        if service == 'rds-db':
            items = {
                'resource1': 'user1',
                'resource2': 'user2',
            }

        rendered = render_policy_template(
            account_number='',
            app='coreforrest',
            env='dev',
            group='forrest',
            items=items,
            pipeline_settings={
                'lambda': {
                    'vpc_enabled': False,
                },
            },
            region='us-east-1',
            service=service)

        assert isinstance(rendered, list)


"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

from datetime import tzinfo

class UTC(tzinfo):
    """
    The one true time zone.
    """

    def utcoffset(self, dt):
        """
        Return the offset to UTC.
        """

        from datetime import timedelta

        return timedelta(0)

    def tzname(self, dt):
        """
        Return the time zone name.
        """

        return "UTC"

    def dst(self, dt):
        """
        Return the DST offset.
        """

        from datetime import timedelta

        return timedelta(0)

def utc_now():
    """
    Return a non-naive UTC datetime instance.
    """

    from datetime import datetime as DateTime

    return DateTime.now(UTC())

def seconds(value):
    """
    Return the equivalent number of seconds, floating-point.
    """

    return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6

Response:
<REPLACE_OLD> instance, zoned pytz.utc.
 <REPLACE_NEW> instance.
 <REPLACE_END> <|endoftext|> """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

from datetime import tzinfo

class UTC(tzinfo):
    """
    The one true time zone.
    """

    def utcoffset(self, dt):
        """
        Return the offset to UTC.
        """

        from datetime import timedelta

        return timedelta(0)

    def tzname(self, dt):
        """
        Return the time zone name.
        """

        return "UTC"

    def dst(self, dt):
        """
        Return the DST offset.
        """

        from datetime import timedelta

        return timedelta(0)

def utc_now():
    """
    Return a non-naive UTC datetime instance.
    """

    from datetime import datetime as DateTime

    return DateTime.now(UTC())

def seconds(value):
    """
    Return the equivalent number of seconds, floating-point.
    """

    return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6

Prompt:
Fix comment after dropping the pytz dependency.

"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

from datetime import tzinfo

class UTC(tzinfo):
    """
    The one true time zone.
    """

    def utcoffset(self, dt):
        """
        Return the offset to UTC.
        """

        from datetime import timedelta

        return timedelta(0)

    def tzname(self, dt):
        """
        Return the time zone name.
        """

        return "UTC"

    def dst(self, dt):
        """
        Return the DST offset.
        """

        from datetime import timedelta

        return timedelta(0)

def utc_now():
    """
    Return a non-naive UTC datetime instance, zoned pytz.utc.
    """

    from datetime import datetime as DateTime

    return DateTime.now(UTC())

def seconds(value):
    """
    Return the equivalent number of seconds, floating-point.
    """

    return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6


import overview
import personnel
import match
import events
import statistics

CSV_ETL_CLASSES = {
    'Overview': {
        'Competitions': overview.CompetitionIngest,
        'Clubs': overview.ClubIngest,
        'Venues': overview.VenueIngest
    },
    'Personnel': {
        'Players': personnel.PlayerIngest,
        'Managers': personnel.ManagerIngest,
        'Referees': personnel.RefereeIngest
    },
    'Match': {
        'Matches': match.MatchIngest,
        'Lineups': match.MatchLineupIngest,
        'Goals': events.GoalIngest,
        'Penalties': events.PenaltyIngest,
        'Bookables': events.BookableIngest,
        'Substitutions': events.SubstitutionIngest,
        'PlayerStats': [
            statistics.AssistsIngest,
            statistics.ClearancesIngest,
            statistics.CornerCrossesIngest,
            statistics.CornersIngest,
            statistics.CrossesIngest,
            statistics.DefensivesIngest,
            statistics.DisciplineIngest,
            statistics.DuelsIngest,
            statistics.FoulWinsIngest,
            statistics.FreeKicksIngest,
            statistics.GKActionsIngest,
            statistics.GKAllowedGoalsIngest,
            statistics.GKAllowedShotsIngest,
            statistics.GKSavesIngest,
            statistics.GoalBodyPartsIngest,
            statistics.GoalLineClearancesIngest,
            statistics.GoalLocationsIngest,
            statistics.GoalTotalsIngest,
            statistics.ImportantPlaysIngest,
            statistics.MatchStatIngest,
            statistics.PassDirectionsIngest,
            statistics.PassLengthsIngest,
            statistics.PassLocationsIngest,
            statistics.PassTotalsIngest,
            statistics.PenaltyActionsIngest,
            statistics.ShotBlocksIngest,
            statistics.ShotBodyPartsIngest,
            statistics.ShotLocationsIngest,
            statistics.ShotPlaysIngest,
            statistics.TacklesIngest,
            statistics.ThrowinsIngest,
            statistics.TouchesIngest,
            statistics.TouchLocationsIngest
        ]
    }
}

Create dictionary to map ETL data files to ingestion classes

Response:
<REPLACE_OLD>  <REPLACE_NEW> import overview
import personnel
import match
import events
import statistics

CSV_ETL_CLASSES = {
    'Overview': {
        'Competitions': overview.CompetitionIngest,
        'Clubs': overview.ClubIngest,
        'Venues': overview.VenueIngest
    },
    'Personnel': {
        'Players': personnel.PlayerIngest,
        'Managers': personnel.ManagerIngest,
        'Referees': personnel.RefereeIngest
    },
    'Match': {
        'Matches': match.MatchIngest,
        'Lineups': match.MatchLineupIngest,
        'Goals': events.GoalIngest,
        'Penalties': events.PenaltyIngest,
        'Bookables': events.BookableIngest,
        'Substitutions': events.SubstitutionIngest,
        'PlayerStats': [
            statistics.AssistsIngest,
            statistics.ClearancesIngest,
            statistics.CornerCrossesIngest,
            statistics.CornersIngest,
            statistics.CrossesIngest,
            statistics.DefensivesIngest,
            statistics.DisciplineIngest,
            statistics.DuelsIngest,
            statistics.FoulWinsIngest,
            statistics.FreeKicksIngest,
            statistics.GKActionsIngest,
            statistics.GKAllowedGoalsIngest,
            statistics.GKAllowedShotsIngest,
            statistics.GKSavesIngest,
            statistics.GoalBodyPartsIngest,
            statistics.GoalLineClearancesIngest,
            statistics.GoalLocationsIngest,
            statistics.GoalTotalsIngest,
            statistics.ImportantPlaysIngest,
            statistics.MatchStatIngest,
            statistics.PassDirectionsIngest,
            statistics.PassLengthsIngest,
            statistics.PassLocationsIngest,
            statistics.PassTotalsIngest,
            statistics.PenaltyActionsIngest,
            statistics.ShotBlocksIngest,
            statistics.ShotBodyPartsIngest,
            statistics.ShotLocationsIngest,
            statistics.ShotPlaysIngest,
            statistics.TacklesIngest,
            statistics.ThrowinsIngest,
            statistics.TouchesIngest,
            statistics.TouchLocationsIngest
        ]
    }
}
 <REPLACE_END> <|endoftext|> import overview
import personnel
import match
import events
import statistics

CSV_ETL_CLASSES = {
    'Overview': {
        'Competitions': overview.CompetitionIngest,
        'Clubs': overview.ClubIngest,
        'Venues': overview.VenueIngest
    },
    'Personnel': {
        'Players': personnel.PlayerIngest,
        'Managers': personnel.ManagerIngest,
        'Referees': personnel.RefereeIngest
    },
    'Match': {
        'Matches': match.MatchIngest,
        'Lineups': match.MatchLineupIngest,
        'Goals': events.GoalIngest,
        'Penalties': events.PenaltyIngest,
        'Bookables': events.BookableIngest,
        'Substitutions': events.SubstitutionIngest,
        'PlayerStats': [
            statistics.AssistsIngest,
            statistics.ClearancesIngest,
            statistics.CornerCrossesIngest,
            statistics.CornersIngest,
            statistics.CrossesIngest,
            statistics.DefensivesIngest,
            statistics.DisciplineIngest,
            statistics.DuelsIngest,
            statistics.FoulWinsIngest,
            statistics.FreeKicksIngest,
            statistics.GKActionsIngest,
            statistics.GKAllowedGoalsIngest,
            statistics.GKAllowedShotsIngest,
            statistics.GKSavesIngest,
            statistics.GoalBodyPartsIngest,
            statistics.GoalLineClearancesIngest,
            statistics.GoalLocationsIngest,
            statistics.GoalTotalsIngest,
            statistics.ImportantPlaysIngest,
            statistics.MatchStatIngest,
            statistics.PassDirectionsIngest,
            statistics.PassLengthsIngest,
            statistics.PassLocationsIngest,
            statistics.PassTotalsIngest,
            statistics.PenaltyActionsIngest,
            statistics.ShotBlocksIngest,
            statistics.ShotBodyPartsIngest,
            statistics.ShotLocationsIngest,
            statistics.ShotPlaysIngest,
            statistics.TacklesIngest,
            statistics.ThrowinsIngest,
            statistics.TouchesIngest,
            statistics.TouchLocationsIngest
        ]
    }
}

Prompt: Create dictionary to map ETL data files to ingestion classes


from sublime_plugin import TextCommand

from ...core.base_command import BaseCommand
from ..github import open_file_in_browser

class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):

    """
    Open a new browser window to the web-version of the currently opened
    (or specified) file. If `preselect` is `True`, include the selected
    lines in the request.

    At present, this only supports github.com and GitHub enterprise.
    """

    def run(self, edit, preselect=False, fpath=None):
        fpath = fpath or self.get_rel_path()
        start_line = None
        end_line = None

        if preselect:
            selections = self.view.sel()
            if len(selections) >= 1:
                first_selection = selections[0]
                last_selection = selections[-1]
                # Git lines are 1-indexed; Sublime rows are 0-indexed.
                start_line = self.view.rowcol(first_selection.begin())[0] + 1
                end_line = self.view.rowcol(last_selection.end())[0] + 1

        default_name, default_remote_url = self.get_remotes().popitem(last=False)

        open_file_in_browser(
            fpath,
            default_remote_url,
            self.get_commit_hash_for_head(),
            start_line=start_line,
            end_line=end_line
        )

Response:
<REPLACE_OLD> ...common.file_and_repo <REPLACE_NEW> ...core.base_command <REPLACE_END> <REPLACE_OLD> FileAndRepo
from <REPLACE_NEW> BaseCommand
from <REPLACE_END> <REPLACE_OLD> FileAndRepo):

 <REPLACE_NEW> BaseCommand):

 <REPLACE_END> <INSERT> edit, <INSERT_END> <|endoftext|> from sublime_plugin import TextCommand

from ...core.base_command import BaseCommand
from ..github import open_file_in_browser

class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):

    """
    Open a new browser window to the web-version of the currently opened
    (or specified) file. If `preselect` is `True`, include the selected
    lines in the request.

    At present, this only supports github.com and GitHub enterprise.
    """

    def run(self, edit, preselect=False, fpath=None):
        fpath = fpath or self.get_rel_path()
        start_line = None
        end_line = None

        if preselect:
            selections = self.view.sel()
            if len(selections) >= 1:
                first_selection = selections[0]
                last_selection = selections[-1]
                # Git lines are 1-indexed; Sublime rows are 0-indexed.
                start_line = self.view.rowcol(first_selection.begin())[0] + 1
                end_line = self.view.rowcol(last_selection.end())[0] + 1

        default_name, default_remote_url = self.get_remotes().popitem(last=False)

        open_file_in_browser(
            fpath,
            default_remote_url,
            self.get_commit_hash_for_head(),
            start_line=start_line,
            end_line=end_line
        )

Prompt:
Fix regression where unable to open file on remote.

from sublime_plugin import TextCommand

from ...common.file_and_repo import FileAndRepo
from ..github import open_file_in_browser

class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo):

    """
    Open a new browser window to the web-version of the currently opened
    (or specified) file. If `preselect` is `True`, include the selected
    lines in the request.

    At present, this only supports github.com and GitHub enterprise.
    """

    def run(self, preselect=False, fpath=None):
        fpath = fpath or self.get_rel_path()
        start_line = None
        end_line = None

        if preselect:
            selections = self.view.sel()
            if len(selections) >= 1:
                first_selection = selections[0]
                last_selection = selections[-1]
                # Git lines are 1-indexed; Sublime rows are 0-indexed.
                start_line = self.view.rowcol(first_selection.begin())[0] + 1
                end_line = self.view.rowcol(last_selection.end())[0] + 1

        default_name, default_remote_url = self.get_remotes().popitem(last=False)

        open_file_in_browser(
            fpath,
            default_remote_url,
            self.get_commit_hash_for_head(),
            start_line=start_line,
            end_line=end_line
        )


from . import models
from django.conf import settings
from django.contrib.auth import hashers

def groups(request):
    return {
            'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
            'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
            }

def statistics(request):
    return {
            'gestalt_count': models.Gestalt.objects.exclude(user__password__startswith=hashers.UNUSABLE_PASSWORD_PREFIX).count,
            'group_count': models.Group.objects.count
            }

Exclude unusable users from stats

Exclude unusable users from stats

Response:
<REPLACE_OLD> settings

def <REPLACE_NEW> settings
from django.contrib.auth import hashers

def <REPLACE_END> <REPLACE_OLD> models.Gestalt.objects.count, <REPLACE_NEW> models.Gestalt.objects.exclude(user__password__startswith=hashers.UNUSABLE_PASSWORD_PREFIX).count, <REPLACE_END> <|endoftext|> from . import models
from django.conf import settings
from django.contrib.auth import hashers

def groups(request):
    return {
            'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
            'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
            }

def statistics(request):
    return {
            'gestalt_count': models.Gestalt.objects.exclude(user__password__startswith=hashers.UNUSABLE_PASSWORD_PREFIX).count,
            'group_count': models.Group.objects.count
            }

Prompt:
Exclude unusable users from stats

from . import models
from django.conf import settings

def groups(request):
    return {
            'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
            'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
            }

def statistics(request):
    return {
            'gestalt_count': models.Gestalt.objects.count,
            'group_count': models.Group.objects.count
            }


from runtests import Tester
import os.path
import sys

tester = Tester(os.path.abspath(__file__), "fake_spectra")

tester.main(sys.argv[1:])

Add import back to test script

Add import back to test script

Response:
<REPLACE_OLD> os.path

tester <REPLACE_NEW> os.path
import sys

tester <REPLACE_END> <|endoftext|> from runtests import Tester
import os.path
import sys

tester = Tester(os.path.abspath(__file__), "fake_spectra")

tester.main(sys.argv[1:])

Prompt:
Add import back to test script

from runtests import Tester
import os.path

tester = Tester(os.path.abspath(__file__), "fake_spectra")

tester.main(sys.argv[1:])


import pytest

from typing import Tuple

from .pells_equation import solve_pells_equation
from ..sqrt import is_square

PELLS_SOLUTIONS = [
    (
        2,
        [
            3,
            2
        ]
    ),
    (
        3,
        [
            2,
            1
        ]
    ),
    (
        5,
        [
            9,
            4
        ]
    ),
    (
        6,
        [
            5,
            2
        ]
    ),
    (
        7,
        [
            8,
            3
        ]
    ),
]

RANGE = [n for n in range(1, 20) if not is_square(n)]
DEPTH = 100

@pytest.mark.parametrize('n,expected_output', PELLS_SOLUTIONS)
def test_first_solution_pells_equation(n: int,
                                       expected_output: Tuple[int, int]) -> \
        None:
    assert tuple(expected_output) == next(solve_pells_equation(n))

@pytest.mark.parametrize('n', RANGE)
def test_further_solutions_pells_equation(n: int,
                                          number: int=DEPTH) -> None:
    solutions = solve_pells_equation(n)

    for (x, y), i in zip(solutions, range(number)):
        assert x ** 2 - n * y ** 2 == 1

Add testing for Pells equation

Add testing for Pells equation

Response:
<REPLACE_OLD>  <REPLACE_NEW> import pytest

from typing import Tuple

from .pells_equation import solve_pells_equation
from ..sqrt import is_square

PELLS_SOLUTIONS = [
    (
        2,
        [
            3,
            2
        ]
    ),
    (
        3,
        [
            2,
            1
        ]
    ),
    (
        5,
        [
            9,
            4
        ]
    ),
    (
        6,
        [
            5,
            2
        ]
    ),
    (
        7,
        [
            8,
            3
        ]
    ),
]

RANGE = [n for n in range(1, 20) if not is_square(n)]
DEPTH = 100

@pytest.mark.parametrize('n,expected_output', PELLS_SOLUTIONS)
def test_first_solution_pells_equation(n: int,
                                       expected_output: Tuple[int, int]) -> \
        None:
    assert tuple(expected_output) == next(solve_pells_equation(n))

@pytest.mark.parametrize('n', RANGE)
def test_further_solutions_pells_equation(n: int,
                                          number: int=DEPTH) -> None:
    solutions = solve_pells_equation(n)

    for (x, y), i in zip(solutions, range(number)):
        assert x ** 2 - n * y ** 2 == 1
 <REPLACE_END> <|endoftext|> import pytest

from typing import Tuple

from .pells_equation import solve_pells_equation
from ..sqrt import is_square

PELLS_SOLUTIONS = [
    (
        2,
        [
            3,
            2
        ]
    ),
    (
        3,
        [
            2,
            1
        ]
    ),
    (
        5,
        [
            9,
            4
        ]
    ),
    (
        6,
        [
            5,
            2
        ]
    ),
    (
        7,
        [
            8,
            3
        ]
    ),
]

RANGE = [n for n in range(1, 20) if not is_square(n)]
DEPTH = 100

@pytest.mark.parametrize('n,expected_output', PELLS_SOLUTIONS)
def test_first_solution_pells_equation(n: int,
                                       expected_output: Tuple[int, int]) -> \
        None:
    assert tuple(expected_output) == next(solve_pells_equation(n))

@pytest.mark.parametrize('n', RANGE)
def test_further_solutions_pells_equation(n: int,
                                          number: int=DEPTH) -> None:
    solutions = solve_pells_equation(n)

    for (x, y), i in zip(solutions, range(number)):
        assert x ** 2 - n * y ** 2 == 1

Prompt: Add testing for Pells equation


import binascii

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes

from knox.settings import knox_settings, CONSTANTS

sha = knox_settings.SECURE_HASH_ALGORITHM

def create_token_string():
    return binascii.hexlify(
        generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
    ).decode()

def create_salt_string():
    return binascii.hexlify(
        generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()

def hash_token(token, salt):
    '''
    Calculates the hash of a token and salt.
    input is unhexlified
    '''
    digest = hashes.Hash(sha(), backend=default_backend())
    digest.update(binascii.unhexlify(token))
    digest.update(binascii.unhexlify(salt))
    return binascii.hexlify(digest.finalize()).decode()

Response:
<REPLACE_OLD> OpenSSL.rand <REPLACE_NEW> os <REPLACE_END> <REPLACE_OLD> bytes <REPLACE_NEW> urandom <REPLACE_END> <|endoftext|> import binascii

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes

from knox.settings import knox_settings, CONSTANTS

sha = knox_settings.SECURE_HASH_ALGORITHM

def create_token_string():
    return binascii.hexlify(
        generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
    ).decode()

def create_salt_string():
    return binascii.hexlify(
        generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()

def hash_token(token, salt):
    '''
    Calculates the hash of a token and salt.
    input is unhexlified
    '''
    digest = hashes.Hash(sha(), backend=default_backend())
    digest.update(binascii.unhexlify(token))
    digest.update(binascii.unhexlify(salt))
    return binascii.hexlify(digest.finalize()).decode()

Prompt:
Use os.urandom instead of OpenSSL.rand.bytes

Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1
import binascii

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from OpenSSL.rand import bytes as generate_bytes

from knox.settings import knox_settings, CONSTANTS

sha = knox_settings.SECURE_HASH_ALGORITHM

def create_token_string():
    return binascii.hexlify(
        generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
    ).decode()

def create_salt_string():
    return binascii.hexlify(
        generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()

def hash_token(token, salt):
    '''
    Calculates the hash of a token and salt.
    input is unhexlified
    '''
    digest = hashes.Hash(sha(), backend=default_backend())
    digest.update(binascii.unhexlify(token))
    digest.update(binascii.unhexlify(salt))
    return binascii.hexlify(digest.finalize()).decode()


import math
import numpy
import pyaudio

def sine(frequency, length, rate):
    length = int(length * rate)
    factor = float(frequency) * (math.pi * 2) / rate
    return numpy.sin(numpy.arange(length) * factor)

def play_tone(stream, frequency=440, length=1, rate=44100):
    chunks = []
    chunks.append(sine(frequency, length, rate))

    chunk = numpy.concatenate(chunks) * 0.25

    stream.write(chunk.astype(numpy.float32).tostring())

if __name__ == '__main__':
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                    channels=1, rate=44100, output=1)

    play_tone(stream, frequency=750, length=10)

    stream.close()
    p.terminate()

Test codie to get sound duration right

Test codie to get sound duration right

Response:
<INSERT> import math
import numpy
import pyaudio

def sine(frequency, length, rate):
 <INSERT_END> <INSERT>   length = int(length * rate)
    factor = float(frequency) * (math.pi * 2) / rate
    return numpy.sin(numpy.arange(length) * factor)

def play_tone(stream, frequency=440, length=1, rate=44100):
    chunks = []
    chunks.append(sine(frequency, length, rate))

    chunk = numpy.concatenate(chunks) * 0.25

    stream.write(chunk.astype(numpy.float32).tostring())

if __name__ == '__main__':
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                    channels=1, rate=44100, output=1)

    play_tone(stream, frequency=750, length=10)

    stream.close()
    p.terminate()
 <INSERT_END> <|endoftext|> import math
import numpy
import pyaudio

def sine(frequency, length, rate):
    length = int(length * rate)
    factor = float(frequency) * (math.pi * 2) / rate
    return numpy.sin(numpy.arange(length) * factor)

def play_tone(stream, frequency=440, length=1, rate=44100):
    chunks = []
    chunks.append(sine(frequency, length, rate))

    chunk = numpy.concatenate(chunks) * 0.25

    stream.write(chunk.astype(numpy.float32).tostring())

if __name__ == '__main__':
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                    channels=1, rate=44100, output=1)

    play_tone(stream, frequency=750, length=10)

    stream.close()
    p.terminate()

Prompt: Test codie to get sound duration right


from django.contrib import admin

from registration.models import RegistrationProfile

class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'activation_key_expired')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)

Response:
<INSERT> raw_id_fields = ['user']
    <INSERT_END> <|endoftext|> from django.contrib import admin

from registration.models import RegistrationProfile

class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'activation_key_expired')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)

Prompt:
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.

from django.contrib import admin

from registration.models import RegistrationProfile

class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'activation_key_expired')
    search_fields = ('user__username', 'user__first_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)


"""suorganizer URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin

from organizer.views import homepage, tag_detail

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', homepage),
    url(r'^tag/(?P<slug>[\w\-]+)/$',
        tag_detail,
        ),
]

Create URL pattern for Tag Detail.

Response:
<REPLACE_OLD> homepage

urlpatterns <REPLACE_NEW> homepage, tag_detail

urlpatterns <REPLACE_END> <REPLACE_OLD> homepage),
]
 <REPLACE_NEW> homepage),
    url(r'^tag/(?P<slug>[\w\-]+)/$',
        tag_detail,
        ),
]
 <REPLACE_END> <|endoftext|> """suorganizer URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin

from organizer.views import homepage, tag_detail

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', homepage),
    url(r'^tag/(?P<slug>[\w\-]+)/$',
        tag_detail,
        ),
]

Prompt:
Ch05: Create URL pattern for Tag Detail.

"""suorganizer URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin

from organizer.views import homepage

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', homepage),
]


#!/usr/bin/env python

import base64
import rsa
import six

from st2common.runners.base_action import Action

class AwsDecryptPassworData(Action):

    def run(self, keyfile, password_data):
        # copied from:
        # https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122

        self.logger.debug("Decrypting password data using: %s", keyfile)
        value = password_data

        if not value:
            return ''

        # Hack because somewhere in the Mistral parameter "publish" pipeline, we
        # strip trailing and leading whitespace from a string which results in
        # an invalid base64 string
        if not value.startswith('\r\n'):
            value = '\r\n' + value

        if not value.endswith('\r\n'):
            value = value + '\r\n'

        value = base64.b64decode(value)

        try:
            with open(keyfile) as pk_file:
                pk_contents = pk_file.read()
                private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                value = rsa.decrypt(value, private_key)
                return value.decode('utf-8')
        except Exception:
            msg = ('Unable to decrypt password data using '
                   'provided private key file: {}').format(keyfile)
            self.logger.debug(msg, exc_info=True)
            raise ValueError(msg)

Response:
<REPLACE_OLD> password_data
 <REPLACE_NEW> password_data

 <REPLACE_END> <INSERT>        # Hack because somewhere in the Mistral parameter "publish" pipeline, we
        # strip trailing and leading whitespace from a string which results in
        # an invalid base64 string
        if not value.startswith('\r\n'):
            value = '\r\n' + value

        if not value.endswith('\r\n'):
            value = value + '\r\n'

        value = base64.b64decode(value)

 <INSERT_END> <DELETE>                value = base64.b64decode(value)
 <DELETE_END> <|endoftext|> #!/usr/bin/env python

import base64
import rsa
import six

from st2common.runners.base_action import Action

class AwsDecryptPassworData(Action):

    def run(self, keyfile, password_data):
        # copied from:
        # https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122

        self.logger.debug("Decrypting password data using: %s", keyfile)
        value = password_data

        if not value:
            return ''

        # Hack because somewhere in the Mistral parameter "publish" pipeline, we
        # strip trailing and leading whitespace from a string which results in
        # an invalid base64 string
        if not value.startswith('\r\n'):
            value = '\r\n' + value

        if not value.endswith('\r\n'):
            value = value + '\r\n'

        value = base64.b64decode(value)

        try:
            with open(keyfile) as pk_file:
                pk_contents = pk_file.read()
                private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                value = rsa.decrypt(value, private_key)
                return value.decode('utf-8')
        except Exception:
            msg = ('Unable to decrypt password data using '
                   'provided private key file: {}').format(keyfile)
            self.logger.debug(msg, exc_info=True)
            raise ValueError(msg)

Prompt:
Add a workaround since somewhere in the Mistral "publish variable"
pipeline, trealing and leading whitespace is removed.

#!/usr/bin/env python

import base64
import rsa
import six

from st2common.runners.base_action import Action

class AwsDecryptPassworData(Action):

    def run(self, keyfile, password_data):
        # copied from:
        # https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122

        self.logger.debug("Decrypting password data using: %s", keyfile)
        value = password_data
        if not value:
            return ''

        try:
            with open(keyfile) as pk_file:
                pk_contents = pk_file.read()
                private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                value = base64.b64decode(value)
                value = rsa.decrypt(value, private_key)
                return value.decode('utf-8')
        except Exception:
            msg = ('Unable to decrypt password data using '
                   'provided private key file: {}').format(keyfile)
            self.logger.debug(msg, exc_info=True)
            raise ValueError(msg)


"""Collection of HTTP helpers."""

from functools import partial, wraps
from inspect import iscoroutine

from aiohttp.web import json_response

def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
    """Turn dict output of an HTTP handler into JSON response.

    Decorates aiohttp request handlers.
    """
    if orig_method is None:
        return partial(async_json_out, status=200, content_type='application/json', **kwargs)

    @wraps(orig_method)
    async def wrapper(*args, **kwargs):
        dict_resp = orig_method(*args, **kwargs)

        if iscoroutine(dict_resp):
            dict_resp = await dict_resp

        return json_response(
            dict_resp,
            status=status,
            content_type=content_type,
            **kwargs
        )
    return wrapper

Response:
<INSERT> status=200, <INSERT_END> <INSERT> status=200, <INSERT_END> <INSERT> status=status,
            <INSERT_END> <|endoftext|> """Collection of HTTP helpers."""

from functools import partial, wraps
from inspect import iscoroutine

from aiohttp.web import json_response

def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
    """Turn dict output of an HTTP handler into JSON response.

    Decorates aiohttp request handlers.
    """
    if orig_method is None:
        return partial(async_json_out, status=200, content_type='application/json', **kwargs)

    @wraps(orig_method)
    async def wrapper(*args, **kwargs):
        dict_resp = orig_method(*args, **kwargs)

        if iscoroutine(dict_resp):
            dict_resp = await dict_resp

        return json_response(
            dict_resp,
            status=status,
            content_type=content_type,
            **kwargs
        )
    return wrapper

Prompt:
Add default status=200 to async_json_out decorator

"""Collection of HTTP helpers."""

from functools import partial, wraps
from inspect import iscoroutine

from aiohttp.web import json_response

def async_json_out(orig_method=None, *, content_type='application/json', **kwargs):
    """Turn dict output of an HTTP handler into JSON response.

    Decorates aiohttp request handlers.
    """
    if orig_method is None:
        return partial(async_json_out, content_type='application/json', **kwargs)

    @wraps(orig_method)
    async def wrapper(*args, **kwargs):
        dict_resp = orig_method(*args, **kwargs)

        if iscoroutine(dict_resp):
            dict_resp = await dict_resp

        return json_response(
            dict_resp,
            content_type=content_type,
            **kwargs
        )
    return wrapper


from nameko.rpc import rpc, RpcProxy

class ScoreService(object):
    name = 'score_service'

    player_rpc = RpcProxy('players_service')

    @rpc
    def leaderboard(self):
        players = self.player_rpc.get_players()
        sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
        return [(p.name, p.score) for p in players]

    @rpc
    def update_player_score(self, player_id, score):
        player = self.player_rpc.get_player(player_id)
        player.add_score(score)

Add method to update a player's score

Add method to update a player's score

Response:
<REPLACE_OLD> player_service <REPLACE_NEW> player_rpc <REPLACE_END> <REPLACE_OLD> self.player_service.get_players()
 <REPLACE_NEW> self.player_rpc.get_players()
        sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
 <REPLACE_END> <REPLACE_OLD> sorted(players, key=lambda player: player.score, reverse=True)
 <REPLACE_NEW> [(p.name, p.score) for p in players]

    @rpc
    def update_player_score(self, player_id, score):
        player = self.player_rpc.get_player(player_id)
        player.add_score(score)
 <REPLACE_END> <|endoftext|> from nameko.rpc import rpc, RpcProxy

class ScoreService(object):
    name = 'score_service'

    player_rpc = RpcProxy('players_service')

    @rpc
    def leaderboard(self):
        players = self.player_rpc.get_players()
        sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
        return [(p.name, p.score) for p in players]

    @rpc
    def update_player_score(self, player_id, score):
        player = self.player_rpc.get_player(player_id)
        player.add_score(score)

Prompt:
Add method to update a player's score

from nameko.rpc import rpc, RpcProxy

class ScoreService(object):
    name = 'score_service'

    player_service = RpcProxy('players_service')

    @rpc
    def leaderboard(self):
        players = self.player_service.get_players()
        return sorted(players, key=lambda player: player.score, reverse=True)


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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest

# To test this module:
# python -m unittest -v nested

def string_maxlen(txt,max_len=12):
    n = len(txt)
    if n <= max_len:
        return txt
    elif n > max_len-3:
        return txt[:(max_len-3)] + '...'

# python -m unittest -v nested.TestStringMaxLength
class TestStringMaxLength(unittest.TestCase):
    def test_short_strings(self):
        self.assertEqual(string_maxlen('abcdefghij'),     'abcdefghij')
        self.assertEqual(string_maxlen('abcdefghijk'),    'abcdefghijk')
        self.assertEqual(string_maxlen('abcdefghijkl'),   'abcdefghijkl')

    def test_long_strings(self):
        self.assertEqual(string_maxlen('abcdefghijklm'),  'abcdefghi...')
        self.assertEqual(string_maxlen('abcdefghijklmn'), 'abcdefghi...')

def print_structure(elmt,level=0,max_level=5):
    txt=''
    if level > max_level:
        return txt

    whitespace = " " * (level * 2)
    if isinstance(elmt, (dict)) is True:
        for k in elmt.keys():
            if type(elmt[k])==int:
                txt += whitespace + "+'{0}': {1}\n".format(k,elmt[k])
            elif type(elmt[k])==str:
                my_str=elmt[k][:40]
                txt += whitespace + "+'{0}': '{1}'\n".format(k,my_str)
            else:
                txt += whitespace + "+'{0}': {1}\n".format(k,type(elmt[k]))
                txt += print_structure(elmt[k],level+1,max_level=max_level)
    elif isinstance(elmt, (list)) is True:
        txt += whitespace + "+[list]\n"
        if len(elmt) > 0:
            txt += print_structure(elmt[0],level+1,max_level=max_level)
    else:
        pass
    return txt

# python -m unittest -v nested.TestPrintStructure
class TestPrintStructure(unittest.TestCase):
    def test_dict_int(self):
        d = {'integer': 123}
        self.assertEqual(print_structure(d),"+'integer': 123\n")

    def test_dict_string(self):
        d = {'string': 'abc'}
        self.assertEqual(print_structure(d),"+'string': 'abc'\n")

    def test_dict_list(self):
        d = {'list': [1,2,3]}
        self.assertEqual(print_structure(d),"+'list': <class 'list'>\n  +[list]\n")

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

Add subroutine to print a dictionary tree

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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest

# To test this module:
# python -m unittest -v nested

def string_maxlen(txt,max_len=12):
    n = len(txt)
    if n <= max_len:
        return txt
    elif n > max_len-3:
        return txt[:(max_len-3)] + '...'

# python -m unittest -v nested.TestStringMaxLength
class TestStringMaxLength(unittest.TestCase):
    def test_short_strings(self):
        self.assertEqual(string_maxlen('abcdefghij'),     'abcdefghij')
        self.assertEqual(string_maxlen('abcdefghijk'),    'abcdefghijk')
        self.assertEqual(string_maxlen('abcdefghijkl'),   'abcdefghijkl')

    def test_long_strings(self):
        self.assertEqual(string_maxlen('abcdefghijklm'),  'abcdefghi...')
        self.assertEqual(string_maxlen('abcdefghijklmn'), 'abcdefghi...')

def print_structure(elmt,level=0,max_level=5):
    txt=''
    if level > max_level:
        return txt

    whitespace = " " * (level * 2)
    if isinstance(elmt, (dict)) is True:
        for k in elmt.keys():
            if type(elmt[k])==int:
                txt += whitespace + "+'{0}': {1}\n".format(k,elmt[k])
            elif type(elmt[k])==str:
                my_str=elmt[k][:40]
                txt += whitespace + "+'{0}': '{1}'\n".format(k,my_str)
            else:
                txt += whitespace + "+'{0}': {1}\n".format(k,type(elmt[k]))
                txt += print_structure(elmt[k],level+1,max_level=max_level)
    elif isinstance(elmt, (list)) is True:
        txt += whitespace + "+[list]\n"
        if len(elmt) > 0:
            txt += print_structure(elmt[0],level+1,max_level=max_level)
    else:
        pass
    return txt

# python -m unittest -v nested.TestPrintStructure
class TestPrintStructure(unittest.TestCase):
    def test_dict_int(self):
        d = {'integer': 123}
        self.assertEqual(print_structure(d),"+'integer': 123\n")

    def test_dict_string(self):
        d = {'string': 'abc'}
        self.assertEqual(print_structure(d),"+'string': 'abc'\n")

    def test_dict_list(self):
        d = {'list': [1,2,3]}
        self.assertEqual(print_structure(d),"+'list': <class 'list'>\n  +[list]\n")

if __name__ == "__main__":
    unittest.main()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: UTF-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest

# To test this module:
# python -m unittest -v nested

def string_maxlen(txt,max_len=12):
    n = len(txt)
    if n <= max_len:
        return txt
    elif n > max_len-3:
        return txt[:(max_len-3)] + '...'

# python -m unittest -v nested.TestStringMaxLength
class TestStringMaxLength(unittest.TestCase):
    def test_short_strings(self):
        self.assertEqual(string_maxlen('abcdefghij'),     'abcdefghij')
        self.assertEqual(string_maxlen('abcdefghijk'),    'abcdefghijk')
        self.assertEqual(string_maxlen('abcdefghijkl'),   'abcdefghijkl')

    def test_long_strings(self):
        self.assertEqual(string_maxlen('abcdefghijklm'),  'abcdefghi...')
        self.assertEqual(string_maxlen('abcdefghijklmn'), 'abcdefghi...')

def print_structure(elmt,level=0,max_level=5):
    txt=''
    if level > max_level:
        return txt

    whitespace = " " * (level * 2)
    if isinstance(elmt, (dict)) is True:
        for k in elmt.keys():
            if type(elmt[k])==int:
                txt += whitespace + "+'{0}': {1}\n".format(k,elmt[k])
            elif type(elmt[k])==str:
                my_str=elmt[k][:40]
                txt += whitespace + "+'{0}': '{1}'\n".format(k,my_str)
            else:
                txt += whitespace + "+'{0}': {1}\n".format(k,type(elmt[k]))
                txt += print_structure(elmt[k],level+1,max_level=max_level)
    elif isinstance(elmt, (list)) is True:
        txt += whitespace + "+[list]\n"
        if len(elmt) > 0:
            txt += print_structure(elmt[0],level+1,max_level=max_level)
    else:
        pass
    return txt

# python -m unittest -v nested.TestPrintStructure
class TestPrintStructure(unittest.TestCase):
    def test_dict_int(self):
        d = {'integer': 123}
        self.assertEqual(print_structure(d),"+'integer': 123\n")

    def test_dict_string(self):
        d = {'string': 'abc'}
        self.assertEqual(print_structure(d),"+'string': 'abc'\n")

    def test_dict_list(self):
        d = {'list': [1,2,3]}
        self.assertEqual(print_structure(d),"+'list': <class 'list'>\n  +[list]\n")

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

Prompt: Add subroutine to print a dictionary tree


import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-nexmo',
    version='1.0.1',
    packages=['nexmo'],
    include_package_data=True,
    license='WTFPL',
    description='A simple Django app to send text messages using the Nexmo api.',
    long_description=README,
    url='https://github.com/thibault/django-nexmo',
    author='Thibault Jouannic',
    author_email='thibault@miximum.fr',
    setup_requires=('setuptools'),
    install_requires=[
        'libnexmo',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Add libnexmo as a dependency

Add libnexmo as a dependency

Response:
<REPLACE_OLD> requires=(),
 <REPLACE_NEW> install_requires=[
        'libnexmo',
    ],
 <REPLACE_END> <|endoftext|> import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-nexmo',
    version='1.0.1',
    packages=['nexmo'],
    include_package_data=True,
    license='WTFPL',
    description='A simple Django app to send text messages using the Nexmo api.',
    long_description=README,
    url='https://github.com/thibault/django-nexmo',
    author='Thibault Jouannic',
    author_email='thibault@miximum.fr',
    setup_requires=('setuptools'),
    install_requires=[
        'libnexmo',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Prompt:
Add libnexmo as a dependency

import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-nexmo',
    version='1.0.1',
    packages=['nexmo'],
    include_package_data=True,
    license='WTFPL',
    description='A simple Django app to send text messages using the Nexmo api.',
    long_description=README,
    url='https://github.com/thibault/django-nexmo',
    author='Thibault Jouannic',
    author_email='thibault@miximum.fr',
    setup_requires=('setuptools'),
    requires=(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requires = [
    'requests',
    'rauth'
]

setup(
    name='fatsecret',
    version='0.2.1',
    description='Python wrapper for FatSecret REST API',
    url='github.com/walexnelson/pyfatsecret',
    license='MIT',
    author='Alex Nelson',
    author_email='w.alexnelson@gmail.com',
    install_requires=requires,
    packages=["fatsecret"],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ]
)

Use packaging instead of a module

Use packaging instead of a module

Response:
<REPLACE_OLD> py_modules=("fatsecret",),
 <REPLACE_NEW> packages=["fatsecret"],
 <REPLACE_END> <|endoftext|> try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requires = [
    'requests',
    'rauth'
]

setup(
    name='fatsecret',
    version='0.2.1',
    description='Python wrapper for FatSecret REST API',
    url='github.com/walexnelson/pyfatsecret',
    license='MIT',
    author='Alex Nelson',
    author_email='w.alexnelson@gmail.com',
    install_requires=requires,
    packages=["fatsecret"],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ]
)

Prompt:
Use packaging instead of a module
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requires = [
    'requests',
    'rauth'
]

setup(
    name='fatsecret',
    version='0.2.1',
    description='Python wrapper for FatSecret REST API',
    url='github.com/walexnelson/pyfatsecret',
    license='MIT',
    author='Alex Nelson',
    author_email='w.alexnelson@gmail.com',
    install_requires=requires,
    py_modules=("fatsecret",),
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ]
)


""" Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse

def create_output_timing(f_out, args):
    print(
        """
source {util_tcl}
write_timing_info timing_{name}.json5

report_timing_summary
""".format(name=args.name, util_tcl=args.util_tcl),
        file=f_out
    )

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--name', required=True)
    parser.add_argument('--util_tcl', required=True)
    parser.add_argument('--output_tcl', required=True)

    args = parser.parse_args()
    with open(args.output_tcl, 'w') as f:
        create_output_timing(f, args)

if __name__ == "__main__":
    main()

Response:
<REPLACE_OLD> create_runme(f_out, <REPLACE_NEW> create_output_timing(f_out, <REPLACE_END> <REPLACE_OLD> """
report_timing_summary

source <REPLACE_NEW> """
source <REPLACE_END> <REPLACE_OLD> timing_{name}.json5
""".format(name=args.name, <REPLACE_NEW> timing_{name}.json5

report_timing_summary
""".format(name=args.name, <REPLACE_END> <REPLACE_OLD> create_runme(f, <REPLACE_NEW> create_output_timing(f, <REPLACE_END> <|endoftext|> """ Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse

def create_output_timing(f_out, args):
    print(
        """
source {util_tcl}
write_timing_info timing_{name}.json5

report_timing_summary
""".format(name=args.name, util_tcl=args.util_tcl),
        file=f_out
    )

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--name', required=True)
    parser.add_argument('--util_tcl', required=True)
    parser.add_argument('--output_tcl', required=True)

    args = parser.parse_args()
    with open(args.output_tcl, 'w') as f:
        create_output_timing(f, args)

if __name__ == "__main__":
    main()

Prompt:
Correct function name and put report_timing_summary at end of script.

Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>

""" Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse

def create_runme(f_out, args):
    print(
        """
report_timing_summary

source {util_tcl}
write_timing_info timing_{name}.json5
""".format(name=args.name, util_tcl=args.util_tcl),
        file=f_out
    )

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--name', required=True)
    parser.add_argument('--util_tcl', required=True)
    parser.add_argument('--output_tcl', required=True)

    args = parser.parse_args()
    with open(args.output_tcl, 'w') as f:
        create_runme(f, args)

if __name__ == "__main__":
    main()


def sieve(n):
    if n < 2:
        return []
    not_prime = set()
    prime = [2]
    for i in range(3, n+1, 2):
        if i not in not_prime:
            prime.append(i)
            not_prime.update(range(i*i, n, i))
    return prime

Response:
<DELETE>    return list(primes(n))

def primes(n):
 <DELETE_END> <REPLACE_OLD> raise StopIteration
    yield 2
 <REPLACE_NEW> return []
 <REPLACE_END> <INSERT>    prime = [2]
 <INSERT_END> <REPLACE_OLD> yield i
 <REPLACE_NEW> prime.append(i)
     <REPLACE_END> <INSERT>    return prime
 <INSERT_END> <|endoftext|> def sieve(n):
    if n < 2:
        return []
    not_prime = set()
    prime = [2]
    for i in range(3, n+1, 2):
        if i not in not_prime:
            prime.append(i)
            not_prime.update(range(i*i, n, i))
    return prime

Prompt:
Switch to more optimal non-generator solution

def sieve(n):
    return list(primes(n))

def primes(n):
    if n < 2:
        raise StopIteration
    yield 2
    not_prime = set()
    for i in range(3, n+1, 2):
        if i not in not_prime:
            yield i
        not_prime.update(range(i*i, n, i))


import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')

# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""

    result = []

    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)

    return unicode(delim.join(result))

Response:
<REPLACE_OLD> !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')

# <REPLACE_NEW> !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')

# <REPLACE_END> <|endoftext|> import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')

# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""

    result = []

    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)

    return unicode(delim.join(result))

Prompt:
Change ":" in titles to "-" for better SEO

import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')

# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""

    result = []

    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)

    return unicode(delim.join(result))


from Cura.View.View import View

class MeshView(View):
    def __init__(self):
        super(MeshView, self).__init__()

    def render(self):
        scene = self.getController().getScene()
        renderer = self.getRenderer()

        self._renderObject(scene.getRoot(), renderer)

    def _renderObject(self, object, renderer):
        if not object.render():
            if object.getMeshData():
                renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())

        for child in object.getChildren():
            self._renderObject(child, renderer)

Allow SceneObjects to render themselves

Allow SceneObjects to render themselves

Response:
<INSERT> not object.render():
            if <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> from Cura.View.View import View

class MeshView(View):
    def __init__(self):
        super(MeshView, self).__init__()

    def render(self):
        scene = self.getController().getScene()
        renderer = self.getRenderer()

        self._renderObject(scene.getRoot(), renderer)

    def _renderObject(self, object, renderer):
        if not object.render():
            if object.getMeshData():
                renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())

        for child in object.getChildren():
            self._renderObject(child, renderer)

Prompt:
Allow SceneObjects to render themselves

from Cura.View.View import View

class MeshView(View):
    def __init__(self):
        super(MeshView, self).__init__()

    def render(self):
        scene = self.getController().getScene()
        renderer = self.getRenderer()

        self._renderObject(scene.getRoot(), renderer)

    def _renderObject(self, object, renderer):
        if object.getMeshData():
            renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())

        for child in object.getChildren():
            self._renderObject(child, renderer)


from __future__ import unicode_literals

import sys

from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView

from django.contrib import admin

from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    url(r'^parties/', include('parties.urls')),
    url(r'^', include('candidates.urls')),
    url(r'^tasks/', include('tasks.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^upload_document/', include('official_documents.urls')),
    url(r'^results/', include('results.urls')),
    url(r'^robots\.txt$', TemplateView.as_view(
        template_name='robots.txt',
        content_type='text/plain')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]

if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False):
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Response:
<REPLACE_OLD> settings.RUNNING_TESTS:
 <REPLACE_NEW> getattr(settings, 'RUNNING_TESTS', False):
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

import sys

from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView

from django.contrib import admin

from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    url(r'^parties/', include('parties.urls')),
    url(r'^', include('candidates.urls')),
    url(r'^tasks/', include('tasks.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^upload_document/', include('official_documents.urls')),
    url(r'^results/', include('results.urls')),
    url(r'^robots\.txt$', TemplateView.as_view(
        template_name='robots.txt',
        content_type='text/plain')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]

if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False):
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Prompt:
Use getattr in case setting doesn't exist

from __future__ import unicode_literals

import sys

from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView

from django.contrib import admin

from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    url(r'^parties/', include('parties.urls')),
    url(r'^', include('candidates.urls')),
    url(r'^tasks/', include('tasks.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^upload_document/', include('official_documents.urls')),
    url(r'^results/', include('results.urls')),
    url(r'^robots\.txt$', TemplateView.as_view(
        template_name='robots.txt',
        content_type='text/plain')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]

if settings.DEBUG or settings.RUNNING_TESTS:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from rest_framework import status
from rest_framework.exceptions import APIException

def json_api_exception_handler(exc, context):
    """ Custom exception handler that returns errors object as an array """

    # Import inside method to avoid errors when the OSF is loaded without Django
    from rest_framework.views import exception_handler
    response = exception_handler(exc, context)

    # Error objects may have the following members. Title removed to avoid clash with node "title" errors.
    top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
    errors = []

    if response:
        message = response.data
        if isinstance(message, dict):
            for key, value in message.iteritems():
                if key in top_level_error_keys:
                    errors.append({key: value})
                else:
                    if isinstance(value, list):
                        for reason in value:
                            errors.append({'detail': reason, 'meta': {'field': key}})
                    else:
                        errors.append({'detail': value, 'meta': {'field': key}})
        elif isinstance(message, (list, tuple)):
            for error in message:
                errors.append({'detail': error})
        else:
            errors.append({'detail': message})

        response.data = {'errors': errors}

    return response

# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
    status_code = status.HTTP_410_GONE
    default_detail = ('The requested resource is no longer available.')

Response:
<REPLACE_OLD> value = value[0]
 <REPLACE_NEW> for reason in value:
                            errors.append({'detail': reason, 'meta': {'field': key}})
                    else:
     <REPLACE_END> <|endoftext|>
from rest_framework import status
from rest_framework.exceptions import APIException

def json_api_exception_handler(exc, context):
    """ Custom exception handler that returns errors object as an array """

    # Import inside method to avoid errors when the OSF is loaded without Django
    from rest_framework.views import exception_handler
    response = exception_handler(exc, context)

    # Error objects may have the following members. Title removed to avoid clash with node "title" errors.
    top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
    errors = []

    if response:
        message = response.data
        if isinstance(message, dict):
            for key, value in message.iteritems():
                if key in top_level_error_keys:
                    errors.append({key: value})
                else:
                    if isinstance(value, list):
                        for reason in value:
                            errors.append({'detail': reason, 'meta': {'field': key}})
                    else:
                        errors.append({'detail': value, 'meta': {'field': key}})
        elif isinstance(message, (list, tuple)):
            for error in message:
                errors.append({'detail': error})
        else:
            errors.append({'detail': message})

        response.data = {'errors': errors}

    return response

# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
    status_code = status.HTTP_410_GONE
    default_detail = ('The requested resource is no longer available.')

Prompt:
Handle cases where there are multiple values for a field.

from rest_framework import status
from rest_framework.exceptions import APIException

def json_api_exception_handler(exc, context):
    """ Custom exception handler that returns errors object as an array """

    # Import inside method to avoid errors when the OSF is loaded without Django
    from rest_framework.views import exception_handler
    response = exception_handler(exc, context)

    # Error objects may have the following members. Title removed to avoid clash with node "title" errors.
    top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
    errors = []

    if response:
        message = response.data
        if isinstance(message, dict):
            for key, value in message.iteritems():
                if key in top_level_error_keys:
                    errors.append({key: value})
                else:
                    if isinstance(value, list):
                        value = value[0]
                    errors.append({'detail': value, 'meta': {'field': key}})
        elif isinstance(message, (list, tuple)):
            for error in message:
                errors.append({'detail': error})
        else:
            errors.append({'detail': message})

        response.data = {'errors': errors}

    return response

# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
    status_code = status.HTTP_410_GONE
    default_detail = ('The requested resource is no longer available.')


from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider

IDENTIFIER = "Terminal"

class Provider(OutputProvider):
    def process_data(self, movie_data):
        movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data)
        movie_data = sorted(movie_data, key=lambda data: (data.get("filmtipset_my_grade", 0), data.get("imdb_rating", 0)), reverse=True)
        return movie_data

    def output(self, movie_data):
        movie_data = self.process_data(movie_data)

        print()
        for data in movie_data[:10]:
            print("%s (Filmtipset: %s, IMDB: %s)" % (
                data["title"],
                data.get("filmtipset_my_grade", "-"),
                data.get("imdb_rating", "-"),
            ))

            print("  [Genre: %s, Country: %s, Year: %s]" % (
                ", ".join(data.get("genre", "-")),
                data.get("country", "-"),
                data.get("year", "-"),
            ))

            plot = data.get("plot", None)
            if plot:
                text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent="  ", subsequent_indent="  ")
                print("\n".join(text))
            print()

Response:
<REPLACE_OLD> data.get("filmtipset_my_grade", <REPLACE_NEW> (data.get("filmtipset_my_grade", <REPLACE_END> <INSERT> data.get("imdb_rating", 0)), <INSERT_END> <|endoftext|> from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider

IDENTIFIER = "Terminal"

class Provider(OutputProvider):
    def process_data(self, movie_data):
        movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data)
        movie_data = sorted(movie_data, key=lambda data: (data.get("filmtipset_my_grade", 0), data.get("imdb_rating", 0)), reverse=True)
        return movie_data

    def output(self, movie_data):
        movie_data = self.process_data(movie_data)

        print()
        for data in movie_data[:10]:
            print("%s (Filmtipset: %s, IMDB: %s)" % (
                data["title"],
                data.get("filmtipset_my_grade", "-"),
                data.get("imdb_rating", "-"),
            ))

            print("  [Genre: %s, Country: %s, Year: %s]" % (
                ", ".join(data.get("genre", "-")),
                data.get("country", "-"),
                data.get("year", "-"),
            ))

            plot = data.get("plot", None)
            if plot:
                text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent="  ", subsequent_indent="  ")
                print("\n".join(text))
            print()

Prompt:
Sort on imdb rating if filmtipset ratings are the same.

from __future__ import print_function
import textwrap
from providers.output.provider import OutputProvider

IDENTIFIER = "Terminal"

class Provider(OutputProvider):
    def process_data(self, movie_data):
        movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data)
        movie_data = sorted(movie_data, key=lambda data: data.get("filmtipset_my_grade", 0), reverse=True)
        return movie_data

    def output(self, movie_data):
        movie_data = self.process_data(movie_data)

        print()
        for data in movie_data[:10]:
            print("%s (Filmtipset: %s, IMDB: %s)" % (
                data["title"],
                data.get("filmtipset_my_grade", "-"),
                data.get("imdb_rating", "-"),
            ))

            print("  [Genre: %s, Country: %s, Year: %s]" % (
                ", ".join(data.get("genre", "-")),
                data.get("country", "-"),
                data.get("year", "-"),
            ))

            plot = data.get("plot", None)
            if plot:
                text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent="  ", subsequent_indent="  ")
                print("\n".join(text))
            print()