#!/usr/bin/env python
# Copyright (c) 2008-2010 ActiveState Corp.
# License: MIT (http://www.opensource.org/licenses/mit-license.php)

r"""A small Django app that provides template tags for Markdown using the
python-markdown2 library.

See <http://github.com/trentm/django-markdown-deux> for more info.
"""

__version_info__ = (1, 0, 2)
__version__ = '.'.join(map(str, __version_info__))
__author__ = "Trent Mick"

def markdown(text, style="default"):
    if not text:
        return ""
    import markdown2
    return markdown2.markdown(text, **get_style(style))

def get_style(style):
    from markdown_deux.conf import settings
    try:
        return settings.MARKDOWN_DEUX_STYLES[style]
    except KeyError:
        return settings.MARKDOWN_DEUX_STYLES.get("default",
            settings.MARKDOWN_DEUX_DEFAULT_STYLE)

Response:
<REPLACE_OLD> '1.0.1'
__author__ <REPLACE_NEW> '.'.join(map(str, __version_info__))
__author__ <REPLACE_END> <DELETE>    print "XXX markdown_deux.markdown(style=%r) -> %r" % (style, get_style(style))

 <DELETE_END> <|endoftext|> #!/usr/bin/env python
# Copyright (c) 2008-2010 ActiveState Corp.
# License: MIT (http://www.opensource.org/licenses/mit-license.php)

r"""A small Django app that provides template tags for Markdown using the
python-markdown2 library.

See <http://github.com/trentm/django-markdown-deux> for more info.
"""

__version_info__ = (1, 0, 2)
__version__ = '.'.join(map(str, __version_info__))
__author__ = "Trent Mick"

def markdown(text, style="default"):
    if not text:
        return ""
    import markdown2
    return markdown2.markdown(text, **get_style(style))

def get_style(style):
    from markdown_deux.conf import settings
    try:
        return settings.MARKDOWN_DEUX_STYLES[style]
    except KeyError:
        return settings.MARKDOWN_DEUX_STYLES.get("default",
            settings.MARKDOWN_DEUX_DEFAULT_STYLE)

Prompt:
Fix having ver info written twice (divergence). Makes "mk cut_a_release" ver update work.

#!/usr/bin/env python
# Copyright (c) 2008-2010 ActiveState Corp.
# License: MIT (http://www.opensource.org/licenses/mit-license.php)

r"""A small Django app that provides template tags for Markdown using the
python-markdown2 library.

See <http://github.com/trentm/django-markdown-deux> for more info.
"""

__version_info__ = (1, 0, 2)
__version__ = '1.0.1'
__author__ = "Trent Mick"

def markdown(text, style="default"):
    if not text:
        return ""
    import markdown2
    print "XXX markdown_deux.markdown(style=%r) -> %r" % (style, get_style(style))

    return markdown2.markdown(text, **get_style(style))

def get_style(style):
    from markdown_deux.conf import settings
    try:
        return settings.MARKDOWN_DEUX_STYLES[style]
    except KeyError:
        return settings.MARKDOWN_DEUX_STYLES.get("default",
            settings.MARKDOWN_DEUX_DEFAULT_STYLE)


Add response time distributions from GIS.

Response:
<INSERT> # A dictionary where the key is an fdid-state and the values are lognormal fits generated
# from response time gis data.

response_time_distributions = {
 <INSERT_END> <INSERT>   '37140-CA': (0.20611095226322063, -4.7357748161635111, 8.6850997083002905),
    '02072-FL': (0.34949627393777505, -2.1718657657665021, 6.6793162966144539),
    '06001-GA': (0.15516182334170464, -6.3713354004369327, 9.9123471434677057),
    '52000-HI': (0.30700916252422011, -2.4031329143522013, 6.1229794823087547),
    'CS931-IL': (0.081475834493098712, -13.457565905124984, 17.056736130299502),
    '25035-MA': (0.15505110429322835, -5.1587384739296791, 8.0864571571129122),
    '10302-SC': (0.34438549165942622, -2.0800726636847711, 5.6805249239718378),
    '51000-VA': (0.16621261785191671, -4.5177075520748833, 7.2698576034101752),
    '25009-OH': (0.25995846388218091, -3.390284958787158, 7.0896026268171362),
}

 <INSERT_END> <|endoftext|> # A dictionary where the key is an fdid-state and the values are lognormal fits generated
# from response time gis data.

response_time_distributions = {
    '37140-CA': (0.20611095226322063, -4.7357748161635111, 8.6850997083002905),
    '02072-FL': (0.34949627393777505, -2.1718657657665021, 6.6793162966144539),
    '06001-GA': (0.15516182334170464, -6.3713354004369327, 9.9123471434677057),
    '52000-HI': (0.30700916252422011, -2.4031329143522013, 6.1229794823087547),
    'CS931-IL': (0.081475834493098712, -13.457565905124984, 17.056736130299502),
    '25035-MA': (0.15505110429322835, -5.1587384739296791, 8.0864571571129122),
    '10302-SC': (0.34438549165942622, -2.0800726636847711, 5.6805249239718378),
    '51000-VA': (0.16621261785191671, -4.5177075520748833, 7.2698576034101752),
    '25009-OH': (0.25995846388218091, -3.390284958787158, 7.0896026268171362),
}

Prompt: Add response time distributions from GIS.


import unittest

from pylons import c, g

from ming.orm import ThreadLocalORMSession

from pyforge.tests import helpers
from pyforge.lib import helpers as h

class TestGitApp(unittest.TestCase):

    def setUp(self):
        helpers.setup_basic_test()
        helpers.setup_global_objects()
        h.set_context('test', 'src_git')
        ThreadLocalORMSession.flush_all()
        ThreadLocalORMSession.close_all()

    def test_templates(self):
        assert c.app.templates.endswith('forgegit/templates')

    def test_admin_menu(self):
        assert len(c.app.admin_menu()) == 1

    def test_uninstall(self):
        c.app.uninstall(c.project)
        assert g.mock_amq.pop('audit')
        g.mock_amq.setup_handlers()
        c.app.uninstall(c.project)
        g.mock_amq.handle_all()

Response:
<REPLACE_OLD> c.app.admin_menu() <REPLACE_NEW> len(c.app.admin_menu()) <REPLACE_END> <REPLACE_OLD> []

 <REPLACE_NEW> 1

 <REPLACE_END> <|endoftext|> import unittest

from pylons import c, g

from ming.orm import ThreadLocalORMSession

from pyforge.tests import helpers
from pyforge.lib import helpers as h

class TestGitApp(unittest.TestCase):

    def setUp(self):
        helpers.setup_basic_test()
        helpers.setup_global_objects()
        h.set_context('test', 'src_git')
        ThreadLocalORMSession.flush_all()
        ThreadLocalORMSession.close_all()

    def test_templates(self):
        assert c.app.templates.endswith('forgegit/templates')

    def test_admin_menu(self):
        assert len(c.app.admin_menu()) == 1

    def test_uninstall(self):
        c.app.uninstall(c.project)
        assert g.mock_amq.pop('audit')
        g.mock_amq.setup_handlers()
        c.app.uninstall(c.project)
        g.mock_amq.handle_all()

Prompt:
Update test to reflect changing git codebase

import unittest

from pylons import c, g

from ming.orm import ThreadLocalORMSession

from pyforge.tests import helpers
from pyforge.lib import helpers as h

class TestGitApp(unittest.TestCase):

    def setUp(self):
        helpers.setup_basic_test()
        helpers.setup_global_objects()
        h.set_context('test', 'src_git')
        ThreadLocalORMSession.flush_all()
        ThreadLocalORMSession.close_all()

    def test_templates(self):
        assert c.app.templates.endswith('forgegit/templates')

    def test_admin_menu(self):
        assert c.app.admin_menu() == []

    def test_uninstall(self):
        c.app.uninstall(c.project)
        assert g.mock_amq.pop('audit')
        g.mock_amq.setup_handlers()
        c.app.uninstall(c.project)
        g.mock_amq.handle_all()


from PyOpenWorm import *

class Plot(DataObject):
    """
    Object for storing plot data in PyOpenWorm.

    Must be instantiated with a 2D list of coordinates.
    """

    def __init__(self, data=False, *args, **kwargs):
        DataObject.__init__(self, **kwargs)
        Plot.DatatypeProperty('_data_string', self, multiple=False)

        if data:
            self.set_data(data)

    def _to_string(self, input_list):
        """
        Converts input_list to a string
        for serialized storage in PyOpenWorm.
        """
        return '|'.join([str(item) for item in input_list])

    def _to_list(self, input_string):
        """
        Converts from internal serlialized string
        to a 2D list.
        """
        out_list = []
        for pair_string in input_string.split('|'):
            pair_as_list = pair_string \
                .replace('[', '') \
                .replace(']', '') \
                .split(',')
            out_list.append(
                map(float, pair_as_list)
            )
        return out_list

    def set_data(self, data):
        """
        Set the data attribute, which is user-facing,
        as well as the serialized _data_string
        attribute, which is used for db storage.
        """
        try:
            # make sure we're dealing with a 2D list
            assert isinstance(data, list)
            assert isinstance(data[0], list)
            self._data_string(self._to_string(data))
            self.data = data
        except (AssertionError, IndexError):
            raise ValueError('Attribute "data" must be a 2D list of numbers.')

    def get_data(self):
        """
        Get the data stored for this plot.
        """
        if self._data_string():
            return self._to_list(self._data_string())
        else:
            raise AttributeError('You must call "set_data" first.')

Add data setter and getter for Plot

Add data setter and getter for Plot

