# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.

from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean

class Subscription(AWSProperty):
    props = {
        'Endpoint': (basestring, True),
        'Protocol': (basestring, True),
    }

class SubscriptionResource(AWSObject):
    resource_type = "AWS::SNS::Subscription"

    props = {
        'DeliveryPolicy': (dict, False),
        'Endpoint': (basestring, False),
        'FilterPolicy': (dict, False),
        'Protocol': (basestring, True),
        'RawMessageDelivery': (boolean, False),
        'Region': (basestring, False),
        'TopicArn': (basestring, True),
    }

class TopicPolicy(AWSObject):
    resource_type = "AWS::SNS::TopicPolicy"

    props = {
        'PolicyDocument': (policytypes, True),
        'Topics': (list, True),
    }

class Topic(AWSObject):
    resource_type = "AWS::SNS::Topic"

    props = {
        'DisplayName': (basestring, False),
        'KmsMasterKeyId': (basestring, False),
        'Subscription': ([Subscription], False),
        'Tags': (Tags, False),
        'TopicName': (basestring, False),
    }

Response:
<REPLACE_OLD> AWSProperty
from <REPLACE_NEW> AWSProperty, Tags
from <REPLACE_END> <INSERT> 'Tags': (Tags, False),
        <INSERT_END> <|endoftext|> # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.

from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean

class Subscription(AWSProperty):
    props = {
        'Endpoint': (basestring, True),
        'Protocol': (basestring, True),
    }

class SubscriptionResource(AWSObject):
    resource_type = "AWS::SNS::Subscription"

    props = {
        'DeliveryPolicy': (dict, False),
        'Endpoint': (basestring, False),
        'FilterPolicy': (dict, False),
        'Protocol': (basestring, True),
        'RawMessageDelivery': (boolean, False),
        'Region': (basestring, False),
        'TopicArn': (basestring, True),
    }

class TopicPolicy(AWSObject):
    resource_type = "AWS::SNS::TopicPolicy"

    props = {
        'PolicyDocument': (policytypes, True),
        'Topics': (list, True),
    }

class Topic(AWSObject):
    resource_type = "AWS::SNS::Topic"

    props = {
        'DisplayName': (basestring, False),
        'KmsMasterKeyId': (basestring, False),
        'Subscription': ([Subscription], False),
        'Tags': (Tags, False),
        'TopicName': (basestring, False),
    }

Prompt:
Add Tags to SNS::Topic per 2019-11-31 changes

# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.

from . import AWSObject, AWSProperty
from .compat import policytypes
from .validators import boolean

class Subscription(AWSProperty):
    props = {
        'Endpoint': (basestring, True),
        'Protocol': (basestring, True),
    }

class SubscriptionResource(AWSObject):
    resource_type = "AWS::SNS::Subscription"

    props = {
        'DeliveryPolicy': (dict, False),
        'Endpoint': (basestring, False),
        'FilterPolicy': (dict, False),
        'Protocol': (basestring, True),
        'RawMessageDelivery': (boolean, False),
        'Region': (basestring, False),
        'TopicArn': (basestring, True),
    }

class TopicPolicy(AWSObject):
    resource_type = "AWS::SNS::TopicPolicy"

    props = {
        'PolicyDocument': (policytypes, True),
        'Topics': (list, True),
    }

class Topic(AWSObject):
    resource_type = "AWS::SNS::Topic"

    props = {
        'DisplayName': (basestring, False),
        'KmsMasterKeyId': (basestring, False),
        'Subscription': ([Subscription], False),
        'TopicName': (basestring, False),
    }


#!/usr/bin/env python
"""Script to collect coverage information on ofStateManager"""

import os
import sys
import inspect
import coverage
import subprocess

def main():
	"""Main function"""
	arguments = ''
	if len(sys.argv) > 1:
		arguments = ' '.join(sys.argv[1:])
	testdir = os.path.abspath(os.path.dirname(
			inspect.getfile(inspect.currentframe())))
	script_path = os.path.join(testdir, '..', 'ofStateManager.py')

	os.environ['COVERAGE_PROCESS_START'] = os.path.join(testdir, '.coveragerc')
	os.environ['COVERAGE_FILE'] = os.path.join(testdir, '.coverage')

	subprocess.call('coverage erase', shell=True, cwd=testdir)
	subprocess.call('coverage run -m py.test ' + arguments, shell=True, cwd=testdir)
	subprocess.call('coverage combine', shell=True, cwd=testdir)
	subprocess.call('coverage html -d ' + os.path.join(testdir, 'htmlcov') +
					' --include=' + script_path, shell=True, cwd=testdir)
	subprocess.call('coverage report --include=' + script_path,
					shell=True, cwd=testdir)

if __name__ == '__main__':
	main()

Response:
<REPLACE_OLD> os.path.abspath(os.path.dirname(
			inspect.getfile(inspect.currentframe())))
	os.environ['COVERAGE_PROCESS_START'] <REPLACE_NEW> os.path.abspath(os.path.dirname(
			inspect.getfile(inspect.currentframe())))
	script_path = os.path.join(testdir, '..', 'ofStateManager.py')

	os.environ['COVERAGE_PROCESS_START'] <REPLACE_END> <REPLACE_OLD> '.coverage')
	cov = coverage.coverage(source=os.path.join(testdir, '..'),
		include=os.path.join(testdir, '..', 'ofStateManager.py'))
	cov.erase()
	subprocess.call('coverage <REPLACE_NEW> '.coverage')

	subprocess.call('coverage erase', shell=True, cwd=testdir)
	subprocess.call('coverage <REPLACE_END> <REPLACE_OLD> shell=True,
					cwd=testdir)
	cov.combine()
	cov.html_report(directory=os.path.join(testdir, 'htmlcov'))
	cov.report(show_missing=False)

if <REPLACE_NEW> shell=True, cwd=testdir)
	subprocess.call('coverage combine', shell=True, cwd=testdir)
	subprocess.call('coverage html -d ' + os.path.join(testdir, 'htmlcov') +
					' --include=' + script_path, shell=True, cwd=testdir)
	subprocess.call('coverage report --include=' + script_path,
					shell=True, cwd=testdir)

if <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""Script to collect coverage information on ofStateManager"""

import os
import sys
import inspect
import coverage
import subprocess

def main():
	"""Main function"""
	arguments = ''
	if len(sys.argv) > 1:
		arguments = ' '.join(sys.argv[1:])
	testdir = os.path.abspath(os.path.dirname(
			inspect.getfile(inspect.currentframe())))
	script_path = os.path.join(testdir, '..', 'ofStateManager.py')

	os.environ['COVERAGE_PROCESS_START'] = os.path.join(testdir, '.coveragerc')
	os.environ['COVERAGE_FILE'] = os.path.join(testdir, '.coverage')

	subprocess.call('coverage erase', shell=True, cwd=testdir)
	subprocess.call('coverage run -m py.test ' + arguments, shell=True, cwd=testdir)
	subprocess.call('coverage combine', shell=True, cwd=testdir)
	subprocess.call('coverage html -d ' + os.path.join(testdir, 'htmlcov') +
					' --include=' + script_path, shell=True, cwd=testdir)
	subprocess.call('coverage report --include=' + script_path,
					shell=True, cwd=testdir)

if __name__ == '__main__':
	main()

Prompt:
Replace coverage API calls by subprocess calls.
#!/usr/bin/env python
"""Script to collect coverage information on ofStateManager"""

import os
import sys
import inspect
import coverage
import subprocess

def main():
	"""Main function"""
	arguments = ''
	if len(sys.argv) > 1:
		arguments = ' '.join(sys.argv[1:])
	testdir = os.path.abspath(os.path.dirname(
			inspect.getfile(inspect.currentframe())))
	os.environ['COVERAGE_PROCESS_START'] = os.path.join(testdir, '.coveragerc')
	os.environ['COVERAGE_FILE'] = os.path.join(testdir, '.coverage')
	cov = coverage.coverage(source=os.path.join(testdir, '..'),
		include=os.path.join(testdir, '..', 'ofStateManager.py'))
	cov.erase()
	subprocess.call('coverage run -m py.test ' + arguments, shell=True,
					cwd=testdir)
	cov.combine()
	cov.html_report(directory=os.path.join(testdir, 'htmlcov'))
	cov.report(show_missing=False)

if __name__ == '__main__':
	main()


#!/usr/bin/env python

from setuptools import setup, find_packages

__author__ = "Nitrax <nitrax@lokisec.fr>"
__copyright__ = "Copyright 2017, Legobot"

description = 'Lego providing networking tools'
name = 'legos.nettools'
setup(
    name=name,
    version='0.1.0',
    namespace_packages=name.split('.')[:-1],
    license='MIT',
    description=description,
    author='Nitrax',
    url='https://github.com/Legobot/' + name,
    install_requires=['legobot>=1.1.4,<=2.0.0',
                      'python-whois',
                      'urllib3',
                      'bandit==1.3.0',
                      'flake8==3.2.1',
                      'pytest==3.0.5'
                      ],
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3'
    ],
    packages=find_packages()
)

Fix trove classifier for pypi

Fix trove classifier for pypi

Response:
<REPLACE_OLD> MIT',

 <REPLACE_NEW> OSI Approved :: MIT License',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from setuptools import setup, find_packages

__author__ = "Nitrax <nitrax@lokisec.fr>"
__copyright__ = "Copyright 2017, Legobot"

description = 'Lego providing networking tools'
name = 'legos.nettools'
setup(
    name=name,
    version='0.1.0',
    namespace_packages=name.split('.')[:-1],
    license='MIT',
    description=description,
    author='Nitrax',
    url='https://github.com/Legobot/' + name,
    install_requires=['legobot>=1.1.4,<=2.0.0',
                      'python-whois',
                      'urllib3',
                      'bandit==1.3.0',
                      'flake8==3.2.1',
                      'pytest==3.0.5'
                      ],
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3'
    ],
    packages=find_packages()
)

Prompt:
Fix trove classifier for pypi

#!/usr/bin/env python

from setuptools import setup, find_packages

__author__ = "Nitrax <nitrax@lokisec.fr>"
__copyright__ = "Copyright 2017, Legobot"

description = 'Lego providing networking tools'
name = 'legos.nettools'
setup(
    name=name,
    version='0.1.0',
    namespace_packages=name.split('.')[:-1],
    license='MIT',
    description=description,
    author='Nitrax',
    url='https://github.com/Legobot/' + name,
    install_requires=['legobot>=1.1.4,<=2.0.0',
                      'python-whois',
                      'urllib3',
                      'bandit==1.3.0',
                      'flake8==3.2.1',
                      'pytest==3.0.5'
                      ],
    classifiers=[
        'License :: MIT',

        'Programming Language :: Python :: 3'
    ],
    packages=find_packages()
)


import tornado
import time
from bson.json_util import dumps
from tornado.options import options

class FilesServiceHandler(tornado.web.RequestHandler):
    def initialize(self, logger, mongodb):
        self.logger = logger
        self.mongodb = mongodb[options.db_name]['Files']

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self):
        self.logger.info('Request to file upload')

        result = []

        for item in self.request.files.values():
            for file_info in item:
                timestamp = time.time()

                data = {
                    'name': '%s-%s' % (timestamp, file_info['filename']),
                    'location': 'TBD',
                    'context': 'context',
                    'realName': file_info['filename'],
                    'mimeType': file_info['content_type'],
                    'deleted': False,
                    'timestamp': timestamp,
                    'restrictions': {
                        'quota': False,
                        'session': False
                    }
                }

                self.logger.info('File uploaded: %s with mime type %s' % (data['realName'], data['mimeType']))

                with open('%s/%s' % (options.files_dir, data['name']), 'w') as f:
                    f.write(file_info['body'])

                self.logger.info('File saved at %s' % data['name'])

                yield self.mongodb.save(data)
                result.append(data)

        self.write(dumps(result))

Save file info in DB

Save file info in DB

Response:
<REPLACE_OLD> mongodb

 <REPLACE_NEW> mongodb[options.db_name]['Files']

 <REPLACE_END> <INSERT> result = []

        <INSERT_END> <INSERT> for <INSERT_END> <INSERT> in item:
                timestamp <INSERT_END> <REPLACE_OLD> item[0]

 <REPLACE_NEW> time.time()

                data = {
                    'name': '%s-%s' % (timestamp, file_info['filename']),
                    'location': 'TBD',
                    'context': 'context',
                    'realName': file_info['filename'],
                    'mimeType': file_info['content_type'],
                    'deleted': False,
                    'timestamp': timestamp,
                    'restrictions': {
                        'quota': False,
                        'session': False
                    }
                }

     <REPLACE_END> <REPLACE_OLD> (file_info['filename'], file_info['content_type']))
            name = '%s-%s' % (time.time(), file_info['filename'])

 <REPLACE_NEW> (data['realName'], data['mimeType']))

     <REPLACE_END> <REPLACE_OLD> name), <REPLACE_NEW> data['name']), <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> name)

        self.write('done')
 <REPLACE_NEW> data['name'])

                yield self.mongodb.save(data)
                result.append(data)

        self.write(dumps(result))
 <REPLACE_END> <|endoftext|> import tornado
import time
from bson.json_util import dumps
from tornado.options import options

class FilesServiceHandler(tornado.web.RequestHandler):
    def initialize(self, logger, mongodb):
        self.logger = logger
        self.mongodb = mongodb[options.db_name]['Files']

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self):
        self.logger.info('Request to file upload')

        result = []

        for item in self.request.files.values():
            for file_info in item:
                timestamp = time.time()

                data = {
                    'name': '%s-%s' % (timestamp, file_info['filename']),
                    'location': 'TBD',
                    'context': 'context',
                    'realName': file_info['filename'],
                    'mimeType': file_info['content_type'],
                    'deleted': False,
                    'timestamp': timestamp,
                    'restrictions': {
                        'quota': False,
                        'session': False
                    }
                }

                self.logger.info('File uploaded: %s with mime type %s' % (data['realName'], data['mimeType']))

                with open('%s/%s' % (options.files_dir, data['name']), 'w') as f:
                    f.write(file_info['body'])

                self.logger.info('File saved at %s' % data['name'])

                yield self.mongodb.save(data)
                result.append(data)

        self.write(dumps(result))

Prompt:
Save file info in DB

import tornado
import time
from bson.json_util import dumps
from tornado.options import options

class FilesServiceHandler(tornado.web.RequestHandler):
    def initialize(self, logger, mongodb):
        self.logger = logger
        self.mongodb = mongodb

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self):
        self.logger.info('Request to file upload')

        for item in self.request.files.values():
            file_info = item[0]

            self.logger.info('File uploaded: %s with mime type %s' % (file_info['filename'], file_info['content_type']))
            name = '%s-%s' % (time.time(), file_info['filename'])

            with open('%s/%s' % (options.files_dir, name), 'w') as f:
                f.write(file_info['body'])

            self.logger.info('File saved at %s' % name)

        self.write('done')


#!/usr/bin/env python
TRAJECTORY = 'linear'

if TRAJECTORY == 'linear':
    SIMULATION_TIME_IN_SECONDS = 80.0
elif TRAJECTORY == 'circular':
    SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
    SIMULATION_TIME_IN_SECONDS = 160.0

DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)

# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90

# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00

K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000

Response:
<REPLACE_OLD> 40.0
elif <REPLACE_NEW> 80.0
elif <REPLACE_END> <|endoftext|> #!/usr/bin/env python
TRAJECTORY = 'linear'

if TRAJECTORY == 'linear':
    SIMULATION_TIME_IN_SECONDS = 80.0
elif TRAJECTORY == 'circular':
    SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
    SIMULATION_TIME_IN_SECONDS = 160.0

DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)

# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90

# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00

K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000

Prompt:
Increase simulation time for linear trajectory

#!/usr/bin/env python
TRAJECTORY = 'linear'

if TRAJECTORY == 'linear':
    SIMULATION_TIME_IN_SECONDS = 40.0
elif TRAJECTORY == 'circular':
    SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
    SIMULATION_TIME_IN_SECONDS = 160.0

DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)

# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90

# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00

K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000


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

from tempest.lib import decorators

from senlin.tests.tempest.api import base

class TestAPIVersionShow(base.BaseSenlinTest):

    @decorators.idempotent_id('4a270caa-9917-4acd-98ef-6636f9618037')
    def test_API_version_show(self):
        resp, body = self.client.request('GET', '/v1/')
        res = self.client._parsed_resp(resp, body)

        # Verify resp of API version show
        self.assertEqual(200, res['status'])
        self.assertIsNotNone(res['body'])
        version = res['body']
        for key in ['id', 'links', 'media-types', 'status', 'updated']:
            self.assertIn(key, version)
        self.assertEqual('1.0', version['id'])

Add tempest API test for API version show

This patch add tempest API test for API version show.

Change-Id: I1cf7cba550bb04629acab9899be310fd3b767576

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

from tempest.lib import decorators

from senlin.tests.tempest.api import base

class TestAPIVersionShow(base.BaseSenlinTest):

    @decorators.idempotent_id('4a270caa-9917-4acd-98ef-6636f9618037')
    def test_API_version_show(self):
        resp, body = self.client.request('GET', '/v1/')
        res = self.client._parsed_resp(resp, body)

        # Verify resp of API version show
        self.assertEqual(200, res['status'])
        self.assertIsNotNone(res['body'])
        version = res['body']
        for key in ['id', 'links', 'media-types', 'status', 'updated']:
            self.assertIn(key, version)
        self.assertEqual('1.0', version['id'])
 <REPLACE_END> <|endoftext|> # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from tempest.lib import decorators

from senlin.tests.tempest.api import base

class TestAPIVersionShow(base.BaseSenlinTest):

    @decorators.idempotent_id('4a270caa-9917-4acd-98ef-6636f9618037')
    def test_API_version_show(self):
        resp, body = self.client.request('GET', '/v1/')
        res = self.client._parsed_resp(resp, body)

        # Verify resp of API version show
        self.assertEqual(200, res['status'])
        self.assertIsNotNone(res['body'])
        version = res['body']
        for key in ['id', 'links', 'media-types', 'status', 'updated']:
            self.assertIn(key, version)
        self.assertEqual('1.0', version['id'])

Prompt:
Add tempest API test for API version show

This patch add tempest API test for API version show.

Change-Id: I1cf7cba550bb04629acab9899be310fd3b767576


import time
import urllib2
from BeautifulSoup import *
# from bs4 import *

print 'Welcome to the Get Twitter tool. This tool will allow you to download a page from Twitter to be used to extract the data.'

print "Current date & time {}".format(time.strftime("%c"))
userResponse = raw_input("Please enter the full URL from the Tweet page: ")
response = urllib2.urlopen(userResponse)
html = response.read()

soup = BeautifulSoup(html)
with open(time.strftime("%c"), 'a') as f:
	f.write(html)

Response:
<INSERT> time
import <INSERT_END> <REPLACE_OLD> *

print <REPLACE_NEW> *
# from bs4 import *

print <REPLACE_END> <REPLACE_OLD> data'

userResponse <REPLACE_NEW> data.'

print "Current date & time {}".format(time.strftime("%c"))
userResponse <REPLACE_END> <REPLACE_OLD> page")
response <REPLACE_NEW> page: ")
response <REPLACE_END> <REPLACE_OLD> open('TwitterPage', <REPLACE_NEW> open(time.strftime("%c"), <REPLACE_END> <|endoftext|> import time
import urllib2
from BeautifulSoup import *
# from bs4 import *

print 'Welcome to the Get Twitter tool. This tool will allow you to download a page from Twitter to be used to extract the data.'

print "Current date & time {}".format(time.strftime("%c"))
userResponse = raw_input("Please enter the full URL from the Tweet page: ")
response = urllib2.urlopen(userResponse)
html = response.read()

soup = BeautifulSoup(html)
with open(time.strftime("%c"), 'a') as f:
	f.write(html)

Prompt:
Call html page the date and time of get request

The html file that is outputted how has the current date and time as its name
import urllib2
from BeautifulSoup import *

print 'Welcome to the Get Twitter tool. This tool will allow you to download a page from Twitter to be used to extract the data'

userResponse = raw_input("Please enter the full URL from the Tweet page")
response = urllib2.urlopen(userResponse)
html = response.read()

soup = BeautifulSoup(html)
with open('TwitterPage', 'a') as f:
	f.write(html)


# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import

class NetworkInterfaceNotFoundError(Exception):
    """
    Exception raised when network interface not found.
    """

class ModuleNotFoundError(Exception):
    """
    Exception raised when mandatory kernel module not found.
    """

class TcCommandExecutionError(Exception):
    """
    Exception raised when failed to execute a ``tc`` command.
    """

class TcAlreadyExist(TcCommandExecutionError):
    """
    Exception raised when a traffic shaping rule already exist.
    """

class EmptyParameterError(ValueError):
    """
    Exception raised when a parameter value is empty value.
    """

class InvalidParameterError(ValueError):
    """
    Exception raised when an invalid parameter specified for
    a traffic shaping rule.
    """

    def __init__(self, *args, **kwargs):
        self.__value = kwargs.pop("value", None)
        self.__expected = kwargs.pop("expected", None)

        super(ValueError, self).__init__(*args)

    def __str__(self, *args, **kwargs):
        item_list = [ValueError.__str__(self, *args, **kwargs)]
        extra_item_list = []

        if self.__expected:
            extra_item_list.append("expected={}".format(self.__expected))

        if self.__value:
            extra_item_list.append("value={}".format(self.__value))

        if extra_item_list:
            item_list.extend([":", ", ".join(extra_item_list)])

        return " ".join(item_list)

    def __repr__(self, *args, **kwargs):
        return self.__str__(*args, **kwargs)

class UnitNotFoundError(InvalidParameterError):
    """
    """

Response:
<REPLACE_OLD> """