Response:
<REPLACE_OLD> (isinstance(data, list)) and (isinstance(data[0], list)):
            # data is user-facing, _data_string is for db
            self._data_string(self._to_string(data))
            self.data = data
        else:
            raise ValueError('Plot must be instantiated with 2D list.')

 <REPLACE_NEW> data:
            self.set_data(data)

 <REPLACE_END> <INSERT>    def set_data(self, data):
        """
        Set the data attribute, which is user-facing,
        as well as the serialized _data_string
        attribute, which is used for db storage.
        """
        try:
            # make sure we're dealing with a 2D list
            assert isinstance(data, list)
            assert isinstance(data[0], list)
            self._data_string(self._to_string(data))
            self.data = data
        except (AssertionError, IndexError):
            raise ValueError('Attribute "data" must be a 2D list of numbers.')

    def get_data(self):
        """
        Get the data stored for this plot.
        """
        if self._data_string():
            return self._to_list(self._data_string())
        else:
            raise AttributeError('You must call "set_data" first.')
 <INSERT_END> <|endoftext|> from PyOpenWorm import *

class Plot(DataObject):
    """
    Object for storing plot data in PyOpenWorm.

    Must be instantiated with a 2D list of coordinates.
    """

    def __init__(self, data=False, *args, **kwargs):
        DataObject.__init__(self, **kwargs)
        Plot.DatatypeProperty('_data_string', self, multiple=False)

        if data:
            self.set_data(data)

    def _to_string(self, input_list):
        """
        Converts input_list to a string
        for serialized storage in PyOpenWorm.
        """
        return '|'.join([str(item) for item in input_list])

    def _to_list(self, input_string):
        """
        Converts from internal serlialized string
        to a 2D list.
        """
        out_list = []
        for pair_string in input_string.split('|'):
            pair_as_list = pair_string \
                .replace('[', '') \
                .replace(']', '') \
                .split(',')
            out_list.append(
                map(float, pair_as_list)
            )
        return out_list

    def set_data(self, data):
        """
        Set the data attribute, which is user-facing,
        as well as the serialized _data_string
        attribute, which is used for db storage.
        """
        try:
            # make sure we're dealing with a 2D list
            assert isinstance(data, list)
            assert isinstance(data[0], list)
            self._data_string(self._to_string(data))
            self.data = data
        except (AssertionError, IndexError):
            raise ValueError('Attribute "data" must be a 2D list of numbers.')

    def get_data(self):
        """
        Get the data stored for this plot.
        """
        if self._data_string():
            return self._to_list(self._data_string())
        else:
            raise AttributeError('You must call "set_data" first.')

Prompt:
Add data setter and getter for Plot

from PyOpenWorm import *

class Plot(DataObject):
    """
    Object for storing plot data in PyOpenWorm.

    Must be instantiated with a 2D list of coordinates.
    """

    def __init__(self, data=False, *args, **kwargs):
        DataObject.__init__(self, **kwargs)
        Plot.DatatypeProperty('_data_string', self, multiple=False)

        if (isinstance(data, list)) and (isinstance(data[0], list)):
            # data is user-facing, _data_string is for db
            self._data_string(self._to_string(data))
            self.data = data
        else:
            raise ValueError('Plot must be instantiated with 2D list.')

    def _to_string(self, input_list):
        """
        Converts input_list to a string
        for serialized storage in PyOpenWorm.
        """
        return '|'.join([str(item) for item in input_list])

    def _to_list(self, input_string):
        """
        Converts from internal serlialized string
        to a 2D list.
        """
        out_list = []
        for pair_string in input_string.split('|'):
            pair_as_list = pair_string \
                .replace('[', '') \
                .replace(']', '') \
                .split(',')
            out_list.append(
                map(float, pair_as_list)
            )
        return out_list


from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation

class AbstractType(SubclassWithMeta):

    def __init_subclass__(cls, *args, **kwargs):
        warn_deprecation(
            "Abstract type is deprecated, please use normal object inheritance instead.\n"
            "See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
        )
        super(AbstractType, cls).__init_subclass__(*args, **kwargs)

Response:
<REPLACE_OLD> https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
 <REPLACE_NEW> https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
 <REPLACE_END> <|endoftext|> from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation

class AbstractType(SubclassWithMeta):

    def __init_subclass__(cls, *args, **kwargs):
        warn_deprecation(
            "Abstract type is deprecated, please use normal object inheritance instead.\n"
            "See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
        )
        super(AbstractType, cls).__init_subclass__(*args, **kwargs)

Prompt:
Fix deprecations url in DeprecationWarning message.

from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation

class AbstractType(SubclassWithMeta):

    def __init_subclass__(cls, *args, **kwargs):
        warn_deprecation(
            "Abstract type is deprecated, please use normal object inheritance instead.\n"
            "See more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
        )
        super(AbstractType, cls).__init_subclass__(*args, **kwargs)


from core.models import *

def handle(slice):
	site_deployments = SiteDeployments.objects.all()
	site_deploy_lookup = defaultdict(list)
	for site_deployment in site_deployments:
		site_deploy_lookup[site_deployment.site].append(site_deployment.deployment)

	slice_deployments = SliceDeployments.objects.all()
	slice_deploy_lookup = defaultdict(list)
	for slice_deployment in slice_deployments:
		slice_deploy_lookup[slice_deployment.slice].append(slice_deployment.deployment)

	all_deployments = Deployment.objects.all()
	# slices are added to all deployments for now
	expected_deployments = all_deployments
	#expected_deployments = site_deploy_lookup[slice.site]
	for expected_deployment in expected_deployments:
		if slice not in slice_deploy_lookup or \
		   expected_deployment not in slice_deploy_lookup[slice]:
			sd = SliceDeployments(slice=slice, deployment=expected_deployment)
			sd.save()

Add new slices to all deployments

Policy: Add new slices to all deployments

Response:
<INSERT> from core.models import *

def handle(slice):
	site_deployments = SiteDeployments.objects.all()
	site_deploy_lookup = defaultdict(list)
	for site_deployment in site_deployments:
		site_deploy_lookup[site_deployment.site].append(site_deployment.deployment)

	slice_deployments = SliceDeployments.objects.all()
	slice_deploy_lookup = defaultdict(list)
	for slice_deployment in slice_deployments:
		slice_deploy_lookup[slice_deployment.slice].append(slice_deployment.deployment)

	all_deployments = Deployment.objects.all()
	# slices are added to all deployments for now
	expected_deployments = all_deployments
	#expected_deployments = site_deploy_lookup[slice.site]
	for expected_deployment in expected_deployments:
		if slice not in slice_deploy_lookup or \
		 <INSERT_END> <INSERT>  expected_deployment not in slice_deploy_lookup[slice]:
			sd = SliceDeployments(slice=slice, deployment=expected_deployment)
			sd.save()

 <INSERT_END> <|endoftext|> from core.models import *

def handle(slice):
	site_deployments = SiteDeployments.objects.all()
	site_deploy_lookup = defaultdict(list)
	for site_deployment in site_deployments:
		site_deploy_lookup[site_deployment.site].append(site_deployment.deployment)

	slice_deployments = SliceDeployments.objects.all()
	slice_deploy_lookup = defaultdict(list)
	for slice_deployment in slice_deployments:
		slice_deploy_lookup[slice_deployment.slice].append(slice_deployment.deployment)

	all_deployments = Deployment.objects.all()
	# slices are added to all deployments for now
	expected_deployments = all_deployments
	#expected_deployments = site_deploy_lookup[slice.site]
	for expected_deployment in expected_deployments:
		if slice not in slice_deploy_lookup or \
		   expected_deployment not in slice_deploy_lookup[slice]:
			sd = SliceDeployments(slice=slice, deployment=expected_deployment)
			sd.save()

Prompt: Policy: Add new slices to all deployments


```python

i = -1
sum = 0

one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

while i < 10:
	i += 1
	sum += one_to_ten[i]

print(sum)

```

**Make function!**
`like:`
```python
def sum(number):
    # .. TODO
    return 0
```

`I want to reuse this function, like:`
```python
one_to_ten = sum(range(1,11))
one_to_five = sum(range(1,6))
five_to_ten = sum(range(5,11))
```

Response:
<REPLACE_OLD> one_to_ten[i]

print(sum)

``` <REPLACE_NEW> one_to_ten[i]

print(sum)

```

**Make function!**
`like:`
```python
def sum(number):
    # .. TODO
    return 0
```

`I want to reuse this function, like:`
```python
one_to_ten = sum(range(1,11))
one_to_five = sum(range(1,6))
five_to_ten = sum(range(5,11))
```
 <REPLACE_END> <|endoftext|> ```python

i = -1
sum = 0

one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

while i < 10:
	i += 1
	sum += one_to_ten[i]

print(sum)

```

**Make function!**
`like:`
```python
def sum(number):
    # .. TODO
    return 0
```

`I want to reuse this function, like:`
```python
one_to_ten = sum(range(1,11))
one_to_five = sum(range(1,6))
five_to_ten = sum(range(5,11))
```

Prompt:
Make function! and Use 4 tabs, not 8 tabs.
```python

i = -1
sum = 0

one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

while i < 10:
	i += 1
	sum += one_to_ten[i]

print(sum)

```


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

import json
from junit_xml import TestSuite, TestCase

class JunitFormatter(object):

    def __init__(self, project_cfg, project_result):
        """Initialize the stuff"""
        self.testcases = {
            unicode(item["id"]): item for item in project_cfg["testcases"]
        }

        test_cases = []
        for case in project_result["results"]:
            tc = TestCase(
                u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
                elapsed_sec=case["duration_sec"]
            )
            if case["status"] == "failed":
                # Last error and first error message
                tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])

            test_cases.append(tc)

        self.test_suite = TestSuite(
            name=u"Project {0}".format(project_cfg["project_name"]),
            test_cases=test_cases
        )

    def to_file(self, filename):
        """
        Output project results to specified filename
        """
        with open(filename, 'w') as f:
            f.write(
                TestSuite.to_xml_string(
                    [self.test_suite], prettyprint=True, encoding="utf-8"
                ).encode("utf-8")
            )

Fix junit utf-8 output to file

Fix junit utf-8 output to file

Response:
<REPLACE_OLD> import <REPLACE_NEW> # -*- coding: utf-8 -*-