class <REPLACE_NEW> """

    def __init__(self, *args, **kwargs):
        self.__value = kwargs.pop("value", None)
        self.__expected = kwargs.pop("expected", None)

        super(ValueError, self).__init__(*args)

    def __str__(self, *args, **kwargs):
        item_list = [ValueError.__str__(self, *args, **kwargs)]
        extra_item_list = []

        if self.__expected:
            extra_item_list.append("expected={}".format(self.__expected))

        if self.__value:
            extra_item_list.append("value={}".format(self.__value))

        if extra_item_list:
            item_list.extend([":", ", ".join(extra_item_list)])

        return " ".join(item_list)

    def __repr__(self, *args, **kwargs):
        return self.__str__(*args, **kwargs)

class <REPLACE_END> <|endoftext|> # encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import

class NetworkInterfaceNotFoundError(Exception):
    """
    Exception raised when network interface not found.
    """

class ModuleNotFoundError(Exception):
    """
    Exception raised when mandatory kernel module not found.
    """

class TcCommandExecutionError(Exception):
    """
    Exception raised when failed to execute a ``tc`` command.
    """

class TcAlreadyExist(TcCommandExecutionError):
    """
    Exception raised when a traffic shaping rule already exist.
    """

class EmptyParameterError(ValueError):
    """
    Exception raised when a parameter value is empty value.
    """

class InvalidParameterError(ValueError):
    """
    Exception raised when an invalid parameter specified for
    a traffic shaping rule.
    """

    def __init__(self, *args, **kwargs):
        self.__value = kwargs.pop("value", None)
        self.__expected = kwargs.pop("expected", None)

        super(ValueError, self).__init__(*args)

    def __str__(self, *args, **kwargs):
        item_list = [ValueError.__str__(self, *args, **kwargs)]
        extra_item_list = []

        if self.__expected:
            extra_item_list.append("expected={}".format(self.__expected))

        if self.__value:
            extra_item_list.append("value={}".format(self.__value))

        if extra_item_list:
            item_list.extend([":", ", ".join(extra_item_list)])

        return " ".join(item_list)

    def __repr__(self, *args, **kwargs):
        return self.__str__(*args, **kwargs)

class UnitNotFoundError(InvalidParameterError):
    """
    """

Prompt:
Add custom arguments for InvalidParameterError

# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import

class NetworkInterfaceNotFoundError(Exception):
    """
    Exception raised when network interface not found.
    """

class ModuleNotFoundError(Exception):
    """
    Exception raised when mandatory kernel module not found.
    """

class TcCommandExecutionError(Exception):
    """
    Exception raised when failed to execute a ``tc`` command.
    """

class TcAlreadyExist(TcCommandExecutionError):
    """
    Exception raised when a traffic shaping rule already exist.
    """

class EmptyParameterError(ValueError):
    """
    Exception raised when a parameter value is empty value.
    """

class InvalidParameterError(ValueError):
    """
    Exception raised when an invalid parameter specified for
    a traffic shaping rule.
    """

class UnitNotFoundError(InvalidParameterError):
    """
    """


import unittest2

from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException

class ConfigTests(unittest2.TestCase):
    def test_properties_parsing(self):
        config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'any-stack': {'template-url': 'foo.json', 'tags': {'any-tag': 'any-tag-value'}, 'parameters': {'any-parameter': 'any-value'}}}})
        self.assertEqual('eu-west-1', config.region)
        self.assertEqual(1, len(config.stacks.keys()))
        self.assertTrue(isinstance(config.stacks['any-stack'], StackConfig))
        self.assertEqual('foo.json', config.stacks['any-stack'].template_url)
        self.assertEqual({'any-tag': 'any-tag-value'}, config.stacks['any-stack'].tags)
        self.assertEqual({'any-parameter': 'any-value'}, config.stacks['any-stack'].parameters)

    def test_raises_exception_if_no_region_key(self):
        with self.assertRaises(NoConfigException):
            Config(config_dict={'foo': '', 'stacks': {'any-stack': {'template': 'foo.json'}}})

    def test_raises_exception_if_no_stacks_key(self):
        with self.assertRaises(NoConfigException):
            Config(config_dict={'region': 'eu-west-1'})

Make test variables more descriptive

Response:
<REPLACE_OLD> {'foo': <REPLACE_NEW> {'any-stack': <REPLACE_END> <REPLACE_OLD> 'foo.json'}}})
 <REPLACE_NEW> 'foo.json', 'tags': {'any-tag': 'any-tag-value'}, 'parameters': {'any-parameter': 'any-value'}}}})
 <REPLACE_END> <REPLACE_OLD> self.assertTrue(isinstance(config.stacks['foo'], <REPLACE_NEW> self.assertTrue(isinstance(config.stacks['any-stack'], <REPLACE_END> <REPLACE_OLD> config.stacks['foo'].template_url)

 <REPLACE_NEW> config.stacks['any-stack'].template_url)
        self.assertEqual({'any-tag': 'any-tag-value'}, config.stacks['any-stack'].tags)
        self.assertEqual({'any-parameter': 'any-value'}, config.stacks['any-stack'].parameters)

 <REPLACE_END> <REPLACE_OLD> {'foo': <REPLACE_NEW> {'any-stack': <REPLACE_END> <|endoftext|> import unittest2

from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException

class ConfigTests(unittest2.TestCase):
    def test_properties_parsing(self):
        config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'any-stack': {'template-url': 'foo.json', 'tags': {'any-tag': 'any-tag-value'}, 'parameters': {'any-parameter': 'any-value'}}}})
        self.assertEqual('eu-west-1', config.region)
        self.assertEqual(1, len(config.stacks.keys()))
        self.assertTrue(isinstance(config.stacks['any-stack'], StackConfig))
        self.assertEqual('foo.json', config.stacks['any-stack'].template_url)
        self.assertEqual({'any-tag': 'any-tag-value'}, config.stacks['any-stack'].tags)
        self.assertEqual({'any-parameter': 'any-value'}, config.stacks['any-stack'].parameters)

    def test_raises_exception_if_no_region_key(self):
        with self.assertRaises(NoConfigException):
            Config(config_dict={'foo': '', 'stacks': {'any-stack': {'template': 'foo.json'}}})

    def test_raises_exception_if_no_stacks_key(self):
        with self.assertRaises(NoConfigException):
            Config(config_dict={'region': 'eu-west-1'})

Prompt:
refactor: Make test variables more descriptive

import unittest2

from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException

class ConfigTests(unittest2.TestCase):
    def test_properties_parsing(self):
        config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'foo': {'template-url': 'foo.json'}}})
        self.assertEqual('eu-west-1', config.region)
        self.assertEqual(1, len(config.stacks.keys()))
        self.assertTrue(isinstance(config.stacks['foo'], StackConfig))
        self.assertEqual('foo.json', config.stacks['foo'].template_url)

    def test_raises_exception_if_no_region_key(self):
        with self.assertRaises(NoConfigException):
            Config(config_dict={'foo': '', 'stacks': {'foo': {'template': 'foo.json'}}})

    def test_raises_exception_if_no_stacks_key(self):
        with self.assertRaises(NoConfigException):
            Config(config_dict={'region': 'eu-west-1'})


"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.

constants
"""

import logging

def set_logging(name="dock", level=logging.DEBUG, handler=None):
    # create logger
    logger = logging.getLogger(name)
    logger.handlers = []
    logger.setLevel(level)

    if not handler:
        # create console handler and set level to debug
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)

        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # add formatter to ch
        handler.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(handler)

set_logging(level=logging.WARNING)  # override this however you want

Response:
<REPLACE_OLD> level=logging.DEBUG):
 <REPLACE_NEW> level=logging.DEBUG, handler=None):
 <REPLACE_END> <INSERT> if not handler:
        <INSERT_END> <REPLACE_OLD> ch <REPLACE_NEW>     handler <REPLACE_END> <REPLACE_OLD> ch.setLevel(logging.DEBUG)

 <REPLACE_NEW>     handler.setLevel(logging.DEBUG)

     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> ch.setFormatter(formatter)

 <REPLACE_NEW>     handler.setFormatter(formatter)

 <REPLACE_END> <REPLACE_OLD> logger.addHandler(ch)

set_logging(level=logging.WARNING) <REPLACE_NEW> logger.addHandler(handler)

set_logging(level=logging.WARNING) <REPLACE_END> <REPLACE_OLD> want <REPLACE_NEW> want
 <REPLACE_END> <|endoftext|> """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.

constants
"""

import logging

def set_logging(name="dock", level=logging.DEBUG, handler=None):
    # create logger
    logger = logging.getLogger(name)
    logger.handlers = []
    logger.setLevel(level)

    if not handler:
        # create console handler and set level to debug
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)

        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # add formatter to ch
        handler.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(handler)

set_logging(level=logging.WARNING)  # override this however you want

Prompt:
Allow redirecting dock's logs to a given handler only

"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.

constants
"""

import logging

def set_logging(name="dock", level=logging.DEBUG):
    # create logger
    logger = logging.getLogger(name)
    logger.handlers = []
    logger.setLevel(level)

    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # add formatter to ch
    ch.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(ch)

set_logging(level=logging.WARNING)  # override this however you want


import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol, MessageFrameParser

def main():
    zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True

    collector = MeasurementCollector()
    rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
    signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]

    signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])

    payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])

    message_parser = MessageFrameParser(payload_parser.handle_message)

    ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")

    protocol = Protocol(ser, [message_parser.parse_data])

    try:
        protocol.run()
    except EOFError:
        pass

    visualize_measurements(collector)

if __name__ == "__main__":
    main()

Response:
<REPLACE_OLD> Protocol

def <REPLACE_NEW> Protocol, MessageFrameParser

def <REPLACE_END> <INSERT> message_parser = MessageFrameParser(payload_parser.handle_message)

    <INSERT_END> <REPLACE_OLD> payload_parser.handle_message)
 <REPLACE_NEW> [message_parser.parse_data])
 <REPLACE_END> <|endoftext|>
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol, MessageFrameParser

def main():
    zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True

    collector = MeasurementCollector()
    rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
    signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]

    signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])

    payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])

    message_parser = MessageFrameParser(payload_parser.handle_message)

    ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")

    protocol = Protocol(ser, [message_parser.parse_data])

    try:
        protocol.run()
    except EOFError:
        pass

    visualize_measurements(collector)

if __name__ == "__main__":
    main()

Prompt:
Fix test data plotting to use the changed interfaces

import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol

def main():
    zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True

    collector = MeasurementCollector()
    rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
    signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]

    signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])

    payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])

    ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")

    protocol = Protocol(ser, payload_parser.handle_message)

    try:
        protocol.run()
    except EOFError:
        pass

    visualize_measurements(collector)

if __name__ == "__main__":
    main()


import guzzle_sphinx_theme

project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
    "project_nav_name": project,
    "projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
    "**": [
        "logo-text.html",
        # "globaltoc.html",
        "localtoc.html",
        "searchbox.html"
    ]
}

Adjust copyright line in docs

Adjust copyright line in docs

Response:
<REPLACE_OLD> Kislyuk"
author <REPLACE_NEW> Kislyuk and argcomplete contributors"
author <REPLACE_END> <|endoftext|> import guzzle_sphinx_theme

project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
    "project_nav_name": project,
    "projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
    "**": [
        "logo-text.html",
        # "globaltoc.html",
        "localtoc.html",
        "searchbox.html"
    ]
}

Prompt:
Adjust copyright line in docs

import guzzle_sphinx_theme

project = "argcomplete"
copyright = "Andrey Kislyuk"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
    "project_nav_name": project,
    "projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
    "**": [
        "logo-text.html",
        # "globaltoc.html",
        "localtoc.html",
        "searchbox.html"
    ]
}


import functools

from django.contrib.auth import REDIRECT_FIELD_NAME

from account.utils import handle_redirect_to_login

def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log in page if necessary.
    """
    def decorator(view_func):
        @functools.wraps(view_func, assigned=functools.WRAPPER_ASSIGNMENTS)
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated:
                return view_func(request, *args, **kwargs)
            return handle_redirect_to_login(
                request,
                redirect_field_name=redirect_field_name,
                login_url=login_url
            )
        return _wrapped_view
    if func:
        return decorator(func)
    return decorator

Fix a 3.0 compat issue

Fix a 3.0 compat issue

Response:
<REPLACE_OLD> REDIRECT_FIELD_NAME
from django.utils.decorators import available_attrs

from <REPLACE_NEW> REDIRECT_FIELD_NAME

from <REPLACE_END> <REPLACE_OLD> assigned=available_attrs(view_func))
 <REPLACE_NEW> assigned=functools.WRAPPER_ASSIGNMENTS)
 <REPLACE_END> <|endoftext|> import functools

from django.contrib.auth import REDIRECT_FIELD_NAME

from account.utils import handle_redirect_to_login

def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log in page if necessary.
    """
    def decorator(view_func):
        @functools.wraps(view_func, assigned=functools.WRAPPER_ASSIGNMENTS)
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated:
                return view_func(request, *args, **kwargs)
            return handle_redirect_to_login(
                request,
                redirect_field_name=redirect_field_name,
                login_url=login_url
            )
        return _wrapped_view
    if func:
        return decorator(func)
    return decorator

Prompt:
Fix a 3.0 compat issue

import functools

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.decorators import available_attrs

from account.utils import handle_redirect_to_login

def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log in page if necessary.
    """
    def decorator(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated:
                return view_func(request, *args, **kwargs)
            return handle_redirect_to_login(
                request,
                redirect_field_name=redirect_field_name,
                login_url=login_url
            )
        return _wrapped_view
    if func:
        return decorator(func)
    return decorator


from django_evolution.db import evolver

def write_sql(sql):
    "Output a list of SQL statements, unrolling parameters as required"
    for statement in sql:
        if isinstance(statement, tuple):
            print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
        else:
            print unicode(statement)

def execute_sql(cursor, sql):
    """
    Execute a list of SQL statements on the provided cursor, unrolling
    parameters as required
    """
    for statement in sql:
        if isinstance(statement, tuple):
            if not statement[0].startswith('--'):
                cursor.execute(*statement)
        else:
            if not statement.startswith('--'):
                cursor.execute(statement)

Response:
<DELETE> try:
                    <DELETE_END> <DELETE>                except:
                    print statement
                    print sql
                    raise Exception(statement)
 <DELETE_END> <|endoftext|> from django_evolution.db import evolver

def write_sql(sql):
    "Output a list of SQL statements, unrolling parameters as required"
    for statement in sql:
        if isinstance(statement, tuple):
            print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
        else:
            print unicode(statement)

def execute_sql(cursor, sql):
    """
    Execute a list of SQL statements on the provided cursor, unrolling
    parameters as required
    """
    for statement in sql:
        if isinstance(statement, tuple):
            if not statement[0].startswith('--'):
                cursor.execute(*statement)
        else:
            if not statement.startswith('--'):
                cursor.execute(statement)

Prompt:
Revert a debugging change that slipped in.

git-svn-id: 48f3d5eb0141859d8d7d81547b6bd7b3dde885f8@186 8655a95f-0638-0410-abc2-2f1ed958ef3d

from django_evolution.db import evolver

def write_sql(sql):
    "Output a list of SQL statements, unrolling parameters as required"
    for statement in sql:
        if isinstance(statement, tuple):
            print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
        else:
            print unicode(statement)

def execute_sql(cursor, sql):
    """
    Execute a list of SQL statements on the provided cursor, unrolling
    parameters as required
    """
    for statement in sql:
        if isinstance(statement, tuple):
            if not statement[0].startswith('--'):
                cursor.execute(*statement)
        else:
            if not statement.startswith('--'):
                try:
                    cursor.execute(statement)
                except:
                    print statement
                    print sql
                    raise Exception(statement)


#!/usr/bin/env python3
import os
from setuptools import setup, find_packages

def get_readme():
    return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

setup(
    author="Julio Gonzalez Altamirano",
    author_email='devjga@gmail.com',
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3 :: Only',
    ],
    description="ETL for CapMetro raw data.",
    entry_points={
        'console_scripts': [
            'capmetrics=capmetrics_etl.cli:run',
            'capmetrics-tables=capmetrics_etl.cli.tables'
        ],
    },
    install_requires=['click', 'pytz', 'sqlalchemy', 'xlrd'],
    keywords="python etl transit",
    license="MIT",
    long_description=get_readme(),
    name='capmetrics-etl',
    package_data={
        'capmetrics_etl': ['templates/*.html'],
    },
    packages=find_packages(include=['capmetrics_etl', 'capmetrics_etl.*'],
                           exclude=['tests', 'tests.*']),
    platforms=['any'],
    url='https://github.com/jga/capmetrics-etl',
    version='0.1.0'
)

Add table generation console script.

Add table generation console script.

Response:
<INSERT>     'capmetrics-tables=capmetrics_etl.cli.tables'
        <INSERT_END> <|endoftext|> #!/usr/bin/env python3
import os
from setuptools import setup, find_packages

def get_readme():
    return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