import <REPLACE_END> <REPLACE_OLD> str(item["id"]): <REPLACE_NEW> unicode(item["id"]): <REPLACE_END> <REPLACE_OLD> self.testcases[str(case["testcase_id"])]["name"],
 <REPLACE_NEW> u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
 <REPLACE_END> <REPLACE_OLD> name="Project <REPLACE_NEW> name=u"Project <REPLACE_END> <REPLACE_OLD> TestSuite.to_file(f, <REPLACE_NEW> f.write(
                TestSuite.to_xml_string(
                    <REPLACE_END> <REPLACE_OLD> prettyprint=True)
 <REPLACE_NEW> prettyprint=True, encoding="utf-8"
                ).encode("utf-8")
            )
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import json
from junit_xml import TestSuite, TestCase

class JunitFormatter(object):

    def __init__(self, project_cfg, project_result):
        """Initialize the stuff"""
        self.testcases = {
            unicode(item["id"]): item for item in project_cfg["testcases"]
        }

        test_cases = []
        for case in project_result["results"]:
            tc = TestCase(
                u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
                elapsed_sec=case["duration_sec"]
            )
            if case["status"] == "failed":
                # Last error and first error message
                tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])

            test_cases.append(tc)

        self.test_suite = TestSuite(
            name=u"Project {0}".format(project_cfg["project_name"]),
            test_cases=test_cases
        )

    def to_file(self, filename):
        """
        Output project results to specified filename
        """
        with open(filename, 'w') as f:
            f.write(
                TestSuite.to_xml_string(
                    [self.test_suite], prettyprint=True, encoding="utf-8"
                ).encode("utf-8")
            )

Prompt:
Fix junit utf-8 output to file

import json
from junit_xml import TestSuite, TestCase

class JunitFormatter(object):

    def __init__(self, project_cfg, project_result):
        """Initialize the stuff"""
        self.testcases = {
            str(item["id"]): item for item in project_cfg["testcases"]
        }

        test_cases = []
        for case in project_result["results"]:
            tc = TestCase(
                self.testcases[str(case["testcase_id"])]["name"],
                elapsed_sec=case["duration_sec"]
            )
            if case["status"] == "failed":
                # Last error and first error message
                tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])

            test_cases.append(tc)

        self.test_suite = TestSuite(
            name="Project {0}".format(project_cfg["project_name"]),
            test_cases=test_cases
        )

    def to_file(self, filename):
        """
        Output project results to specified filename
        """
        with open(filename, 'w') as f:
            TestSuite.to_file(f, [self.test_suite], prettyprint=True)


from setuptools import setup

setup(
    name="teamscale-client",
    version="3.2.0",
    author="Thomas Kinnen - CQSE GmbH",
    author_email="kinnen@cqse.eu",
    description=("A simple service client to interact with Teamscale's REST API."),
    license="Apache",
    keywords="rest api teamscale",
    url="https://github.com/cqse/teamscale-client-python",
    packages=['teamscale_client'],
    long_description="A simple service client to interact with Teamscale's REST API.",
    classifiers=[
        "Topic :: Utilities",
    ],
    install_requires=[
          'simplejson',
          'requests>=2.0',
          'jsonpickle'
    ],

    tests_require=[
          'pytest',
          'responses'
    ],
    setup_requires=["pytest-runner"]
)

Update Client Version to 3.2

Update Client Version to 3.2

Response:
<REPLACE_OLD> version="3.1.1",
 <REPLACE_NEW> version="3.2.0",
 <REPLACE_END> <|endoftext|> from setuptools import setup

setup(
    name="teamscale-client",
    version="3.2.0",
    author="Thomas Kinnen - CQSE GmbH",
    author_email="kinnen@cqse.eu",
    description=("A simple service client to interact with Teamscale's REST API."),
    license="Apache",
    keywords="rest api teamscale",
    url="https://github.com/cqse/teamscale-client-python",
    packages=['teamscale_client'],
    long_description="A simple service client to interact with Teamscale's REST API.",
    classifiers=[
        "Topic :: Utilities",
    ],
    install_requires=[
          'simplejson',
          'requests>=2.0',
          'jsonpickle'
    ],

    tests_require=[
          'pytest',
          'responses'
    ],
    setup_requires=["pytest-runner"]
)

Prompt:
Update Client Version to 3.2

from setuptools import setup

setup(
    name="teamscale-client",
    version="3.1.1",
    author="Thomas Kinnen - CQSE GmbH",
    author_email="kinnen@cqse.eu",
    description=("A simple service client to interact with Teamscale's REST API."),
    license="Apache",
    keywords="rest api teamscale",
    url="https://github.com/cqse/teamscale-client-python",
    packages=['teamscale_client'],
    long_description="A simple service client to interact with Teamscale's REST API.",
    classifiers=[
        "Topic :: Utilities",
    ],
    install_requires=[
          'simplejson',
          'requests>=2.0',
          'jsonpickle'
    ],

    tests_require=[
          'pytest',
          'responses'
    ],
    setup_requires=["pytest-runner"]
)


#!/usr/bin/env python

import platform

def amiss(logPrefix):
    global ignoreList
    foundSomething = False

    currentFile = file(logPrefix + "-err", "r")

    # map from (assertion message) to (true, if seen in the current file)
    seenInCurrentFile = {}

    for line in currentFile:
        line = line.strip("\x07").rstrip("\n")
        if (line.startswith("###!!!") and not (line in seenInCurrentFile)):
            seenInCurrentFile[line] = True
            if not (ignore(line)):
                print line
                foundSomething = True

    currentFile.close()

    return foundSomething

def getIgnores():

    global simpleIgnoreList
    ignoreFile = open("known_assertions.txt", "r")

    for line in ignoreFile:
        line = line.strip()
        if ((len(line) > 0) and not line.startswith("#")):
            mpi = line.find(", file ")  # assertions use this format
            if (mpi == -1):
                mpi = line.find(": file ")  # aborts use this format
            if (mpi == -1):
                simpleIgnoreList.append(line)
            else:
                twoPartIgnoreList.append((line[:mpi+7], localSlashes(line[mpi+7:])))

def localSlashes(s):
    if platform.system() in ('Windows', 'Microsoft'):
        return s.replace("\\", "/")
    return s

def ignore(assertion):
    global simpleIgnoreList
    for ig in simpleIgnoreList:
        if assertion.find(ig) != -1:
            return True
    for (part1, part2) in twoPartIgnoreList:
        if assertion.find(part1) != -1 and assertion.find(part2) != -1:
            return True
    return False

simpleIgnoreList = []
twoPartIgnoreList = []
getIgnores()
#print "detect_assertions is ready (ignoring %d strings without filenames and %d strings with filenames)" % (len(simpleIgnoreList), len(twoPartIgnoreList))

Response:
<REPLACE_OLD> python

def <REPLACE_NEW> python

import platform

def <REPLACE_END> <REPLACE_OLD> ignoreList
 <REPLACE_NEW> simpleIgnoreList
 <REPLACE_END> <REPLACE_OLD> ignoreList.append(line)

def ignore(assertion):

 <REPLACE_NEW> mpi = line.find(", file ")  # assertions use this format
            if (mpi == -1):
                mpi = line.find(": file ")  # aborts use this format
            if (mpi == -1):
                simpleIgnoreList.append(line)
            else:
                twoPartIgnoreList.append((line[:mpi+7], localSlashes(line[mpi+7:])))

def localSlashes(s):
    if platform.system() in ('Windows', 'Microsoft'):
        return s.replace("\\", "/")
    return s

def ignore(assertion):
 <REPLACE_END> <REPLACE_OLD> ignoreList
 <REPLACE_NEW> simpleIgnoreList
 <REPLACE_END> <REPLACE_OLD> ignoreList:
        if (assertion.find(ig) <REPLACE_NEW> simpleIgnoreList:
        if assertion.find(ig) <REPLACE_END> <REPLACE_OLD> -1):
 <REPLACE_NEW> -1:
 <REPLACE_END> <REPLACE_OLD> return False

ignoreList = []
getIgnores()
# print <REPLACE_NEW> for (part1, part2) in twoPartIgnoreList:
        if assertion.find(part1) != -1 and assertion.find(part2) != -1:
            return True
    return False

simpleIgnoreList = []
twoPartIgnoreList = []
getIgnores()
#print <REPLACE_END> <REPLACE_OLD> assertions)" <REPLACE_NEW> strings without filenames and %d strings with filenames)" <REPLACE_END> <REPLACE_OLD> len(ignoreList)
 <REPLACE_NEW> (len(simpleIgnoreList), len(twoPartIgnoreList))
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import platform

def amiss(logPrefix):
    global ignoreList
    foundSomething = False

    currentFile = file(logPrefix + "-err", "r")

    # map from (assertion message) to (true, if seen in the current file)
    seenInCurrentFile = {}

    for line in currentFile:
        line = line.strip("\x07").rstrip("\n")
        if (line.startswith("###!!!") and not (line in seenInCurrentFile)):
            seenInCurrentFile[line] = True
            if not (ignore(line)):
                print line
                foundSomething = True

    currentFile.close()

    return foundSomething

def getIgnores():

    global simpleIgnoreList
    ignoreFile = open("known_assertions.txt", "r")

    for line in ignoreFile:
        line = line.strip()
        if ((len(line) > 0) and not line.startswith("#")):
            mpi = line.find(", file ")  # assertions use this format
            if (mpi == -1):
                mpi = line.find(": file ")  # aborts use this format
            if (mpi == -1):
                simpleIgnoreList.append(line)
            else:
                twoPartIgnoreList.append((line[:mpi+7], localSlashes(line[mpi+7:])))

def localSlashes(s):
    if platform.system() in ('Windows', 'Microsoft'):
        return s.replace("\\", "/")
    return s

def ignore(assertion):
    global simpleIgnoreList
    for ig in simpleIgnoreList:
        if assertion.find(ig) != -1:
            return True
    for (part1, part2) in twoPartIgnoreList:
        if assertion.find(part1) != -1 and assertion.find(part2) != -1:
            return True
    return False

simpleIgnoreList = []
twoPartIgnoreList = []
getIgnores()
#print "detect_assertions is ready (ignoring %d strings without filenames and %d strings with filenames)" % (len(simpleIgnoreList), len(twoPartIgnoreList))

Prompt:
Make known_assertions.txt cross-machine and hopefully also cross-platform.

#!/usr/bin/env python

def amiss(logPrefix):
    global ignoreList
    foundSomething = False

    currentFile = file(logPrefix + "-err", "r")

    # map from (assertion message) to (true, if seen in the current file)
    seenInCurrentFile = {}

    for line in currentFile:
        line = line.strip("\x07").rstrip("\n")
        if (line.startswith("###!!!") and not (line in seenInCurrentFile)):
            seenInCurrentFile[line] = True
            if not (ignore(line)):
                print line
                foundSomething = True

    currentFile.close()

    return foundSomething

def getIgnores():

    global ignoreList
    ignoreFile = open("known_assertions.txt", "r")

    for line in ignoreFile:
        line = line.strip()
        if ((len(line) > 0) and not line.startswith("#")):
            ignoreList.append(line)

def ignore(assertion):

    global ignoreList
    for ig in ignoreList:
        if (assertion.find(ig) != -1):
            return True
    return False

ignoreList = []
getIgnores()
# print "detect_assertions is ready (ignoring %d assertions)" % len(ignoreList)


# Copyright (c) 2012 Michael Babich
# See LICENSE.txt or http://opensource.org/licenses/MIT

'''This submodule manages the database.
'''

from sqlalchemy import create_engine, MetaData
from avenue.database.tables import get_tables

LOCATION = 'sqlite:///:memory:'
# LOCATION = 'sqlite:////home/mbabich/foo.sqlite'

engine = create_engine(LOCATION, echo=False)
metadata = MetaData()
table = get_tables(metadata)
metadata.create_all(engine)
connection = engine.connect()

Switch back to in-memory sqlite.

Switch back to in-memory sqlite.

Response:
<REPLACE_OLD> get_tables

# <REPLACE_NEW> get_tables

LOCATION = 'sqlite:///:memory:'
# <REPLACE_END> <DELETE> = 'sqlite:///:memory:'
LOCATION <DELETE_END> <|endoftext|> # Copyright (c) 2012 Michael Babich
# See LICENSE.txt or http://opensource.org/licenses/MIT

'''This submodule manages the database.
'''

from sqlalchemy import create_engine, MetaData
from avenue.database.tables import get_tables

LOCATION = 'sqlite:///:memory:'
# LOCATION = 'sqlite:////home/mbabich/foo.sqlite'

engine = create_engine(LOCATION, echo=False)
metadata = MetaData()
table = get_tables(metadata)
metadata.create_all(engine)
connection = engine.connect()

Prompt:
Switch back to in-memory sqlite.

# Copyright (c) 2012 Michael Babich
# See LICENSE.txt or http://opensource.org/licenses/MIT

'''This submodule manages the database.
'''

from sqlalchemy import create_engine, MetaData
from avenue.database.tables import get_tables

# LOCATION = 'sqlite:///:memory:'
LOCATION = 'sqlite:////home/mbabich/foo.sqlite'

engine = create_engine(LOCATION, echo=False)
metadata = MetaData()
table = get_tables(metadata)
metadata.create_all(engine)
connection = engine.connect()


# This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.

# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.

DEBUG = False

# disable compression for tests that check javascript contents
COMPRESS_ENABLED = False

# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            },
    },

}

# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'derrida.common.solr_backend.RangeSolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/test-derrida',
        'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
    }
}

# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS

# secret key added as a travis build step

Response:
<REPLACE_OLD> 'haystack.backends.solr_backend.SolrEngine',
 <REPLACE_NEW> 'derrida.common.solr_backend.RangeSolrEngine',
 <REPLACE_END> <|endoftext|> # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.

# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.

DEBUG = False

# disable compression for tests that check javascript contents
COMPRESS_ENABLED = False

# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            },
    },

}

# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'derrida.common.solr_backend.RangeSolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/test-derrida',
        'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
    }
}

# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS

# secret key added as a travis build step

Prompt:
Update travis-ci settings to use local backend with range queries

# This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.

# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.

DEBUG = False

# disable compression for tests that check javascript contents
COMPRESS_ENABLED = False

# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            },
    },

}

# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/test-derrida',
        'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
    }
}

# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS

# secret key added as a travis build step


import os
from functools import wraps
from argparse import ArgumentParser
from fabric.context_managers import prefix

def cached_property(func):
    cach_attr = '_{0}'.format(func.__name__)

    @property
    def wrap(self):
        if not hasattr(self, cach_attr):
            value = func(self)
            if value is not None:
                setattr(self, cach_attr, value)
        return getattr(self, cach_attr, None)
    return wrap

def cli(*args, **kwargs):
    def decorator(func):
        class Parser(ArgumentParser):
            def handle(self, *args, **kwargs):
                try:
                    func(*args, **kwargs)
                except Exception, e:
                    self.error(e.message)

            # No catching of exceptions
            def handle_raw(self, *args, **kwargs):
                func(*args, **kwargs)

        return Parser(*args, **kwargs)
    return decorator

def virtualenv(path):
    "Wraps a function and prefixes the call with the virtualenv active."
    if path is None:
        activate = None
    else:
        activate = os.path.join(path, 'bin/activate')

    def decorator(func):
        @wraps(func)
        def inner(*args, **kwargs):
            if path is not None:
                with prefix('source {0}'.format(activate)):
                    return func(*args, **kwargs)
            else:
                return func(*args, **kwargs)
        return inner
    return decorator

Response:
<INSERT> return <INSERT_END> <INSERT> return <INSERT_END> <|endoftext|> import os
from functools import wraps
from argparse import ArgumentParser
from fabric.context_managers import prefix

def cached_property(func):
    cach_attr = '_{0}'.format(func.__name__)

    @property
    def wrap(self):
        if not hasattr(self, cach_attr):
            value = func(self)
            if value is not None:
                setattr(self, cach_attr, value)
        return getattr(self, cach_attr, None)
    return wrap

def cli(*args, **kwargs):
    def decorator(func):
        class Parser(ArgumentParser):
            def handle(self, *args, **kwargs):
                try:
                    func(*args, **kwargs)
                except Exception, e:
                    self.error(e.message)

            # No catching of exceptions
            def handle_raw(self, *args, **kwargs):
                func(*args, **kwargs)

        return Parser(*args, **kwargs)
    return decorator

def virtualenv(path):
    "Wraps a function and prefixes the call with the virtualenv active."
    if path is None:
        activate = None
    else:
        activate = os.path.join(path, 'bin/activate')

    def decorator(func):
        @wraps(func)
        def inner(*args, **kwargs):
            if path is not None:
                with prefix('source {0}'.format(activate)):
                    return func(*args, **kwargs)
            else:
                return func(*args, **kwargs)
        return inner
    return decorator

Prompt:
Return resulting object from decorated function if any

import os
from functools import wraps
from argparse import ArgumentParser
from fabric.context_managers import prefix

def cached_property(func):
    cach_attr = '_{0}'.format(func.__name__)

    @property
    def wrap(self):
        if not hasattr(self, cach_attr):
            value = func(self)
            if value is not None:
                setattr(self, cach_attr, value)
        return getattr(self, cach_attr, None)
    return wrap

def cli(*args, **kwargs):
    def decorator(func):
        class Parser(ArgumentParser):
            def handle(self, *args, **kwargs):
                try:
                    func(*args, **kwargs)
                except Exception, e:
                    self.error(e.message)

            # No catching of exceptions
            def handle_raw(self, *args, **kwargs):
                func(*args, **kwargs)

        return Parser(*args, **kwargs)
    return decorator

def virtualenv(path):
    "Wraps a function and prefixes the call with the virtualenv active."
    if path is None:
        activate = None
    else:
        activate = os.path.join(path, 'bin/activate')

    def decorator(func):
        @wraps(func)
        def inner(*args, **kwargs):
            if path is not None:
                with prefix('source {0}'.format(activate)):
                    func(*args, **kwargs)
            else:
                func(*args, **kwargs)
        return inner
    return decorator


import collections

from data import anagram_index
from spec.data.fixtures import tries
from spec.mamba import *