setup(
    author="Julio Gonzalez Altamirano",
    author_email='devjga@gmail.com',
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3 :: Only',
    ],
    description="ETL for CapMetro raw data.",
    entry_points={
        'console_scripts': [
            'capmetrics=capmetrics_etl.cli:run',
            'capmetrics-tables=capmetrics_etl.cli.tables'
        ],
    },
    install_requires=['click', 'pytz', 'sqlalchemy', 'xlrd'],
    keywords="python etl transit",
    license="MIT",
    long_description=get_readme(),
    name='capmetrics-etl',
    package_data={
        'capmetrics_etl': ['templates/*.html'],
    },
    packages=find_packages(include=['capmetrics_etl', 'capmetrics_etl.*'],
                           exclude=['tests', 'tests.*']),
    platforms=['any'],
    url='https://github.com/jga/capmetrics-etl',
    version='0.1.0'
)

Prompt:
Add table generation console script.

#!/usr/bin/env python3
import os
from setuptools import setup, find_packages

def get_readme():
    return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

setup(
    author="Julio Gonzalez Altamirano",
    author_email='devjga@gmail.com',
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3 :: Only',
    ],
    description="ETL for CapMetro raw data.",
    entry_points={
        'console_scripts': [
            'capmetrics=capmetrics_etl.cli:run',
        ],
    },
    install_requires=['click', 'pytz', 'sqlalchemy', 'xlrd'],
    keywords="python etl transit",
    license="MIT",
    long_description=get_readme(),
    name='capmetrics-etl',
    package_data={
        'capmetrics_etl': ['templates/*.html'],
    },
    packages=find_packages(include=['capmetrics_etl', 'capmetrics_etl.*'],
                           exclude=['tests', 'tests.*']),
    platforms=['any'],
    url='https://github.com/jga/capmetrics-etl',
    version='0.1.0'
)


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

import struct
from math import cos, asin, sqrt

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
    return 12742 * asin(sqrt(a)) * 1000

def i2f(int):
    return struct.unpack('<d', struct.pack('<Q', int))[0]

def print_green(message):
    print(u'\033[92m' + message.decode('utf-8') + '\033[0m');

def print_yellow(message):
    print(u'\033[93m' + message.decode('utf-8') + '\033[0m');

def print_red(message):
    print(u'\033[91m' + message.decode('utf-8') + '\033[0m');