with description('anagram_index'):
  with before.all:
    words = collections.OrderedDict(tries.kitchen_sink_data())
    self.subject = anagram_index.AnagramIndex(words)

  with it('instantiates'):
    expect(len(self.subject)).to(be_above(0))

  with it('accepts pre-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('low'))

  with it('accepts anti-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('wlo'))

  with it('returns multiple matches'):
    expect(self.subject['snap']).to(equal(['snap', 'naps']))

Update anagram index spec data source.

Update anagram index spec data source.

Response:
<REPLACE_OLD> from <REPLACE_NEW> import collections

from <REPLACE_END> <REPLACE_OLD> anagram_index, warehouse
from <REPLACE_NEW> anagram_index
from spec.data.fixtures import tries
from <REPLACE_END> <INSERT> words = collections.OrderedDict(tries.kitchen_sink_data())
    <INSERT_END> <REPLACE_OLD> anagram_index.AnagramIndex(warehouse.get('/words/unigram'))

 <REPLACE_NEW> anagram_index.AnagramIndex(words)

 <REPLACE_END> <|endoftext|> import collections

from data import anagram_index
from spec.data.fixtures import tries
from spec.mamba import *

with description('anagram_index'):
  with before.all:
    words = collections.OrderedDict(tries.kitchen_sink_data())
    self.subject = anagram_index.AnagramIndex(words)

  with it('instantiates'):
    expect(len(self.subject)).to(be_above(0))

  with it('accepts pre-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('low'))

  with it('accepts anti-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('wlo'))

  with it('returns multiple matches'):
    expect(self.subject['snap']).to(equal(['snap', 'naps']))

Prompt:
Update anagram index spec data source.

from data import anagram_index, warehouse
from spec.mamba import *

with description('anagram_index'):
  with before.all:
    self.subject = anagram_index.AnagramIndex(warehouse.get('/words/unigram'))

  with it('instantiates'):
    expect(len(self.subject)).to(be_above(0))

  with it('accepts pre-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('low'))

  with it('accepts anti-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('wlo'))

  with it('returns multiple matches'):
    expect(self.subject['snap']).to(equal(['snap', 'naps']))


from telegram import Updater
import json
import os

def getToken():
    token = []
    if not os.path.exists(file_path):
        token.append(input('Insert Token here: '))
        with open('token.json', 'w') as f:
            json.dump(token, f)
    else:
        with open("token.json") as f:
            token = json.load(f)
    return token[0]

def echo(bot, update):
    '''
    Simple function that echos every received message back to the user.
    '''
    bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)

def main():
    token = getToken()
    print("Starting Bot...")

    # Start the Bot with the token
    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add the echo-Message Handler to the Dispatcher
    dispatcher.addTelegramMessageHandler(echo)

    # Make the bot listen for commands
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Response:
<INSERT> echo(bot, update):
    '''
    Simple function that echos every received message back to the user.
    '''
    bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)

def <INSERT_END> <REPLACE_OLD> print(token)

if <REPLACE_NEW> print("Starting Bot...")

    # Start the Bot with the token
    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add the echo-Message Handler to the Dispatcher
    dispatcher.addTelegramMessageHandler(echo)

    # Make the bot listen for commands
    updater.start_polling()
    updater.idle()

if <REPLACE_END> <|endoftext|> from telegram import Updater
import json
import os

def getToken():
    token = []
    if not os.path.exists(file_path):
        token.append(input('Insert Token here: '))
        with open('token.json', 'w') as f:
            json.dump(token, f)
    else:
        with open("token.json") as f:
            token = json.load(f)
    return token[0]

def echo(bot, update):
    '''
    Simple function that echos every received message back to the user.
    '''
    bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)

def main():
    token = getToken()
    print("Starting Bot...")

    # Start the Bot with the token
    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add the echo-Message Handler to the Dispatcher
    dispatcher.addTelegramMessageHandler(echo)

    # Make the bot listen for commands
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Prompt:
Add simple Echo function and Bot initialisation

from telegram import Updater
import json
import os

def getToken():
    token = []
    if not os.path.exists(file_path):
        token.append(input('Insert Token here: '))
        with open('token.json', 'w') as f:
            json.dump(token, f)
    else:
        with open("token.json") as f:
            token = json.load(f)
    return token[0]

def main():
    token = getToken()
    print(token)

if __name__ == '__main__':
    main()


from setuptools import setup, find_packages

setup(name='lightweight-rest-tester',
      version='1.4.0',
      description='A lightweight REST API testing framework.',
      url='https://github.com/ridibooks/lightweight-rest-tester',
      author='Jeehoon Yoo',
      author_email='jeehoon.yoo@ridi.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      install_requires=[
          'certifi==2017.4.17',
          'chardet==3.0.4',
          'idna==2.5',
          'jsonschema==2.6.0',
          'requests==2.18.1',
          'urllib3==1.21.1',
          'click==6.7',
      ],
      entry_points={
          'console_scripts': [
              'lw_rest_tester = rest_tester.command_line:main'
          ],
      })

Update the version to 1.4.0.

Update the version to 1.4.0.

Response:
<REPLACE_OLD> version='1.2.0',
 <REPLACE_NEW> version='1.4.0',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(name='lightweight-rest-tester',
      version='1.4.0',
      description='A lightweight REST API testing framework.',
      url='https://github.com/ridibooks/lightweight-rest-tester',
      author='Jeehoon Yoo',
      author_email='jeehoon.yoo@ridi.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      install_requires=[
          'certifi==2017.4.17',
          'chardet==3.0.4',
          'idna==2.5',
          'jsonschema==2.6.0',
          'requests==2.18.1',
          'urllib3==1.21.1',
          'click==6.7',
      ],
      entry_points={
          'console_scripts': [
              'lw_rest_tester = rest_tester.command_line:main'
          ],
      })

Prompt:
Update the version to 1.4.0.

from setuptools import setup, find_packages

setup(name='lightweight-rest-tester',
      version='1.2.0',
      description='A lightweight REST API testing framework.',
      url='https://github.com/ridibooks/lightweight-rest-tester',
      author='Jeehoon Yoo',
      author_email='jeehoon.yoo@ridi.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      install_requires=[
          'certifi==2017.4.17',
          'chardet==3.0.4',
          'idna==2.5',
          'jsonschema==2.6.0',
          'requests==2.18.1',
          'urllib3==1.21.1',
          'click==6.7',
      ],
      entry_points={
          'console_scripts': [
              'lw_rest_tester = rest_tester.command_line:main'
          ],
      })


import functools

from pkit.slot import get_slot_pool

def acquire(pool_name):
    """Actor's method decorator to auto-acquire a slot before execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                # Unix semaphores are acquired through sem_post and sem_wait
                # syscalls, which can potentially fail.
                slots_pool.acquire()
            except OSError:
                pass

            res = method(self, *args, **kwargs)
            return res
        return wrapper
    return decorator

def release(pool_name):
    """Actors method decorator to auto-release a used slot after execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                res = method(self, *args, **kwargs)
            except Exception:
                raise
            finally:
                try:
                    slots_pool.release()
                except OSError:
                    pass

            return res

        return wrapper
    return decorator

Fix slot release on method exception

Fix slot release on method exception

Response:
<REPLACE_OLD> get_slot_pool(pool_name)
 <REPLACE_NEW> get_slot_pool(pool_name)

            try:
     <REPLACE_END> <REPLACE_OLD> **kwargs)

 <REPLACE_NEW> **kwargs)
            except Exception:
                raise
            finally:
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> import functools

from pkit.slot import get_slot_pool

def acquire(pool_name):
    """Actor's method decorator to auto-acquire a slot before execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                # Unix semaphores are acquired through sem_post and sem_wait
                # syscalls, which can potentially fail.
                slots_pool.acquire()
            except OSError:
                pass

            res = method(self, *args, **kwargs)
            return res
        return wrapper
    return decorator

def release(pool_name):
    """Actors method decorator to auto-release a used slot after execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                res = method(self, *args, **kwargs)
            except Exception:
                raise
            finally:
                try:
                    slots_pool.release()
                except OSError:
                    pass

            return res

        return wrapper
    return decorator

Prompt:
Fix slot release on method exception

import functools

from pkit.slot import get_slot_pool

def acquire(pool_name):
    """Actor's method decorator to auto-acquire a slot before execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                # Unix semaphores are acquired through sem_post and sem_wait
                # syscalls, which can potentially fail.
                slots_pool.acquire()
            except OSError:
                pass

            res = method(self, *args, **kwargs)
            return res
        return wrapper
    return decorator

def release(pool_name):
    """Actors method decorator to auto-release a used slot after execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)
            res = method(self, *args, **kwargs)

            try:
                slots_pool.release()
            except OSError:
                pass

            return res

        return wrapper
    return decorator


from .exceptions import ApiError

# -----------------------------------------------------------------------------

class Related(object):
    def __init__(self, item_class=None, **kwargs):
        self._item_class = item_class
        self._resolvers = kwargs

    def resolve_related(self, data):
        for field_name, resolver in self._resolvers.items():
            value = data.get(field_name, None)
            if value is None:
                # If this field were required or non-nullable, the deserializer
                # would already have raised an exception.
                continue

            try:
                resolved = self.resolve_field(value, resolver)
            except ApiError as e:
                pointer = '/data/{}'.format(field_name)
                raise e.update({'source': {'pointer': pointer}})

            data[field_name] = resolved

        if self._item_class:
            return self._item_class(**data)

        return data

    def resolve_field(self, value, resolver):
        # marshmallow always uses lists here.
        many = isinstance(value, list)
        if many and not value:
            # As a tiny optimization, there's no need to resolve an empty list.
            return value

        if isinstance(resolver, Related):
            resolve_item = resolver.resolve_related
        else:
            resolve_item = resolver().resolve_related_item

        if many:
            return [resolve_item(item) for item in value]

        return resolve_item(value)

Fix variable names in Related

Fix variable names in Related

Response:
<REPLACE_OLD> self._view_classes <REPLACE_NEW> self._resolvers <REPLACE_END> <REPLACE_OLD> view_class <REPLACE_NEW> resolver <REPLACE_END> <REPLACE_OLD> self._view_classes.items():
 <REPLACE_NEW> self._resolvers.items():
 <REPLACE_END> <REPLACE_OLD> view_class)
 <REPLACE_NEW> resolver)
 <REPLACE_END> <REPLACE_OLD> view_class):
 <REPLACE_NEW> resolver):
 <REPLACE_END> <REPLACE_OLD> isinstance(view_class, <REPLACE_NEW> isinstance(resolver, <REPLACE_END> <REPLACE_OLD> # This is not actually a view class.
            resolver = view_class.resolve_related
 <REPLACE_NEW> resolve_item = resolver.resolve_related
 <REPLACE_END> <REPLACE_OLD> resolver = view_class().resolve_related_item

 <REPLACE_NEW> resolve_item = resolver().resolve_related_item

 <REPLACE_END> <REPLACE_OLD> [resolver(item) <REPLACE_NEW> [resolve_item(item) <REPLACE_END> <REPLACE_OLD> resolver(value)
 <REPLACE_NEW> resolve_item(value)
 <REPLACE_END> <|endoftext|> from .exceptions import ApiError

# -----------------------------------------------------------------------------

class Related(object):
    def __init__(self, item_class=None, **kwargs):
        self._item_class = item_class
        self._resolvers = kwargs

    def resolve_related(self, data):
        for field_name, resolver in self._resolvers.items():
            value = data.get(field_name, None)
            if value is None:
                # If this field were required or non-nullable, the deserializer
                # would already have raised an exception.
                continue

            try:
                resolved = self.resolve_field(value, resolver)
            except ApiError as e:
                pointer = '/data/{}'.format(field_name)
                raise e.update({'source': {'pointer': pointer}})

            data[field_name] = resolved

        if self._item_class:
            return self._item_class(**data)

        return data

    def resolve_field(self, value, resolver):
        # marshmallow always uses lists here.
        many = isinstance(value, list)
        if many and not value:
            # As a tiny optimization, there's no need to resolve an empty list.
            return value

        if isinstance(resolver, Related):
            resolve_item = resolver.resolve_related
        else:
            resolve_item = resolver().resolve_related_item

        if many:
            return [resolve_item(item) for item in value]

        return resolve_item(value)

Prompt:
Fix variable names in Related

from .exceptions import ApiError

# -----------------------------------------------------------------------------

class Related(object):
    def __init__(self, item_class=None, **kwargs):
        self._item_class = item_class
        self._view_classes = kwargs

    def resolve_related(self, data):
        for field_name, view_class in self._view_classes.items():
            value = data.get(field_name, None)
            if value is None:
                # If this field were required or non-nullable, the deserializer
                # would already have raised an exception.
                continue

            try:
                resolved = self.resolve_field(value, view_class)
            except ApiError as e:
                pointer = '/data/{}'.format(field_name)
                raise e.update({'source': {'pointer': pointer}})

            data[field_name] = resolved

        if self._item_class:
            return self._item_class(**data)

        return data

    def resolve_field(self, value, view_class):
        # marshmallow always uses lists here.
        many = isinstance(value, list)
        if many and not value:
            # As a tiny optimization, there's no need to resolve an empty list.
            return value

        if isinstance(view_class, Related):
            # This is not actually a view class.
            resolver = view_class.resolve_related
        else:
            resolver = view_class().resolve_related_item

        if many:
            return [resolver(item) for item in value]

        return resolver(value)


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

from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor

class DataScienceJobsSpider(CrawlSpider):
    log = getLogger(__name__)
    name = 'data-science-jobs'
    allowed_domains = ['www.data-science-jobs.com']
    start_urls = ['http://www.data-science-jobs.com']
    job_links = Rule(LinkExtractor(allow='detail\/'), callback='parse_job')
    pagination_links = Rule(LinkExtractor(allow='page=\d+'))
    rules = [job_links, pagination_links]

    def parse_job(self, response):
        self.log.info('Parsing %s', response.url)

Response:
<REPLACE_OLD> ['www.data-science-jobs.com', 'fonts.googleapis.com', 'jobs.lever.com']
 <REPLACE_NEW> ['www.data-science-jobs.com']
 <REPLACE_END> <REPLACE_OLD> ['http://www.data-science-jobs.com/']
    test = Rule(LinkExtractor(allow='family'), callback='parse')
    test2 = Rule(LinkExtractor(allow='comtravo'), callback='parse')
 <REPLACE_NEW> ['http://www.data-science-jobs.com']
 <REPLACE_END> <REPLACE_OLD> callback='parse')
 <REPLACE_NEW> callback='parse_job')
 <REPLACE_END> <REPLACE_OLD> Rule(LinkExtractor(allow='\?page=\d+'), callback='parse')
 <REPLACE_NEW> Rule(LinkExtractor(allow='page=\d+'))
 <REPLACE_END> <REPLACE_OLD> pagination_links, test, test2]
    response = None

 <REPLACE_NEW> pagination_links]

 <REPLACE_END> <REPLACE_OLD> parse(self, <REPLACE_NEW> parse_job(self, <REPLACE_END> <REPLACE_OLD> response.url)
 <REPLACE_NEW> response.url)

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

from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor

class DataScienceJobsSpider(CrawlSpider):
    log = getLogger(__name__)
    name = 'data-science-jobs'
    allowed_domains = ['www.data-science-jobs.com']
    start_urls = ['http://www.data-science-jobs.com']
    job_links = Rule(LinkExtractor(allow='detail\/'), callback='parse_job')
    pagination_links = Rule(LinkExtractor(allow='page=\d+'))
    rules = [job_links, pagination_links]

    def parse_job(self, response):
        self.log.info('Parsing %s', response.url)

Prompt:
Rename the parser function to parse_jobs.

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

from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor

class DataScienceJobsSpider(CrawlSpider):
    log = getLogger(__name__)
    name = 'data-science-jobs'
    allowed_domains = ['www.data-science-jobs.com', 'fonts.googleapis.com', 'jobs.lever.com']
    start_urls = ['http://www.data-science-jobs.com/']
    test = Rule(LinkExtractor(allow='family'), callback='parse')
    test2 = Rule(LinkExtractor(allow='comtravo'), callback='parse')
    job_links = Rule(LinkExtractor(allow='detail\/'), callback='parse')
    pagination_links = Rule(LinkExtractor(allow='\?page=\d+'), callback='parse')
    rules = [job_links, pagination_links, test, test2]
    response = None

    def parse(self, response):
        self.log.info('Parsing %s', response.url)


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        start, end = 0, 0
        q = [(root, 0, 0)]
        cd = -1
        m = 0
        for v, d, c in q:
            if d != cd:
                start, end = c, c
                cd = d
            else:
                end = c
            m = max(m, end - start + 1)
            if v.left:
                q.append((v.left, d + 1, c << 1))
            if v.right:
                q.append((v.right, d + 1, (c << 1) | 1))
        return m

Add py solution for 662. Maximum Width of Binary Tree

662. Maximum Width of Binary Tree: https://leetcode.com/problems/maximum-width-of-binary-tree/

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        start, end = 0, 0
        q = [(root, 0, 0)]
        cd = -1
        m = 0
        for v, d, c in q:
            if d != cd:
                start, end = c, c
                cd = d
            else:
                end = c
            m = max(m, end - start + 1)
            if v.left:
                q.append((v.left, d + 1, c << 1))
            if v.right:
                q.append((v.right, d + 1, (c << 1) | 1))
        return m

 <REPLACE_END> <|endoftext|> # Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        start, end = 0, 0
        q = [(root, 0, 0)]
        cd = -1
        m = 0
        for v, d, c in q:
            if d != cd:
                start, end = c, c
                cd = d
            else:
                end = c
            m = max(m, end - start + 1)
            if v.left:
                q.append((v.left, d + 1, c << 1))
            if v.right:
                q.append((v.right, d + 1, (c << 1) | 1))
        return m

Prompt:
Add py solution for 662. Maximum Width of Binary Tree

662. Maximum Width of Binary Tree: https://leetcode.com/problems/maximum-width-of-binary-tree/


import unittest
import os
from test.util import ykman_cli

@unittest.skipIf(
    os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class TestExternalLibraries(unittest.TestCase):

    def test_ykman_version(self):
        output = ykman_cli('-v')
        # Test that major version is 1 on all libs
        self.assertIn('libykpers 1', output)
        self.assertIn('libu2f-host 1', output)
        self.assertIn('libusb 1', output)

    def test_ykman_version_not_found(self):
        output = ykman_cli('-v')
        self.assertNotIn('not found!', output)
        self.assertNotIn('<pyusb backend missing>', output)

Response:
<REPLACE_OLD> unittest
from <REPLACE_NEW> unittest
import os
from <REPLACE_END> <REPLACE_OLD> ykman_cli

class <REPLACE_NEW> ykman_cli

@unittest.skipIf(
    os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class <REPLACE_END> <|endoftext|> import unittest
import os
from test.util import ykman_cli

@unittest.skipIf(
    os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class TestExternalLibraries(unittest.TestCase):

    def test_ykman_version(self):
        output = ykman_cli('-v')
        # Test that major version is 1 on all libs
        self.assertIn('libykpers 1', output)
        self.assertIn('libu2f-host 1', output)
        self.assertIn('libusb 1', output)

    def test_ykman_version_not_found(self):
        output = ykman_cli('-v')
        self.assertNotIn('not found!', output)
        self.assertNotIn('<pyusb backend missing>', output)

Prompt:
Revert "Don't check INTEGRATION_TESTS env var in external libs test"

This reverts commit 648d02fbfca79241a65902f6dd9a7a767a0f633d.

import unittest
from test.util import ykman_cli

class TestExternalLibraries(unittest.TestCase):

    def test_ykman_version(self):
        output = ykman_cli('-v')
        # Test that major version is 1 on all libs
        self.assertIn('libykpers 1', output)
        self.assertIn('libu2f-host 1', output)
        self.assertIn('libusb 1', output)

    def test_ykman_version_not_found(self):
        output = ykman_cli('-v')
        self.assertNotIn('not found!', output)
        self.assertNotIn('<pyusb backend missing>', output)


# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save

class DirtyFieldsMixin(object):
    def __init__(self, *args, **kwargs):
        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
        post_save.connect(reset_state, sender=self.__class__,
                            dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)
        reset_state(sender=self.__class__, instance=self)

    def _as_dict(self):
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields])

    def get_dirty_fields(self):
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

    def is_dirty(self):
        # in order to be dirty we need to have been saved at least once, so we
        # check for a primary key and we need our dirty fields to not be empty
        if not self.pk:
            return True
        return {} != self.get_dirty_fields()

def reset_state(sender, instance, **kwargs):
    instance._original_state = instance._as_dict()

Response:
<REPLACE_OLD> self._meta.local_fields if not f.rel])

 <REPLACE_NEW> self._meta.local_fields])

 <REPLACE_END> <|endoftext|> # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save

class DirtyFieldsMixin(object):
    def __init__(self, *args, **kwargs):
        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
        post_save.connect(reset_state, sender=self.__class__,
                            dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)
        reset_state(sender=self.__class__, instance=self)

    def _as_dict(self):
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields])

    def get_dirty_fields(self):
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

    def is_dirty(self):
        # in order to be dirty we need to have been saved at least once, so we
        # check for a primary key and we need our dirty fields to not be empty
        if not self.pk:
            return True
        return {} != self.get_dirty_fields()