Response:
<REPLACE_OLD> print('\033[92m' <REPLACE_NEW> print(u'\033[92m' <REPLACE_END> <REPLACE_OLD> message <REPLACE_NEW> message.decode('utf-8') <REPLACE_END> <REPLACE_OLD> print('\033[93m' <REPLACE_NEW> print(u'\033[93m' <REPLACE_END> <REPLACE_OLD> message <REPLACE_NEW> message.decode('utf-8') <REPLACE_END> <REPLACE_OLD> print('\033[91m' <REPLACE_NEW> print(u'\033[91m' <REPLACE_END> <REPLACE_OLD> message <REPLACE_NEW> message.decode('utf-8') <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import struct
from math import cos, asin, sqrt

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
    return 12742 * asin(sqrt(a)) * 1000

def i2f(int):
    return struct.unpack('<d', struct.pack('<Q', int))[0]

def print_green(message):
    print(u'\033[92m' + message.decode('utf-8') + '\033[0m');

def print_yellow(message):
    print(u'\033[93m' + message.decode('utf-8') + '\033[0m');

def print_red(message):
    print(u'\033[91m' + message.decode('utf-8') + '\033[0m');

Prompt:
Fix encoding error when printing messages

Some messages that will be printed will contain utf-8 chars, e.g. Pokestops in European locations.
# -*- coding: utf-8 -*-

import struct
from math import cos, asin, sqrt

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
    return 12742 * asin(sqrt(a)) * 1000

def i2f(int):
    return struct.unpack('<d', struct.pack('<Q', int))[0]

def print_green(message):
    print('\033[92m' + message + '\033[0m');

def print_yellow(message):
    print('\033[93m' + message + '\033[0m');

def print_red(message):
    print('\033[91m' + message + '\033[0m');


import requests

class AlgoliaEndpoint(object):
  """Class used to call the Algolia API and parse the response."""

  URL = "http://hn.algolia.com/api/v1/search_by_date"

  @staticmethod
  def get(tag, since, until=None, page=0):
    """Send a GET request to the endpoint.

    Since Algolia only returns JSON, parse it into a dict.

    See http://hn.algolia.com/api for more details.

    Params:
      tag: Can be "story" or "comment".
      since: timestamp representing how old the news should be.

    Optional params:
      until: timestamp representing how new the news should be.
      page: The number of the page to get.

    Returns:
      A python dict representing the response.

    Raises:
      requests.exceptions.RequestException.
    """

    numericFilters = ["created_at_i<%d" % since]
    if until is not None:
      numericFilters += ["created_at_i>%d" % until]

    params = {
        "numericFilters": ",".join(numericFilters),
        "tags": tag,
        "page": page
    }

    url = AlgoliaEndpoint.URL
    url += "?" + "&".join(["%s=%s" for k,v in params.items()])
    response = requests.get(url)

    return response.json()

Add Algolia API website in docstring.

Add Algolia API website in docstring.

Response:
<INSERT> See http://hn.algolia.com/api for more details.

    <INSERT_END> <|endoftext|> import requests

class AlgoliaEndpoint(object):
  """Class used to call the Algolia API and parse the response."""

  URL = "http://hn.algolia.com/api/v1/search_by_date"

  @staticmethod
  def get(tag, since, until=None, page=0):
    """Send a GET request to the endpoint.

    Since Algolia only returns JSON, parse it into a dict.

    See http://hn.algolia.com/api for more details.

    Params:
      tag: Can be "story" or "comment".
      since: timestamp representing how old the news should be.

    Optional params:
      until: timestamp representing how new the news should be.
      page: The number of the page to get.

    Returns:
      A python dict representing the response.

    Raises:
      requests.exceptions.RequestException.
    """

    numericFilters = ["created_at_i<%d" % since]
    if until is not None:
      numericFilters += ["created_at_i>%d" % until]

    params = {
        "numericFilters": ",".join(numericFilters),
        "tags": tag,
        "page": page
    }

    url = AlgoliaEndpoint.URL
    url += "?" + "&".join(["%s=%s" for k,v in params.items()])
    response = requests.get(url)

    return response.json()

Prompt:
Add Algolia API website in docstring.

import requests

class AlgoliaEndpoint(object):
  """Class used to call the Algolia API and parse the response."""

  URL = "http://hn.algolia.com/api/v1/search_by_date"

  @staticmethod
  def get(tag, since, until=None, page=0):
    """Send a GET request to the endpoint.

    Since Algolia only returns JSON, parse it into a dict.

    Params:
      tag: Can be "story" or "comment".
      since: timestamp representing how old the news should be.

    Optional params:
      until: timestamp representing how new the news should be.
      page: The number of the page to get.

    Returns:
      A python dict representing the response.

    Raises:
      requests.exceptions.RequestException.
    """

    numericFilters = ["created_at_i<%d" % since]
    if until is not None:
      numericFilters += ["created_at_i>%d" % until]

    params = {
        "numericFilters": ",".join(numericFilters),
        "tags": tag,
        "page": page
    }

    url = AlgoliaEndpoint.URL
    url += "?" + "&".join(["%s=%s" for k,v in params.items()])
    response = requests.get(url)

    return response.json()


# coding: utf-8

from django.conf import settings

DEFAULTS = {
    "SPEEDINFO_TESTS": False,
    "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached",
    "SPEEDINFO_STORAGE": None,
    "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
    "SPEEDINFO_PROFILING_CONDITIONS": [],
    "SPEEDINFO_EXCLUDE_URLS": [],
    "SPEEDINFO_ADMIN_COLUMNS": (
        ("View name", "{}", "view_name"),
        ("HTTP method", "{}", "method"),
        ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"),
        ("Cache hits", "{:.1f}%", "cache_hits_ratio"),
        ("SQL queries per call", "{}", "sql_count_per_call"),
        ("SQL time", "{:.1f}%", "sql_time_ratio"),
        ("Total calls", "{}", "total_calls"),
        ("Time per call", "{:.8f}", "time_per_call"),
        ("Total time", "{:.4f}", "total_time"),
    ),
}

class SpeedinfoSettings:
    def __init__(self, defaults=None):
        self.defaults = defaults or DEFAULTS

    def __getattr__(self, name):
        if name not in self.defaults:
            raise AttributeError("Invalid setting: '{}'".format(name))

        return getattr(settings, name, self.defaults.get(name))

speedinfo_settings = SpeedinfoSettings()

Response:
<REPLACE_OLD> "is_cached",
 <REPLACE_NEW> "_is_cached",
 <REPLACE_END> <|endoftext|> # coding: utf-8

from django.conf import settings

DEFAULTS = {
    "SPEEDINFO_TESTS": False,
    "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached",
    "SPEEDINFO_STORAGE": None,
    "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
    "SPEEDINFO_PROFILING_CONDITIONS": [],
    "SPEEDINFO_EXCLUDE_URLS": [],
    "SPEEDINFO_ADMIN_COLUMNS": (
        ("View name", "{}", "view_name"),
        ("HTTP method", "{}", "method"),
        ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"),
        ("Cache hits", "{:.1f}%", "cache_hits_ratio"),
        ("SQL queries per call", "{}", "sql_count_per_call"),
        ("SQL time", "{:.1f}%", "sql_time_ratio"),
        ("Total calls", "{}", "total_calls"),
        ("Time per call", "{:.8f}", "time_per_call"),
        ("Total time", "{:.4f}", "total_time"),
    ),
}

class SpeedinfoSettings:
    def __init__(self, defaults=None):
        self.defaults = defaults or DEFAULTS

    def __getattr__(self, name):
        if name not in self.defaults:
            raise AttributeError("Invalid setting: '{}'".format(name))

        return getattr(settings, name, self.defaults.get(name))

speedinfo_settings = SpeedinfoSettings()

Prompt:
Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`

# coding: utf-8

from django.conf import settings

DEFAULTS = {
    "SPEEDINFO_TESTS": False,
    "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached",
    "SPEEDINFO_STORAGE": None,
    "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
    "SPEEDINFO_PROFILING_CONDITIONS": [],
    "SPEEDINFO_EXCLUDE_URLS": [],
    "SPEEDINFO_ADMIN_COLUMNS": (
        ("View name", "{}", "view_name"),
        ("HTTP method", "{}", "method"),
        ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"),
        ("Cache hits", "{:.1f}%", "cache_hits_ratio"),
        ("SQL queries per call", "{}", "sql_count_per_call"),
        ("SQL time", "{:.1f}%", "sql_time_ratio"),
        ("Total calls", "{}", "total_calls"),
        ("Time per call", "{:.8f}", "time_per_call"),
        ("Total time", "{:.4f}", "total_time"),
    ),
}

class SpeedinfoSettings:
    def __init__(self, defaults=None):
        self.defaults = defaults or DEFAULTS

    def __getattr__(self, name):
        if name not in self.defaults:
            raise AttributeError("Invalid setting: '{}'".format(name))

        return getattr(settings, name, self.defaults.get(name))

speedinfo_settings = SpeedinfoSettings()


import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler

bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, None)

@scheduler.scheduled_job(trigger='cron', hour=21, minute=0)
def on_job():
    """Start at 9:00pm PT"""
    print('STARTING BREATHER')
    breather.restart()

@scheduler.scheduled_job(trigger='cron', hour=23, minute=0)
def off_job():
    """End at 11:00pm PT"""
    print("STOPPING BREATHER")
    breather.shutdown()

if __name__ == '__main__':
    scheduler.start()
    waitress.serve(bottle_app, host='0.0.0.0', port=7000)

Response:
<REPLACE_OLD> breathe

if <REPLACE_NEW> breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler

bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, None)

@scheduler.scheduled_job(trigger='cron', hour=21, minute=0)
def on_job():
    """Start at 9:00pm PT"""
    print('STARTING BREATHER')
    breather.restart()

@scheduler.scheduled_job(trigger='cron', hour=23, minute=0)
def off_job():
    """End at 11:00pm PT"""
    print("STOPPING BREATHER")
    breather.shutdown()

if <REPLACE_END> <REPLACE_OLD> bottle_app = bottle.app()
    breather = breathe.Breathe()
    my_controller = controller.Controller(bottle_app, breather)
 <REPLACE_NEW> scheduler.start()
 <REPLACE_END> <|endoftext|> import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler

bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, None)

@scheduler.scheduled_job(trigger='cron', hour=21, minute=0)
def on_job():
    """Start at 9:00pm PT"""
    print('STARTING BREATHER')
    breather.restart()

@scheduler.scheduled_job(trigger='cron', hour=23, minute=0)
def off_job():
    """End at 11:00pm PT"""
    print("STOPPING BREATHER")
    breather.shutdown()

if __name__ == '__main__':
    scheduler.start()
    waitress.serve(bottle_app, host='0.0.0.0', port=7000)

Prompt:
Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm

import bottle
import waitress
import controller
import breathe

if __name__ == '__main__':
    bottle_app = bottle.app()
    breather = breathe.Breathe()
    my_controller = controller.Controller(bottle_app, breather)
    waitress.serve(bottle_app, host='0.0.0.0', port=7000)


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

from django.db import migrations
from django.db import models

class Migration(migrations.Migration):
    atomic=False

    dependencies = [
        ('meinberlin_documents', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='Document',
            new_name='Chapter',
        ),
        migrations.RenameField(
            model_name='paragraph',
            old_name='document',
            new_name='chapter',
        ),
    ]

Work around a migration issue in sqlite

Response:
<REPLACE_OLD> Migration(migrations.Migration):

 <REPLACE_NEW> Migration(migrations.Migration):
    atomic=False

 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations
from django.db import models

class Migration(migrations.Migration):
    atomic=False

    dependencies = [
        ('meinberlin_documents', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='Document',
            new_name='Chapter',
        ),
        migrations.RenameField(
            model_name='paragraph',
            old_name='document',
            new_name='chapter',
        ),
    ]

Prompt:
apps/documents: Work around a migration issue in sqlite

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

from django.db import migrations
from django.db import models

class Migration(migrations.Migration):

    dependencies = [
        ('meinberlin_documents', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='Document',
            new_name='Chapter',
        ),
        migrations.RenameField(
            model_name='paragraph',
            old_name='document',
            new_name='chapter',
        ),
    ]


"""Python Bindings for Psynteract.

"""

# This is built on the demo package as described at
# https://packaging.python.org/en/latest/distributing.html

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='Psynteract',

    # Versions should comply with PEP440.  For a discussion on single-sourcing
    # the version across setup.py and the project code, see
    # https://packaging.python.org/en/latest/single_source_version.html
    version='0.6.1',

    description='Psynteract Python bindings',
    long_description=long_description,

    # The project's main homepage.
    url='https://github.com/psynteract/psynteract-py',

    # Author details
    author='Felix Henninger & Pascal Kieslich',
    author_email='mailbox@felixhenninger.com',

    # Choose your license
    license='Apache 2.0',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 4 - Beta',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',

        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: Apache 2.0',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    # List run-time dependencies here.  These will be installed by pip when
    # your project is installed. For an analysis of "install_requires" vs pip's
    # requirements files see:
    # https://packaging.python.org/en/latest/requirements.html
    install_requires=['requests', 'pycouchdb'],
)

Add tentative support for installation via pip

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Python Bindings for Psynteract.

"""

# This is built on the demo package as described at
# https://packaging.python.org/en/latest/distributing.html

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='Psynteract',

    # Versions should comply with PEP440.  For a discussion on single-sourcing
    # the version across setup.py and the project code, see
    # https://packaging.python.org/en/latest/single_source_version.html
    version='0.6.1',

    description='Psynteract Python bindings',
    long_description=long_description,

    # The project's main homepage.
    url='https://github.com/psynteract/psynteract-py',

    # Author details
    author='Felix Henninger & Pascal Kieslich',
    author_email='mailbox@felixhenninger.com',

    # Choose your license
    license='Apache 2.0',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 4 - Beta',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',

        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: Apache 2.0',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    # List run-time dependencies here.  These will be installed by pip when
    # your project is installed. For an analysis of "install_requires" vs pip's
    # requirements files see:
    # https://packaging.python.org/en/latest/requirements.html
    install_requires=['requests', 'pycouchdb'],
)
 <REPLACE_END> <|endoftext|> """Python Bindings for Psynteract.

"""

# This is built on the demo package as described at
# https://packaging.python.org/en/latest/distributing.html

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='Psynteract',

    # Versions should comply with PEP440.  For a discussion on single-sourcing
    # the version across setup.py and the project code, see
    # https://packaging.python.org/en/latest/single_source_version.html
    version='0.6.1',

    description='Psynteract Python bindings',
    long_description=long_description,

    # The project's main homepage.
    url='https://github.com/psynteract/psynteract-py',

    # Author details
    author='Felix Henninger & Pascal Kieslich',
    author_email='mailbox@felixhenninger.com',

    # Choose your license
    license='Apache 2.0',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 4 - Beta',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',

        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: Apache 2.0',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    # List run-time dependencies here.  These will be installed by pip when
    # your project is installed. For an analysis of "install_requires" vs pip's
    # requirements files see:
    # https://packaging.python.org/en/latest/requirements.html
    install_requires=['requests', 'pycouchdb'],
)

Prompt: Add tentative support for installation via pip


from flask import render_template
from app.main import main

@main.app_errorhandler(400)
def page_not_found(e):
    print(e.message)
    return _render_error_page(500)

@main.app_errorhandler(404)
def page_not_found(e):
    print(e.message)
    return _render_error_page(404)

@main.app_errorhandler(500)
def exception(e):
    print(e.message)
    return _render_error_page(500)

@main.app_errorhandler(503)
def service_unavailable(e):
    print(e.message)
    return _render_error_page(503)

def _render_error_page(status_code):
    template_map = {
        404: "errors/404.html",
        500: "errors/500.html",
        503: "errors/500.html",
    }
    if status_code not in template_map:
        status_code = 500
    template_data = main.config['BASE_TEMPLATE_DATA']
    return render_template(template_map[status_code], **template_data), status_code

Response:
<INSERT> print(e.message)
    <INSERT_END> <INSERT>    print(e.message)
 <INSERT_END> <INSERT> print(e.message)
    <INSERT_END> <INSERT>    print(e.message)
 <INSERT_END> <|endoftext|> from flask import render_template
from app.main import main

@main.app_errorhandler(400)
def page_not_found(e):
    print(e.message)
    return _render_error_page(500)

@main.app_errorhandler(404)
def page_not_found(e):
    print(e.message)
    return _render_error_page(404)

@main.app_errorhandler(500)
def exception(e):
    print(e.message)
    return _render_error_page(500)

@main.app_errorhandler(503)
def service_unavailable(e):
    print(e.message)
    return _render_error_page(503)

def _render_error_page(status_code):
    template_map = {
        404: "errors/404.html",
        500: "errors/500.html",
        503: "errors/500.html",
    }
    if status_code not in template_map:
        status_code = 500
    template_data = main.config['BASE_TEMPLATE_DATA']
    return render_template(template_map[status_code], **template_data), status_code

Prompt:
Add print statements for all error types

from flask import render_template
from app.main import main

@main.app_errorhandler(400)
def page_not_found(e):
    return _render_error_page(500)

@main.app_errorhandler(404)
def page_not_found(e):
    return _render_error_page(404)

@main.app_errorhandler(500)
def exception(e):
    return _render_error_page(500)

@main.app_errorhandler(503)
def service_unavailable(e):
    return _render_error_page(503)

def _render_error_page(status_code):
    template_map = {
        404: "errors/404.html",
        500: "errors/500.html",
        503: "errors/500.html",
    }
    if status_code not in template_map:
        status_code = 500
    template_data = main.config['BASE_TEMPLATE_DATA']
    return render_template(template_map[status_code], **template_data), status_code


from setuptools import setup

PACKAGE_VERSION = '1.0.1'
deps = []

setup(name='wptserve',
      version=PACKAGE_VERSION,
      description="Python webserver intended for in web browser testing",
      long_description=open("README.md").read(),
      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=["Development Status :: 5 - Production/Stable",
                   "License :: OSI Approved :: BSD License",
                   "Topic :: Internet :: WWW/HTTP :: HTTP Servers"],
      keywords='',
      author='James Graham',
      author_email='james@hoppipolla.co.uk',
      url='http://wptserve.readthedocs.org/',
      license='BSD',
      packages=['wptserve'],
      include_package_data=True,
      zip_safe=False,
      install_requires=deps
      )

Update the version for manifest update

Update the version for manifest update

Response:
<REPLACE_OLD> '1.0'
deps <REPLACE_NEW> '1.0.1'
deps <REPLACE_END> <|endoftext|> from setuptools import setup

PACKAGE_VERSION = '1.0.1'
deps = []

setup(name='wptserve',
      version=PACKAGE_VERSION,
      description="Python webserver intended for in web browser testing",
      long_description=open("README.md").read(),
      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=["Development Status :: 5 - Production/Stable",
                   "License :: OSI Approved :: BSD License",
                   "Topic :: Internet :: WWW/HTTP :: HTTP Servers"],
      keywords='',
      author='James Graham',
      author_email='james@hoppipolla.co.uk',
      url='http://wptserve.readthedocs.org/',
      license='BSD',
      packages=['wptserve'],
      include_package_data=True,
      zip_safe=False,
      install_requires=deps
      )

Prompt:
Update the version for manifest update

from setuptools import setup

PACKAGE_VERSION = '1.0'
deps = []

setup(name='wptserve',
      version=PACKAGE_VERSION,
      description="Python webserver intended for in web browser testing",
      long_description=open("README.md").read(),
      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=["Development Status :: 5 - Production/Stable",
                   "License :: OSI Approved :: BSD License",
                   "Topic :: Internet :: WWW/HTTP :: HTTP Servers"],
      keywords='',
      author='James Graham',
      author_email='james@hoppipolla.co.uk',
      url='http://wptserve.readthedocs.org/',
      license='BSD',
      packages=['wptserve'],
      include_package_data=True,
      zip_safe=False,
      install_requires=deps
      )


"""
A collection of Django extensions that add content-management facilities to Django projects.

Developed by Dave Hall.

<http://etianen.com/>
"""

VERSION = (1, 8)

Bump version number for release.

Bump version number for release.

Response:
<REPLACE_OLD> 7, 11)
 <REPLACE_NEW> 8)
 <REPLACE_END> <|endoftext|> """
A collection of Django extensions that add content-management facilities to Django projects.

Developed by Dave Hall.

<http://etianen.com/>
"""

VERSION = (1, 8)

Prompt:
Bump version number for release.

"""
A collection of Django extensions that add content-management facilities to Django projects.

Developed by Dave Hall.

<http://etianen.com/>
"""

VERSION = (1, 7, 11)


from flask.ext.restful import Resource, marshal, reqparse

class BasicResource(Resource):

    def __init__(self):
        super(BasicResource, self).__init__()
        self.parser = reqparse.RequestParser()

    def response(self, data, code):
        return marshal(data, self.fields), code

Add parser to basic resource

Add parser to basic resource

Response:
<REPLACE_OLD> marshal

class <REPLACE_NEW> marshal, reqparse

class <REPLACE_END> <REPLACE_OLD> self).__init__()

 <REPLACE_NEW> self).__init__()
        self.parser = reqparse.RequestParser()

 <REPLACE_END> <|endoftext|> from flask.ext.restful import Resource, marshal, reqparse

class BasicResource(Resource):

    def __init__(self):
        super(BasicResource, self).__init__()
        self.parser = reqparse.RequestParser()

    def response(self, data, code):
        return marshal(data, self.fields), code

Prompt:
Add parser to basic resource

from flask.ext.restful import Resource, marshal

class BasicResource(Resource):

    def __init__(self):
        super(BasicResource, self).__init__()

    def response(self, data, code):
        return marshal(data, self.fields), code


from django.http import HttpResponse
from django.template import loader
from django.utils.crypto import salted_hmac, constant_time_compare

from django.contrib.auth.models import User

class HMACAuth(object):

    def __init__(self, realm='API'):
        self.realm = realm

    def process_request(self, request):
        user_id = request.META.get('HTTP_X_LA_USER_ID', None)
        signature = request.META.get('HTTP_X_LA_HASH', None)
        return user_id, signature

    def is_authenticated(self, request):
        user_id, signature = self.process_request(request)

        if user_id and signature:
            check_digest = salted_hmac("linked_accounts.views.login", str(user_id)).hexdigest()
            if not constant_time_compare(signature, check_digest):
                return False

            try:
                user = User.objects.get(id=user_id)
                if user.is_active:
                    request.user = user
                    return True
            except User.DoesNotExist:
                pass

        return False

    def challenge(self):
        response = HttpResponse()
        response.status_code = 401

        tmpl = loader.render_to_string('linked_accounts/api_challenge.html')

        response.content = tmpl

        return response

    def __repr__(self):
        return u'<HMACAuth: realm=%s>' % self.realm

Response:
<INSERT>         return True
            <INSERT_END> <|endoftext|> from django.http import HttpResponse
from django.template import loader
from django.utils.crypto import salted_hmac, constant_time_compare

from django.contrib.auth.models import User

class HMACAuth(object):

    def __init__(self, realm='API'):
        self.realm = realm

    def process_request(self, request):
        user_id = request.META.get('HTTP_X_LA_USER_ID', None)
        signature = request.META.get('HTTP_X_LA_HASH', None)
        return user_id, signature

    def is_authenticated(self, request):
        user_id, signature = self.process_request(request)

        if user_id and signature:
            check_digest = salted_hmac("linked_accounts.views.login", str(user_id)).hexdigest()
            if not constant_time_compare(signature, check_digest):
                return False

            try:
                user = User.objects.get(id=user_id)
                if user.is_active:
                    request.user = user
                    return True
            except User.DoesNotExist:
                pass

        return False

    def challenge(self):
        response = HttpResponse()
        response.status_code = 401

        tmpl = loader.render_to_string('linked_accounts/api_challenge.html')

        response.content = tmpl

        return response

    def __repr__(self):
        return u'<HMACAuth: realm=%s>' % self.realm

Prompt:
Return is_authenticated true if we got user and it is active

from django.http import HttpResponse
from django.template import loader
from django.utils.crypto import salted_hmac, constant_time_compare

from django.contrib.auth.models import User

class HMACAuth(object):

    def __init__(self, realm='API'):
        self.realm = realm

    def process_request(self, request):
        user_id = request.META.get('HTTP_X_LA_USER_ID', None)
        signature = request.META.get('HTTP_X_LA_HASH', None)
        return user_id, signature

    def is_authenticated(self, request):
        user_id, signature = self.process_request(request)

        if user_id and signature:
            check_digest = salted_hmac("linked_accounts.views.login", str(user_id)).hexdigest()
            if not constant_time_compare(signature, check_digest):
                return False

            try:
                user = User.objects.get(id=user_id)
                if user.is_active:
                    request.user = user
            except User.DoesNotExist:
                pass

        return False

    def challenge(self):
        response = HttpResponse()
        response.status_code = 401

        tmpl = loader.render_to_string('linked_accounts/api_challenge.html')

        response.content = tmpl

        return response

    def __repr__(self):
        return u'<HMACAuth: realm=%s>' % self.realm


from sys import argv
from operator import itemgetter

if __name__ == "__main__":
    if (len(argv) != 3):
        print("Usage: " + argv[0] + " <input.svm> <output.svm>")
        print("Example:")
        print("input.svm:")
        print("1 24:1 12:1 55:1")
        print("0 84:1 82:1 15:1")
        print("...")
        print("output.svm:")
        print("1 12:1 24:1 55:1")
        print("0 15:1 82:1 84:1")
        print("...")
        exit(1)

    input = argv[1]
    output = argv[2]
    with open(input, "r") as f:
        for line in f:
            splits = line.split()
            target = splits[0]
            features = splits[1:]
            d = {int(a[0]):int(a[1]) for a in [feat.split(':') for feat in features]}
            dsorted = sorted(d.iteritems(), key=itemgetter(0), reverse=False)
            with open(output, "a") as g:
                g.write(target + ' ')
                for (i,j) in dsorted:
                    g.write(str(i)+':'+str(j)+' ')
                g.write('\n')

Add helper script to sort svmlight files by column keys.

Response:
<REPLACE_OLD>  <REPLACE_NEW> from sys import argv
from operator import itemgetter

if __name__ == "__main__":
    if (len(argv) != 3):
        print("Usage: " + argv[0] + " <input.svm> <output.svm>")
        print("Example:")
        print("input.svm:")
        print("1 24:1 12:1 55:1")
        print("0 84:1 82:1 15:1")
        print("...")
        print("output.svm:")
        print("1 12:1 24:1 55:1")
        print("0 15:1 82:1 84:1")
        print("...")
        exit(1)

    input = argv[1]
    output = argv[2]
    with open(input, "r") as f:
        for line in f:
            splits = line.split()
            target = splits[0]
            features = splits[1:]
            d = {int(a[0]):int(a[1]) for a in [feat.split(':') for feat in features]}
            dsorted = sorted(d.iteritems(), key=itemgetter(0), reverse=False)
            with open(output, "a") as g:
                g.write(target + ' ')
                for (i,j) in dsorted:
                    g.write(str(i)+':'+str(j)+' ')
                g.write('\n')
 <REPLACE_END> <|endoftext|> from sys import argv
from operator import itemgetter

if __name__ == "__main__":
    if (len(argv) != 3):
        print("Usage: " + argv[0] + " <input.svm> <output.svm>")
        print("Example:")
        print("input.svm:")
        print("1 24:1 12:1 55:1")
        print("0 84:1 82:1 15:1")
        print("...")
        print("output.svm:")
        print("1 12:1 24:1 55:1")
        print("0 15:1 82:1 84:1")
        print("...")
        exit(1)

    input = argv[1]
    output = argv[2]
    with open(input, "r") as f:
        for line in f:
            splits = line.split()
            target = splits[0]
            features = splits[1:]
            d = {int(a[0]):int(a[1]) for a in [feat.split(':') for feat in features]}
            dsorted = sorted(d.iteritems(), key=itemgetter(0), reverse=False)
            with open(output, "a") as g:
                g.write(target + ' ')
                for (i,j) in dsorted:
                    g.write(str(i)+':'+str(j)+' ')
                g.write('\n')

Prompt: Add helper script to sort svmlight files by column keys.


from logger import logger
from seriesly import Seriesly

from perfrunner.settings import StatsSettings

def main():
    s = Seriesly(StatsSettings.SERIESLY['host'])
    for db in s.list_dbs():
        logger.info('Compacting {}'.format(db))
        result = s[db].compact()
        logger.info('Compaction finished: {}'.format(result))

if __name__ == '__main__':
    main()

CBPS-210: Add a script for periodic compaction of Seriesly databases

Change-Id: I95123c116c0dcdce4b4df02974d2a9fdeaef55dc
Reviewed-on: http://review.couchbase.org/69249
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>

Response:
<INSERT> from logger import logger
from seriesly import Seriesly

from perfrunner.settings import StatsSettings

def main():
 <INSERT_END> <INSERT>   s = Seriesly(StatsSettings.SERIESLY['host'])
    for db in s.list_dbs():
        logger.info('Compacting {}'.format(db))
        result = s[db].compact()
        logger.info('Compaction finished: {}'.format(result))

if __name__ == '__main__':
    main()
 <INSERT_END> <|endoftext|> from logger import logger
from seriesly import Seriesly

from perfrunner.settings import StatsSettings

def main():
    s = Seriesly(StatsSettings.SERIESLY['host'])
    for db in s.list_dbs():
        logger.info('Compacting {}'.format(db))
        result = s[db].compact()
        logger.info('Compaction finished: {}'.format(result))

if __name__ == '__main__':
    main()

Prompt:
CBPS-210: Add a script for periodic compaction of Seriesly databases

Change-Id: I95123c116c0dcdce4b4df02974d2a9fdeaef55dc
Reviewed-on: http://review.couchbase.org/69249
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>


from mythril.laser.ethereum.transaction import execute_contract_creation
from mythril.ether import util
import mythril.laser.ethereum.svm as svm
from mythril.disassembler.disassembly import Disassembly
from datetime import datetime
from mythril.ether.soliditycontract import SolidityContract
import tests
from mythril.analysis.security import fire_lasers
from mythril.analysis.symbolic import SymExecWrapper

def test_create():
    contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))

    laser_evm = svm.LaserEVM({})

    laser_evm.time = datetime.now()
    execute_contract_creation(laser_evm, contract.creation_code)

    resulting_final_state = laser_evm.open_states[0]

    for address, created_account in resulting_final_state.accounts.items():
        created_account_code = created_account.code
        actual_code = Disassembly(contract.code)

        for i in range(len(created_account_code.instruction_list)):
            found_instruction = created_account_code.instruction_list[i]
            actual_instruction = actual_code.instruction_list[i]

            assert found_instruction['opcode'] == actual_instruction['opcode']

def test_sym_exec():
    contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))

    sym = SymExecWrapper(contract, address=(util.get_indexed_address(0)), strategy="dfs")
    issues = fire_lasers(sym)

    assert len(issues) != 0

Update test to reflect the refactor

Update test to reflect the refactor

Response:
<INSERT> from mythril.laser.ethereum.transaction <INSERT_END> <REPLACE_OLD> mythril.laser.ethereum.transaction as transaction
from <REPLACE_NEW> execute_contract_creation
from <REPLACE_END> <REPLACE_OLD> laser_evm.execute_contract_creation(contract.creation_code)

 <REPLACE_NEW> execute_contract_creation(laser_evm, contract.creation_code)

 <REPLACE_END> <|endoftext|> from mythril.laser.ethereum.transaction import execute_contract_creation
from mythril.ether import util
import mythril.laser.ethereum.svm as svm
from mythril.disassembler.disassembly import Disassembly
from datetime import datetime
from mythril.ether.soliditycontract import SolidityContract
import tests
from mythril.analysis.security import fire_lasers
from mythril.analysis.symbolic import SymExecWrapper

def test_create():
    contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))

    laser_evm = svm.LaserEVM({})

    laser_evm.time = datetime.now()
    execute_contract_creation(laser_evm, contract.creation_code)

    resulting_final_state = laser_evm.open_states[0]

    for address, created_account in resulting_final_state.accounts.items():
        created_account_code = created_account.code
        actual_code = Disassembly(contract.code)

        for i in range(len(created_account_code.instruction_list)):
            found_instruction = created_account_code.instruction_list[i]
            actual_instruction = actual_code.instruction_list[i]

            assert found_instruction['opcode'] == actual_instruction['opcode']

def test_sym_exec():
    contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))

    sym = SymExecWrapper(contract, address=(util.get_indexed_address(0)), strategy="dfs")
    issues = fire_lasers(sym)

    assert len(issues) != 0

Prompt:
Update test to reflect the refactor

import mythril.laser.ethereum.transaction as transaction
from mythril.ether import util
import mythril.laser.ethereum.svm as svm
from mythril.disassembler.disassembly import Disassembly
from datetime import datetime
from mythril.ether.soliditycontract import SolidityContract
import tests
from mythril.analysis.security import fire_lasers
from mythril.analysis.symbolic import SymExecWrapper

def test_create():
    contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))

    laser_evm = svm.LaserEVM({})

    laser_evm.time = datetime.now()
    laser_evm.execute_contract_creation(contract.creation_code)

    resulting_final_state = laser_evm.open_states[0]

    for address, created_account in resulting_final_state.accounts.items():
        created_account_code = created_account.code
        actual_code = Disassembly(contract.code)

        for i in range(len(created_account_code.instruction_list)):
            found_instruction = created_account_code.instruction_list[i]
            actual_instruction = actual_code.instruction_list[i]

            assert found_instruction['opcode'] == actual_instruction['opcode']

def test_sym_exec():
    contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))

    sym = SymExecWrapper(contract, address=(util.get_indexed_address(0)), strategy="dfs")
    issues = fire_lasers(sym)

    assert len(issues) != 0


Response:
<REPLACE_OLD> download All <REPLACE_NEW> download
All <REPLACE_END> <REPLACE_OLD> custom).
The <REPLACE_NEW> custom). The <REPLACE_END> <REPLACE_OLD> card information, <REPLACE_NEW> card
information, <REPLACE_END> <REPLACE_OLD> the
PAYEE <REPLACE_NEW> the PAYEE <REPLACE_END> <REPLACE_OLD> for an <REPLACE_NEW> for
an <REPLACE_END> <REPLACE_OLD> transactions identify <REPLACE_NEW> transactions
identify <REPLACE_END> <REPLACE_OLD> customer.
This <REPLACE_NEW> customer. This <REPLACE_END> <REPLACE_OLD> it exists, <REPLACE_NEW> it
exists, <REPLACE_END> <REPLACE_OLD> tr.get('customer_description') <REPLACE_NEW> tr.get('customer_description')
        <REPLACE_END> <REPLACE_OLD> 0 <REPLACE_NEW> 0
        <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.stripe
~~~~~~~~~~~~~~~~~~~~~~~~

Provides a mapping for transactions obtained via Stripe card processing

Note that Stripe provides a Default set of columns or you can download
All columns. (as well as custom). The Default set does not include card
information, so provides no appropriate value for the PAYEE field for
an anonymous transaction (missing a customer).
It's suggested the All Columns format be used if not all transactions
identify a customer. This mapping sets PAYEE to Customer Name if it
exists, otherwise Card Name (if provided)
"""
from __future__ import (
    absolute_import, division, print_function, unicode_literals)

from operator import itemgetter

mapping = {
    'has_header': True,
    'account': 'Stripe',
    'id': itemgetter('id'),
    'date': itemgetter('created'),
    'amount': itemgetter('amount'),
    'currency': itemgetter('currency'),
    'payee': lambda tr: tr.get('customer_description')
        if len(tr.get('customer_description')) > 0
        else tr.get('card_name', ""),
    'desc': itemgetter("description")
}

Prompt:
Fix lint line length warnings (blocking manage checks)

# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.stripe
~~~~~~~~~~~~~~~~~~~~~~~~

Provides a mapping for transactions obtained via Stripe card processing

Note that Stripe provides a Default set of columns or you can download All columns. (as well as custom).
The Default set does not include card information, so provides no appropriate value for the
PAYEE field for an anonymous transaction (missing a customer).
It's suggested the All Columns format be used if not all transactions identify a customer.
This mapping sets PAYEE to Customer Name if it exists, otherwise Card Name (if provided)
"""
from __future__ import (
    absolute_import, division, print_function, unicode_literals)

from operator import itemgetter

mapping = {
    'has_header': True,
    'account': 'Stripe',
    'id': itemgetter('id'),
    'date': itemgetter('created'),
    'amount': itemgetter('amount'),
    'currency': itemgetter('currency'),
    'payee': lambda tr: tr.get('customer_description') if len(tr.get('customer_description')) > 0 else tr.get('card_name', ""),
    'desc': itemgetter("description")
}