def reset_state(sender, instance, **kwargs):
    instance._original_state = instance._as_dict()

Prompt:
Check primary keys for foreign key and one-to-one fields

# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save

class DirtyFieldsMixin(object):
    def __init__(self, *args, **kwargs):
        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
        post_save.connect(reset_state, sender=self.__class__,
                            dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)
        reset_state(sender=self.__class__, instance=self)

    def _as_dict(self):
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel])

    def get_dirty_fields(self):
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

    def is_dirty(self):
        # in order to be dirty we need to have been saved at least once, so we
        # check for a primary key and we need our dirty fields to not be empty
        if not self.pk:
            return True
        return {} != self.get_dirty_fields()

def reset_state(sender, instance, **kwargs):
    instance._original_state = instance._as_dict()


#!/usr/bin/env python

import socket, fcntl, sys

#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
   fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
   print 'An instance of this program is already running'
   sys.exit(0)

import Adafruit_CharLCD as LCD

lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)

listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

number_packets_received = 0

def print_lcd():
   lcd.clear()
   lcd.message('# of packets\nreceived: ' + str(number_packets_received))

if __name__ == '__main__':
   while True:
      print_lcd()
      print listener.recvfrom(7777)
      number_packets_received += 1

Fix header of Python file

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

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

import <REPLACE_END> <REPLACE_OLD> listener.recvfrom(7777), '\n', type(listener)
 <REPLACE_NEW> listener.recvfrom(7777)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import socket, fcntl, sys

#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
   fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
   print 'An instance of this program is already running'
   sys.exit(0)

import Adafruit_CharLCD as LCD

lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)

listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

number_packets_received = 0

def print_lcd():
   lcd.clear()
   lcd.message('# of packets\nreceived: ' + str(number_packets_received))

if __name__ == '__main__':
   while True:
      print_lcd()
      print listener.recvfrom(7777)
      number_packets_received += 1

Prompt:
Fix header of Python file

Now correctly points to the Python interpretor

#!/usr/bin/env/python

import socket, fcntl, sys

#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
   fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
   print 'An instance of this program is already running'
   sys.exit(0)

import Adafruit_CharLCD as LCD

lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)

listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

number_packets_received = 0

def print_lcd():
   lcd.clear()
   lcd.message('# of packets\nreceived: ' + str(number_packets_received))

if __name__ == '__main__':
   while True:
      print_lcd()
      print listener.recvfrom(7777), '\n', type(listener)
      number_packets_received += 1


""" Run this file to check your python installation.
"""
from os.path import dirname, join

HERE = dirname(__file__)

def test_import_pandas():
    import pandas

def test_pandas_version():
    import pandas
    version_found = pandas.__version__.split(".")
    version_found = tuple(int(num) for num in version_found)
    assert version_found > (0, 15)

def test_import_numpy():
    import numpy

def test_import_matplotlib():
    import matplotlib.pyplot as plt
    plt.figure
    plt.plot
    plt.legend
    plt.imshow

def test_import_statsmodels():
    import statsmodels as sm
    from statsmodels.formula.api import ols
    from statsmodels.tsa.ar_model import AR

def test_read_html():
    import pandas
    pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
                     "sea_levels", "Obtaining Tide Gauge Data.html"))

def test_scrape_web():
    import pandas as pd
    pd.read_html("http://en.wikipedia.org/wiki/World_population")

if __name__ == "__main__":
    import nose
    nose.run(defaultTest=__name__)

Response:
<REPLACE_OLD> installation.
"""

def <REPLACE_NEW> installation.
"""
from os.path import dirname, join

HERE = dirname(__file__)

def <REPLACE_END> <REPLACE_OLD> matplotlib

def <REPLACE_NEW> matplotlib.pyplot as plt
    plt.figure
    plt.plot
    plt.legend
    plt.imshow

def test_import_statsmodels():
    import statsmodels as sm
    from statsmodels.formula.api import ols
    from statsmodels.tsa.ar_model import AR

def test_read_html():
    import pandas
    pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
                     "sea_levels", "Obtaining Tide Gauge Data.html"))

def <REPLACE_END> <|endoftext|> """ Run this file to check your python installation.
"""
from os.path import dirname, join

HERE = dirname(__file__)

def test_import_pandas():
    import pandas

def test_pandas_version():
    import pandas
    version_found = pandas.__version__.split(".")
    version_found = tuple(int(num) for num in version_found)
    assert version_found > (0, 15)

def test_import_numpy():
    import numpy

def test_import_matplotlib():
    import matplotlib.pyplot as plt
    plt.figure
    plt.plot
    plt.legend
    plt.imshow

def test_import_statsmodels():
    import statsmodels as sm
    from statsmodels.formula.api import ols
    from statsmodels.tsa.ar_model import AR

def test_read_html():
    import pandas
    pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
                     "sea_levels", "Obtaining Tide Gauge Data.html"))

def test_scrape_web():
    import pandas as pd
    pd.read_html("http://en.wikipedia.org/wiki/World_population")

if __name__ == "__main__":
    import nose
    nose.run(defaultTest=__name__)

Prompt:
Add some more content in tests including with statsmodels.

""" Run this file to check your python installation.
"""

def test_import_pandas():
    import pandas

def test_pandas_version():
    import pandas
    version_found = pandas.__version__.split(".")
    version_found = tuple(int(num) for num in version_found)
    assert version_found > (0, 15)

def test_import_numpy():
    import numpy

def test_import_matplotlib():
    import matplotlib

def test_scrape_web():
    import pandas as pd
    pd.read_html("http://en.wikipedia.org/wiki/World_population")

if __name__ == "__main__":
    import nose
    nose.run(defaultTest=__name__)


from hash import HashTable
import io

words = []

with io.open('/usr/share/dict/words', 'r') as word_file:
    words = word_file.readlines()

def test_hash():
    t = HashTable()
    t.set('coffee', 'coffee')
    assert t.get('coffee') == 'coffee'

def test_duplicate_hash_val():
    t = HashTable()
    t.set('bob', 'bob')
    t.set('obb', 'obb')
    assert t.get('bob') == 'bob'
    assert t.get('obb') == 'obb'

def test_word_file():
    t = HashTable()
    for word in words:
        t.set(word, word)
    assert t.get(words[654]) == words[654]
    assert t.get(words[3541]) == words[3541]
    assert t.get(words[6541]) == words[6541]

Add tests for hash table

Add tests for hash table

Response:
<INSERT> from hash import HashTable
import io

words = []

with io.open('/usr/share/dict/words', 'r') as word_file:
 <INSERT_END> <INSERT>   words = word_file.readlines()

def test_hash():
    t = HashTable()
    t.set('coffee', 'coffee')
    assert t.get('coffee') == 'coffee'

def test_duplicate_hash_val():
    t = HashTable()
    t.set('bob', 'bob')
    t.set('obb', 'obb')
    assert t.get('bob') == 'bob'
    assert t.get('obb') == 'obb'

def test_word_file():
    t = HashTable()
    for word in words:
        t.set(word, word)
    assert t.get(words[654]) == words[654]
    assert t.get(words[3541]) == words[3541]
    assert t.get(words[6541]) == words[6541]
 <INSERT_END> <|endoftext|> from hash import HashTable
import io

words = []

with io.open('/usr/share/dict/words', 'r') as word_file:
    words = word_file.readlines()

def test_hash():
    t = HashTable()
    t.set('coffee', 'coffee')
    assert t.get('coffee') == 'coffee'

def test_duplicate_hash_val():
    t = HashTable()
    t.set('bob', 'bob')
    t.set('obb', 'obb')
    assert t.get('bob') == 'bob'
    assert t.get('obb') == 'obb'

def test_word_file():
    t = HashTable()
    for word in words:
        t.set(word, word)
    assert t.get(words[654]) == words[654]
    assert t.get(words[3541]) == words[3541]
    assert t.get(words[6541]) == words[6541]

Prompt: Add tests for hash table


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

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .ir import TranslatableTextNode

def gettext(s):
    return s

def extract(fileobj, keywords, comment_tags, options):
    '''Babel entry point that extracts translation strings from XML templates.
    '''
    from .xml_template import _Parser, _Compiler, expand
    source = fileobj.read()
    if isinstance(source, bytes):
        source = source.decode('utf-8')
    doc = _Parser(filename='<string>', source=source).parse()
    expand(doc)
    compiler = _Compiler(filename='<string>', doc=doc,
                         mode=options.get('mode', 'xml'),
                         is_fragment=options.get('is_fragment', False))
    ir = compiler.compile()
    for node in ir:
        if isinstance(node, TranslatableTextNode):
            if node.text.strip():
                for line in node.text.split('\n'):
                    yield (node.lineno, '_', line, [])

Fix issue with message extractor on Py2

Fix issue with message extractor on Py2

Response:
<INSERT> source = fileobj.read()
    if isinstance(source, bytes):
        source = source.decode('utf-8')
    <INSERT_END> <REPLACE_OLD> source=fileobj.read()).parse()
 <REPLACE_NEW> source=source).parse()
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .ir import TranslatableTextNode

def gettext(s):
    return s

def extract(fileobj, keywords, comment_tags, options):
    '''Babel entry point that extracts translation strings from XML templates.
    '''
    from .xml_template import _Parser, _Compiler, expand
    source = fileobj.read()
    if isinstance(source, bytes):
        source = source.decode('utf-8')
    doc = _Parser(filename='<string>', source=source).parse()
    expand(doc)
    compiler = _Compiler(filename='<string>', doc=doc,
                         mode=options.get('mode', 'xml'),
                         is_fragment=options.get('is_fragment', False))
    ir = compiler.compile()
    for node in ir:
        if isinstance(node, TranslatableTextNode):
            if node.text.strip():
                for line in node.text.split('\n'):
                    yield (node.lineno, '_', line, [])

Prompt:
Fix issue with message extractor on Py2

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

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .ir import TranslatableTextNode

def gettext(s):
    return s

def extract(fileobj, keywords, comment_tags, options):
    '''Babel entry point that extracts translation strings from XML templates.
    '''
    from .xml_template import _Parser, _Compiler, expand
    doc = _Parser(filename='<string>', source=fileobj.read()).parse()
    expand(doc)
    compiler = _Compiler(filename='<string>', doc=doc,
                         mode=options.get('mode', 'xml'),
                         is_fragment=options.get('is_fragment', False))
    ir = compiler.compile()
    for node in ir:
        if isinstance(node, TranslatableTextNode):
            if node.text.strip():
                for line in node.text.split('\n'):
                    yield (node.lineno, '_', line, [])


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

from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3  # noqa

class CustomThemeBase(ThemeBase):
    FROIDE_THEME = 'froide_theme.theme'

    SITE_NAME = "My Froide"
    SITE_EMAIL = "info@example.com"
    SITE_URL = 'http://localhost:8000'

    SECRET_URLS = {
        "admin": "admin",
    }

    @property
    def LOCALE_PATHS(self):
        return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), '..', "locale")
            )
        ]

class Dev(CustomThemeBase, Base):
    pass

class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
    pass

class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
    pass

try:
    from .local_settings import *  # noqa
except ImportError:
    pass

Response:
<REPLACE_OLD> -*-
from <REPLACE_NEW> -*-
import os

from <REPLACE_END> <REPLACE_OLD> }

class <REPLACE_NEW> }

    @property
    def LOCALE_PATHS(self):
        return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), '..', "locale")
            )
        ]

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

from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3  # noqa

class CustomThemeBase(ThemeBase):
    FROIDE_THEME = 'froide_theme.theme'

    SITE_NAME = "My Froide"
    SITE_EMAIL = "info@example.com"
    SITE_URL = 'http://localhost:8000'

    SECRET_URLS = {
        "admin": "admin",
    }

    @property
    def LOCALE_PATHS(self):
        return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), '..', "locale")
            )
        ]

class Dev(CustomThemeBase, Base):
    pass

class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
    pass

class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
    pass

try:
    from .local_settings import *  # noqa
except ImportError:
    pass

Prompt:
Add own locale directory to LOCALE_PATHS
# -*- coding: utf-8 -*-
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3  # noqa

class CustomThemeBase(ThemeBase):
    FROIDE_THEME = 'froide_theme.theme'

    SITE_NAME = "My Froide"
    SITE_EMAIL = "info@example.com"
    SITE_URL = 'http://localhost:8000'

    SECRET_URLS = {
        "admin": "admin",
    }

class Dev(CustomThemeBase, Base):
    pass

class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
    pass

class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
    pass

try:
    from .local_settings import *  # noqa
except ImportError:
    pass


# -*- coding: utf-8 -*-
import scrapy
import json

from locations.items import GeojsonPointItem

class SuperAmericaSpider(scrapy.Spider):
    name = "speedway"
    allowed_domains = ["www.speedway.com"]
    start_urls = (
        'https://www.speedway.com/GasPriceSearch',
    )

    def parse(self, response):
        yield scrapy.Request(
            'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
            callback=self.parse_search,
            method='POST',
            body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            }
        )

    def parse_search(self, response):
        data = json.loads(response.body_as_unicode())

        for store in data:
            properties = {
                'addr:full': store['address'],
                'addr:city': store['city'],
                'addr:state': store['state'],
                'addr:postcode': store['zip'],
                'phone': store['phoneNumber'],
                'ref': store['costCenterId'],
            }

            lon_lat = [
                store['longitude'],
                store['latitude'],
            ]

            yield GeojsonPointItem(
                properties=properties,
                lon_lat=lon_lat,
            )

Correct the name of the spider

Correct the name of the spider

Response:
<REPLACE_OLD> "superamerica"
 <REPLACE_NEW> "speedway"
 <REPLACE_END> <REPLACE_OLD> ["superamerica.com"]
 <REPLACE_NEW> ["www.speedway.com"]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import scrapy
import json

from locations.items import GeojsonPointItem

class SuperAmericaSpider(scrapy.Spider):
    name = "speedway"
    allowed_domains = ["www.speedway.com"]
    start_urls = (
        'https://www.speedway.com/GasPriceSearch',
    )

    def parse(self, response):
        yield scrapy.Request(
            'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
            callback=self.parse_search,
            method='POST',
            body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            }
        )

    def parse_search(self, response):
        data = json.loads(response.body_as_unicode())

        for store in data:
            properties = {
                'addr:full': store['address'],
                'addr:city': store['city'],
                'addr:state': store['state'],
                'addr:postcode': store['zip'],
                'phone': store['phoneNumber'],
                'ref': store['costCenterId'],
            }

            lon_lat = [
                store['longitude'],
                store['latitude'],
            ]

            yield GeojsonPointItem(
                properties=properties,
                lon_lat=lon_lat,
            )

Prompt:
Correct the name of the spider

# -*- coding: utf-8 -*-
import scrapy
import json

from locations.items import GeojsonPointItem

class SuperAmericaSpider(scrapy.Spider):
    name = "superamerica"
    allowed_domains = ["superamerica.com"]
    start_urls = (
        'https://www.speedway.com/GasPriceSearch',
    )

    def parse(self, response):
        yield scrapy.Request(
            'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
            callback=self.parse_search,
            method='POST',
            body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            }
        )

    def parse_search(self, response):
        data = json.loads(response.body_as_unicode())

        for store in data:
            properties = {
                'addr:full': store['address'],
                'addr:city': store['city'],
                'addr:state': store['state'],
                'addr:postcode': store['zip'],
                'phone': store['phoneNumber'],
                'ref': store['costCenterId'],
            }

            lon_lat = [
                store['longitude'],
                store['latitude'],
            ]

            yield GeojsonPointItem(
                properties=properties,
                lon_lat=lon_lat,
            )


#!/usr/bin/env python
#
# dials.util.__init__.py
#
#  Copyright (C) 2013 Diamond Light Source
#
#  Author: James Parkhurst
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division

class HalError(RuntimeError):
    def __init__(self, string=''):

        # Get the username
        try:
            from getpass import getuser
            username = getuser()
        except Exception:
            username = 'Dave'

        # Put in HAL error text.
        text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
            username, string)

        # Init base class
        RuntimeError.__init__(self, text)

def halraiser(e):
    ''' Function to re-raise an exception with a Hal message. '''
    import logging

    # Get the log and write the error to the log file
    log = logging.getLogger(__name__)
    log.error(e)

    # Get the username
    try:
        from getpass import getuser
        username = getuser()
    except Exception:
        username = 'Humanoid'

    # Put in HAL error text.
    text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)

    # Append to exception
    if len(e.args) == 0:
        e.args = (text,)
    elif len(e.args) == 1:
        e.args = (text + ' ' + e.args[0],)
    else:
        e.args = (text,) + e.args

    # Reraise the exception
    raise

Print out errors to log.

Print out errors to log.

Response:
<REPLACE_OLD> '''

 <REPLACE_NEW> '''
    import logging

    # Get the log and write the error to the log file
    log = logging.getLogger(__name__)
    log.error(e)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# dials.util.__init__.py
#
#  Copyright (C) 2013 Diamond Light Source
#
#  Author: James Parkhurst
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division

class HalError(RuntimeError):
    def __init__(self, string=''):

        # Get the username
        try:
            from getpass import getuser
            username = getuser()
        except Exception:
            username = 'Dave'

        # Put in HAL error text.
        text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
            username, string)

        # Init base class
        RuntimeError.__init__(self, text)

def halraiser(e):
    ''' Function to re-raise an exception with a Hal message. '''
    import logging

    # Get the log and write the error to the log file
    log = logging.getLogger(__name__)
    log.error(e)

    # Get the username
    try:
        from getpass import getuser
        username = getuser()
    except Exception:
        username = 'Humanoid'

    # Put in HAL error text.
    text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)

    # Append to exception
    if len(e.args) == 0:
        e.args = (text,)
    elif len(e.args) == 1:
        e.args = (text + ' ' + e.args[0],)
    else:
        e.args = (text,) + e.args

    # Reraise the exception
    raise

Prompt:
Print out errors to log.
#!/usr/bin/env python
#
# dials.util.__init__.py
#
#  Copyright (C) 2013 Diamond Light Source
#
#  Author: James Parkhurst
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division

class HalError(RuntimeError):
    def __init__(self, string=''):

        # Get the username
        try:
            from getpass import getuser
            username = getuser()
        except Exception:
            username = 'Dave'

        # Put in HAL error text.
        text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
            username, string)

        # Init base class
        RuntimeError.__init__(self, text)

def halraiser(e):
    ''' Function to re-raise an exception with a Hal message. '''

    # Get the username
    try:
        from getpass import getuser
        username = getuser()
    except Exception:
        username = 'Humanoid'

    # Put in HAL error text.
    text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)

    # Append to exception
    if len(e.args) == 0:
        e.args = (text,)
    elif len(e.args) == 1:
        e.args = (text + ' ' + e.args[0],)
    else:
        e.args = (text,) + e.args

    # Reraise the exception
    raise


def test_iris():
    from tsne import bh_sne
    from sklearn.datasets import load_iris

    iris = load_iris()

    X = iris.data
    y = iris.target

    X_2d = bh_sne(X)

Add test for iris, same as example notebook

Response:
<INSERT>
def test_iris():
 <INSERT_END> <INSERT>   from tsne import bh_sne
    from sklearn.datasets import load_iris

    iris = load_iris()

    X = iris.data
    y = iris.target

    X_2d = bh_sne(X)
 <INSERT_END> <|endoftext|>
def test_iris():
    from tsne import bh_sne
    from sklearn.datasets import load_iris

    iris = load_iris()

    X = iris.data
    y = iris.target

    X_2d = bh_sne(X)

Prompt: Add test for iris, same as example notebook