#!/usr/bin/env python3

'''
    Process two different streams in parallel,
    retrieving them from the module's scope
'''

import rx
import asyncio
from concurrent.futures import ThreadPoolExecutor
from functools import partial

import APIReaderTwitter as Twitter

try:
    import json
except ImportError:
    import simplejson as json

def is_not_delete(element):
    return not "delete" in element

def is_delete(element):
    return "delete" in element

def pretty_print(element):
    print(json.dumps(element, indent=4))

twitter_stream = rx.Observable.from_(Twitter.get_iterable())

deleted_stream = twitter_stream.filter(is_not_delete)
tweet_stream = twitter_stream.filter(is_delete)

def process_deleted():
    deleted_stream.subscribe(pretty_print)

def process_tweets():
    tweet_stream.subscribe(pretty_print)

if __name__ == "__main__":
    executor = ThreadPoolExecutor(2)
    loop = asyncio.get_event_loop()

    deleted = asyncio.async(loop.run_in_executor(executor, process_deleted))
    tweets  = asyncio.async(loop.run_in_executor(executor, process_tweets))

    loop.run_forever()

Add example of processing two different streams in separate threads retrieving the streams from the module's global scope.

Response:
<INSERT> #!/usr/bin/env python3

'''
 <INSERT_END> <INSERT>   Process two different streams in parallel,
    retrieving them from the module's scope
'''

import rx
import asyncio
from concurrent.futures import ThreadPoolExecutor
from functools import partial

import APIReaderTwitter as Twitter

try:
    import json
except ImportError:
    import simplejson as json

def is_not_delete(element):
    return not "delete" in element

def is_delete(element):
    return "delete" in element

def pretty_print(element):
    print(json.dumps(element, indent=4))

twitter_stream = rx.Observable.from_(Twitter.get_iterable())

deleted_stream = twitter_stream.filter(is_not_delete)
tweet_stream = twitter_stream.filter(is_delete)

def process_deleted():
    deleted_stream.subscribe(pretty_print)

def process_tweets():
    tweet_stream.subscribe(pretty_print)

if __name__ == "__main__":
    executor = ThreadPoolExecutor(2)
    loop = asyncio.get_event_loop()

    deleted = asyncio.async(loop.run_in_executor(executor, process_deleted))
    tweets  = asyncio.async(loop.run_in_executor(executor, process_tweets))

    loop.run_forever()
 <INSERT_END> <|endoftext|> #!/usr/bin/env python3

'''
    Process two different streams in parallel,
    retrieving them from the module's scope
'''

import rx
import asyncio
from concurrent.futures import ThreadPoolExecutor
from functools import partial

import APIReaderTwitter as Twitter

try:
    import json
except ImportError:
    import simplejson as json

def is_not_delete(element):
    return not "delete" in element

def is_delete(element):
    return "delete" in element

def pretty_print(element):
    print(json.dumps(element, indent=4))

twitter_stream = rx.Observable.from_(Twitter.get_iterable())

deleted_stream = twitter_stream.filter(is_not_delete)
tweet_stream = twitter_stream.filter(is_delete)

def process_deleted():
    deleted_stream.subscribe(pretty_print)

def process_tweets():
    tweet_stream.subscribe(pretty_print)

if __name__ == "__main__":
    executor = ThreadPoolExecutor(2)
    loop = asyncio.get_event_loop()

    deleted = asyncio.async(loop.run_in_executor(executor, process_deleted))
    tweets  = asyncio.async(loop.run_in_executor(executor, process_tweets))

    loop.run_forever()

Prompt:
Add example of processing two different streams in separate threads
retrieving the streams from the module's global scope.


from setuptools import setup, find_packages

with open('README.rst') as readme:
    long_description = ''.join(readme).strip()

setup(
    name='rsocks',
    version='0.3.3',
    author='Jiangge Zhang',
    author_email='tonyseek@gmail.com',
    description='A SOCKS reverse proxy server.',
    long_description=long_description,
    url='https://github.com/tonyseek/rsocks',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    packages=find_packages(),
    platforms=['Any'],
    install_requires=[
        'PySocks>=1.7.1,<1.8',
        'eventlet>=0.31,<0.34',
        'click>=3.3,<3.4',
        'toml.py>=0.1,<0.2',
        'six',
    ],
    entry_points={
        'console_scripts': [
            'rsocks=rsocks.cli:main',
        ],
    },
)

Response:
<INSERT> 3.10',
        'Programming Language :: Python :: <INSERT_END> <REPLACE_OLD> 'PySocks>=1.5,<1.6',
 <REPLACE_NEW> 'PySocks>=1.7.1,<1.8',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

with open('README.rst') as readme:
    long_description = ''.join(readme).strip()

setup(
    name='rsocks',
    version='0.3.3',
    author='Jiangge Zhang',
    author_email='tonyseek@gmail.com',
    description='A SOCKS reverse proxy server.',
    long_description=long_description,
    url='https://github.com/tonyseek/rsocks',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    packages=find_packages(),
    platforms=['Any'],
    install_requires=[
        'PySocks>=1.7.1,<1.8',
        'eventlet>=0.31,<0.34',
        'click>=3.3,<3.4',
        'toml.py>=0.1,<0.2',
        'six',
    ],
    entry_points={
        'console_scripts': [
            'rsocks=rsocks.cli:main',
        ],
    },
)

Prompt:
Upgrade PySocks to fix Python 3.10 compatbility

from setuptools import setup, find_packages

with open('README.rst') as readme:
    long_description = ''.join(readme).strip()

setup(
    name='rsocks',
    version='0.3.3',
    author='Jiangge Zhang',
    author_email='tonyseek@gmail.com',
    description='A SOCKS reverse proxy server.',
    long_description=long_description,
    url='https://github.com/tonyseek/rsocks',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    packages=find_packages(),
    platforms=['Any'],
    install_requires=[
        'PySocks>=1.5,<1.6',
        'eventlet>=0.31,<0.34',
        'click>=3.3,<3.4',
        'toml.py>=0.1,<0.2',
        'six',
    ],
    entry_points={
        'console_scripts': [
            'rsocks=rsocks.cli:main',
        ],
    },
)


#!/usr/bin/python
#Author: Scott T. Salesky
#Created: 12.6.2014
#Purpose: Collection of functions, routines to use
#Python for scientific work
#----------------------------------------------

Add function to read 3d direct access Fortran binary files into NumPy arrays.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/python
#Author: Scott T. Salesky
#Created: 12.6.2014
#Purpose: Collection of functions, routines to use
#Python for scientific work
#----------------------------------------------
 <REPLACE_END> <|endoftext|> #!/usr/bin/python
#Author: Scott T. Salesky
#Created: 12.6.2014
#Purpose: Collection of functions, routines to use
#Python for scientific work
#----------------------------------------------

Prompt: Add function to read 3d direct access Fortran binary files into NumPy arrays.


from models import Protein, Mutation
from database import get_or_create

class SearchResult:

    def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
        self.protein = protein
        self.mutation = mutation
        self.is_mutation_novel = is_mutation_novel
        self.type = type
        self.meta_user = None
        self.__dict__.update(kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()

        state['protein_refseq'] = self.protein.refseq
        del state['protein']

        state['mutation_kwargs'] = {
            'position': self.mutation.position,
            'alt': self.mutation.alt
        }
        del state['mutation']

        state['meta_user'].mutation = None

        return state

    def __setstate__(self, state):

        state['protein'] = Protein.query.filter_by(
            refseq=state['protein_refseq']
        ).one()
        del state['protein_refseq']

        state['mutation'], created = get_or_create(
            Mutation,
            protein=state['protein'],
            **state['mutation_kwargs']
        )
        del state['mutation_kwargs']

        state['meta_user'].mutation = state['mutation']
        state['mutation'].meta_user = state['meta_user']

        self.__dict__.update(state)

Fix result loading for novel mutations

Fix result loading for novel mutations

Response:
<REPLACE_OLD> Mutation

class <REPLACE_NEW> Mutation
from database import get_or_create

class <REPLACE_END> <REPLACE_OLD> state['mutation'] = Mutation.query.filter_by(
 <REPLACE_NEW> state['mutation'], created = get_or_create(
            Mutation,
 <REPLACE_END> <REPLACE_OLD> ).one()
 <REPLACE_NEW> )
 <REPLACE_END> <|endoftext|> from models import Protein, Mutation
from database import get_or_create

class SearchResult:

    def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
        self.protein = protein
        self.mutation = mutation
        self.is_mutation_novel = is_mutation_novel
        self.type = type
        self.meta_user = None
        self.__dict__.update(kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()

        state['protein_refseq'] = self.protein.refseq
        del state['protein']

        state['mutation_kwargs'] = {
            'position': self.mutation.position,
            'alt': self.mutation.alt
        }
        del state['mutation']

        state['meta_user'].mutation = None

        return state

    def __setstate__(self, state):

        state['protein'] = Protein.query.filter_by(
            refseq=state['protein_refseq']
        ).one()
        del state['protein_refseq']

        state['mutation'], created = get_or_create(
            Mutation,
            protein=state['protein'],
            **state['mutation_kwargs']
        )
        del state['mutation_kwargs']

        state['meta_user'].mutation = state['mutation']
        state['mutation'].meta_user = state['meta_user']

        self.__dict__.update(state)

Prompt:
Fix result loading for novel mutations

from models import Protein, Mutation

class SearchResult:

    def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
        self.protein = protein
        self.mutation = mutation
        self.is_mutation_novel = is_mutation_novel
        self.type = type
        self.meta_user = None
        self.__dict__.update(kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()

        state['protein_refseq'] = self.protein.refseq
        del state['protein']

        state['mutation_kwargs'] = {
            'position': self.mutation.position,
            'alt': self.mutation.alt
        }
        del state['mutation']

        state['meta_user'].mutation = None

        return state

    def __setstate__(self, state):

        state['protein'] = Protein.query.filter_by(
            refseq=state['protein_refseq']
        ).one()
        del state['protein_refseq']

        state['mutation'] = Mutation.query.filter_by(
            protein=state['protein'],
            **state['mutation_kwargs']
        ).one()
        del state['mutation_kwargs']

        state['meta_user'].mutation = state['mutation']
        state['mutation'].meta_user = state['meta_user']

        self.__dict__.update(state)


from traits.testing.unittest_tools import unittest

from traits.api import Float, HasTraits, Int, List

class Foo(HasTraits):
    x = Float

    y_changes = List

    def _y_changed(self, new):
        self.y_changes.append(new)

class TestDynamicTraitDefinition(unittest.TestCase):
    """ Test demonstrating special change events using the 'event' metadata.
    """

    def test_add_trait(self):
        foo = Foo(x=3)
        foo.add_trait('y', Int)

        self.assertTrue(hasattr(foo, 'y'))
        self.assertEqual(type(foo.y), int)

        foo.y = 4
        self.assertEqual(foo.y_changes, [4])

    def test_remove_trait(self):
        foo = Foo(x=3)

        # We can't remove a "statically" added trait (i.e., a trait defined
        # in the Foo class).
        result = foo.remove_trait('x')
        self.assertFalse(result)

        # We can remove dynamically added traits.
        foo.add_trait('y', Int)
        foo.y = 70

        result = foo.remove_trait('y')
        self.assertTrue(result)

        self.assertFalse(hasattr(foo, 'y'))
        foo.y = 10
        self.assertEqual(foo.y_changes, [70])

Response:
<DELETE> x_changes = List
    <DELETE_END> <DELETE>    def _x_changed(self, new):
        self.x_changes.append(new)

 <DELETE_END> <|endoftext|> from traits.testing.unittest_tools import unittest

from traits.api import Float, HasTraits, Int, List

class Foo(HasTraits):
    x = Float

    y_changes = List

    def _y_changed(self, new):
        self.y_changes.append(new)

class TestDynamicTraitDefinition(unittest.TestCase):
    """ Test demonstrating special change events using the 'event' metadata.
    """

    def test_add_trait(self):
        foo = Foo(x=3)
        foo.add_trait('y', Int)

        self.assertTrue(hasattr(foo, 'y'))
        self.assertEqual(type(foo.y), int)

        foo.y = 4
        self.assertEqual(foo.y_changes, [4])

    def test_remove_trait(self):
        foo = Foo(x=3)

        # We can't remove a "statically" added trait (i.e., a trait defined
        # in the Foo class).
        result = foo.remove_trait('x')
        self.assertFalse(result)

        # We can remove dynamically added traits.
        foo.add_trait('y', Int)
        foo.y = 70

        result = foo.remove_trait('y')
        self.assertTrue(result)

        self.assertFalse(hasattr(foo, 'y'))
        foo.y = 10
        self.assertEqual(foo.y_changes, [70])

Prompt:
Remove unused trait definitions in test.

from traits.testing.unittest_tools import unittest

from traits.api import Float, HasTraits, Int, List

class Foo(HasTraits):
    x = Float

    x_changes = List
    y_changes = List

    def _x_changed(self, new):
        self.x_changes.append(new)

    def _y_changed(self, new):
        self.y_changes.append(new)

class TestDynamicTraitDefinition(unittest.TestCase):
    """ Test demonstrating special change events using the 'event' metadata.
    """

    def test_add_trait(self):
        foo = Foo(x=3)
        foo.add_trait('y', Int)

        self.assertTrue(hasattr(foo, 'y'))
        self.assertEqual(type(foo.y), int)

        foo.y = 4
        self.assertEqual(foo.y_changes, [4])

    def test_remove_trait(self):
        foo = Foo(x=3)

        # We can't remove a "statically" added trait (i.e., a trait defined
        # in the Foo class).
        result = foo.remove_trait('x')
        self.assertFalse(result)

        # We can remove dynamically added traits.
        foo.add_trait('y', Int)
        foo.y = 70

        result = foo.remove_trait('y')
        self.assertTrue(result)

        self.assertFalse(hasattr(foo, 'y'))
        foo.y = 10
        self.assertEqual(foo.y_changes, [70])


"""
===========================================
Robust linear model estimation using RANSAC
===========================================

In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.

"""
import numpy as np
from matplotlib import pyplot as plt

from sklearn import linear_model
from sklearn.utils import ransac

# Set random seed for both equal data noise and equal random sample selection
np.random.seed(seed=1)

# Generate coordinates of line
X = np.arange(-200, 200)
y = 0.2 * X + 20
data = np.column_stack([X, y])

# Add faulty data
faulty = np.array(30 * [(180, -100)], dtype=np.double)
faulty += 5 * np.random.normal(size=faulty.shape)
data[:faulty.shape[0]] = faulty

# Add gaussian noise to coordinates
noise = np.random.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

X = data[:, 0][:, np.newaxis]
y = data[:, 1]

# Fit line using all data
model = linear_model.LinearRegression()
model.fit(X, y)

# Robustly fit linear model with RANSAC algorithm
model_robust = linear_model.LinearRegression()
inlier_mask = ransac(X, y, model_robust, min_n_samples=2, residual_threshold=2)
outlier_mask = ~inlier_mask

# Generate coordinates of estimated models
line_X = np.arange(-250, 250)
line_y = model.predict(line_X[:, np.newaxis])
line_y_robust = model_robust.predict(line_X[:, np.newaxis])

plt.plot(data[inlier_mask, 0], data[inlier_mask, 1], '.g',
         label='Inlier data')
plt.plot(data[outlier_mask, 0], data[outlier_mask, 1], '.r',
         label='Outlier data')
plt.plot(line_X, line_y, '-k', label='Linear model from all data')
plt.plot(line_X, line_y_robust, '-b', label='Robustly fitted linear model')
plt.legend(loc='lower left')
plt.show()

Add example plot script for RANSAC

Add example plot script for RANSAC

Response:
<INSERT> """
===========================================
Robust linear model estimation using RANSAC
===========================================

In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.

"""
import numpy as np
from matplotlib import pyplot as plt

from sklearn import linear_model
from sklearn.utils import ransac

# Set random seed for both equal data noise and equal random sample selection
np.random.seed(seed=1)

# Generate coordinates of line
X = np.arange(-200, 200)
y = 0.2 * X + 20
data = np.column_stack([X, y])

# Add faulty data
faulty = np.array(30 * [(180, -100)], dtype=np.double)
faulty += 5 * np.random.normal(size=faulty.shape)
data[:faulty.shape[0]] = faulty

# Add gaussian noise to coordinates
noise = np.random.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

X = data[:, 0][:, np.newaxis]
y = data[:, 1]

# Fit line using all data
model = linear_model.LinearRegression()
model.fit(X, y)

# Robustly fit linear model with RANSAC algorithm
model_robust = linear_model.LinearRegression()
inlier_mask = ransac(X, y, model_robust, min_n_samples=2, residual_threshold=2)
outlier_mask = ~inlier_mask

# Generate coordinates of estimated models
line_X = np.arange(-250, 250)
line_y = model.predict(line_X[:, np.newaxis])
line_y_robust = model_robust.predict(line_X[:, np.newaxis])

plt.plot(data[inlier_mask, 0], data[inlier_mask, 1], '.g',
 <INSERT_END> <INSERT>        label='Inlier data')
plt.plot(data[outlier_mask, 0], data[outlier_mask, 1], '.r',
         label='Outlier data')
plt.plot(line_X, line_y, '-k', label='Linear model from all data')
plt.plot(line_X, line_y_robust, '-b', label='Robustly fitted linear model')
plt.legend(loc='lower left')
plt.show()
 <INSERT_END> <|endoftext|> """
===========================================
Robust linear model estimation using RANSAC
===========================================

In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.

"""
import numpy as np
from matplotlib import pyplot as plt

from sklearn import linear_model
from sklearn.utils import ransac

# Set random seed for both equal data noise and equal random sample selection
np.random.seed(seed=1)

# Generate coordinates of line
X = np.arange(-200, 200)
y = 0.2 * X + 20
data = np.column_stack([X, y])

# Add faulty data
faulty = np.array(30 * [(180, -100)], dtype=np.double)
faulty += 5 * np.random.normal(size=faulty.shape)
data[:faulty.shape[0]] = faulty

# Add gaussian noise to coordinates
noise = np.random.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

X = data[:, 0][:, np.newaxis]
y = data[:, 1]

# Fit line using all data
model = linear_model.LinearRegression()
model.fit(X, y)

# Robustly fit linear model with RANSAC algorithm
model_robust = linear_model.LinearRegression()
inlier_mask = ransac(X, y, model_robust, min_n_samples=2, residual_threshold=2)
outlier_mask = ~inlier_mask

# Generate coordinates of estimated models
line_X = np.arange(-250, 250)
line_y = model.predict(line_X[:, np.newaxis])
line_y_robust = model_robust.predict(line_X[:, np.newaxis])

plt.plot(data[inlier_mask, 0], data[inlier_mask, 1], '.g',
         label='Inlier data')
plt.plot(data[outlier_mask, 0], data[outlier_mask, 1], '.r',
         label='Outlier data')
plt.plot(line_X, line_y, '-k', label='Linear model from all data')
plt.plot(line_X, line_y_robust, '-b', label='Robustly fitted linear model')
plt.legend(loc='lower left')
plt.show()

Prompt: Add example plot script for RANSAC


import unittest
import github

class TestGithub(unittest.TestCase):

    def setUp(self):

        pass

    def test_user(self):

        u = github.user()
        u1 = github.user()

        self.assertTrue(u)
        # make sure hash works
        self.assertTrue(u is u1)

    def test_has_issues(self):

        self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
        self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

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

Response:
<REPLACE_OLD> self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

    def test_repo_from_path(self):

        up = "/Users/MorehouseJ09/Desktop/github-issues.vim"
        self.assertTrue(github.repo_from_path(up))

if <REPLACE_NEW> self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

if <REPLACE_END> <|endoftext|> import unittest
import github

class TestGithub(unittest.TestCase):

    def setUp(self):

        pass

    def test_user(self):

        u = github.user()
        u1 = github.user()

        self.assertTrue(u)
        # make sure hash works
        self.assertTrue(u is u1)

    def test_has_issues(self):

        self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
        self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

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

Prompt:
Remove old repo_from_path tests. This is a very hard functionality to
test

import unittest
import github

class TestGithub(unittest.TestCase):

    def setUp(self):

        pass

    def test_user(self):

        u = github.user()
        u1 = github.user()

        self.assertTrue(u)
        # make sure hash works
        self.assertTrue(u is u1)

    def test_has_issues(self):

        self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
        self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

    def test_repo_from_path(self):

        up = "/Users/MorehouseJ09/Desktop/github-issues.vim"
        self.assertTrue(github.repo_from_path(up))

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


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

"""The Base level for Savu

use with :

import savu

.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>

"""

from . import core
from . import data
from . import plugins

Response:
<REPLACE_OLD> <scientificsoftware@diamond.ac.uk>

"""
 <REPLACE_NEW> <scientificsoftware@diamond.ac.uk>

"""

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

"""The Base level for Savu

use with :

import savu

.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>

"""

from . import core
from . import data
from . import plugins

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

"""The Base level for Savu

use with :

import savu

.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>

"""


import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from individual import Individual
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

Remove BitVector import - Build fails

Remove BitVector import - Build fails

Response:
<DELETE> BitVector import BitVector
from <DELETE_END> <|endoftext|> import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from individual import Individual
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

Prompt:
Remove BitVector import - Build fails
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from individual import Individual
from BitVector import BitVector
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)


from django.urls import path
from invite import views

app_name = 'invite'
urlpatterns = [
    path('', views.index, name='index'),
    path('invite/', views.invite, name='invite'),
    path('resend/<slug:code>/', views.resend, name='resend'),
    path('revoke/<slug:code>/', views.revoke, name='revoke'),
    path('login/', views.log_in_user, name='login'),
    path('logout/', views.log_out_user, name='edit_logout'),
    path('amnesia/', views.amnesia, name='amnesia'),
    path('reset/', views.reset, name='reset'),
    path('signup/', views.signup, name='account_signup'),
    path('about/', views.about, name='about'),
    path('check/', views.check, name='check'),
]

Response:
<REPLACE_OLD> path('resend/(<slug:code>)/', <REPLACE_NEW> path('resend/<slug:code>/', <REPLACE_END> <REPLACE_OLD> path('revoke/(<slug:code>)/', <REPLACE_NEW> path('revoke/<slug:code>/', <REPLACE_END> <|endoftext|> from django.urls import path
from invite import views

app_name = 'invite'
urlpatterns = [
    path('', views.index, name='index'),
    path('invite/', views.invite, name='invite'),
    path('resend/<slug:code>/', views.resend, name='resend'),
    path('revoke/<slug:code>/', views.revoke, name='revoke'),
    path('login/', views.log_in_user, name='login'),
    path('logout/', views.log_out_user, name='edit_logout'),
    path('amnesia/', views.amnesia, name='amnesia'),
    path('reset/', views.reset, name='reset'),
    path('signup/', views.signup, name='account_signup'),
    path('about/', views.about, name='about'),
    path('check/', views.check, name='check'),
]

Prompt:
Fix issue with URL patterns adding parentheses around codes.

from django.urls import path
from invite import views

app_name = 'invite'
urlpatterns = [
    path('', views.index, name='index'),
    path('invite/', views.invite, name='invite'),
    path('resend/(<slug:code>)/', views.resend, name='resend'),
    path('revoke/(<slug:code>)/', views.revoke, name='revoke'),
    path('login/', views.log_in_user, name='login'),
    path('logout/', views.log_out_user, name='edit_logout'),
    path('amnesia/', views.amnesia, name='amnesia'),
    path('reset/', views.reset, name='reset'),
    path('signup/', views.signup, name='account_signup'),
    path('about/', views.about, name='about'),
    path('check/', views.check, name='check'),
]


#!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x

import os
from datetime import date
from collections import defaultdict

home = os.path.expanduser('~')

class Todo:
    def __init__(self):
        self.items = defaultdict(list)

    def __load_items(self):
        try:
            with open(home + '/.config/todo/list', 'r') as todo:
                for item in todo.readline():
                    # TODO: Need to figure out a way to store tags and items.
                    pass
        except IOError:
            print 'You do not have any items to load.'

    def __save_items(self):
        try:
            with open(home + '/.config/todo/list', 'w') as todo:
                # TODO: Implement saving items.
                pass

    def add_item(self, item, tag):
        self.items[tag].append(item)

    def remove_item(self, item, tag):
        if tag in self.items:
            if item in self.items[tag]:
                self.items[tag].remove(item)
            else:
                print "Item %s could not be found." % item
        else:
            print 'There is not tag named %s' % tag

    def print_all_items(self):
        for (tag, items) in self.items.items():
            print str(tag) + ':'
            for item in items:
                print ' ' + item
            print ''

if __name__ == '__main__':
    todo = Todo()
    # I actually need to do this, for real.
    todo.add_item('Get an oil change.', 'Car')
    todo.add_item('Plastidip my wheels.', 'Car')
    todo.add_item('Clean my room.', 'Housework')
    todo.print_all_items()
    todo.remove_item('Get an oil change.', 'Car')
    todo.remove_item('x', 'x')
    todo.remove_item('x', 'Housework')
    todo.print_all_items()

Response:
<REPLACE_OLD> https://redd.it/39ws1x

from <REPLACE_NEW> https://redd.it/39ws1x

import os
from <REPLACE_END> <REPLACE_OLD> defaultdict

class <REPLACE_NEW> defaultdict

home = os.path.expanduser('~')

class <REPLACE_END> <INSERT>    def __load_items(self):
        try:
            with open(home + '/.config/todo/list', 'r') as todo:
                for item in todo.readline():
                    # TODO: Need to figure out a way to store tags and items.
                    pass
        except IOError:
            print 'You do not have any items to load.'

    def __save_items(self):
        try:
            with open(home + '/.config/todo/list', 'w') as todo:
                # TODO: Implement saving items.
                pass

 <INSERT_END> <REPLACE_OLD> self.items[tag].remove(item)

 <REPLACE_NEW> if tag in self.items:
            if item in self.items[tag]:
                self.items[tag].remove(item)
            else:
                print "Item %s could not be found." % item
        else:
            print 'There is not tag named %s' % tag

 <REPLACE_END> <INSERT> todo.remove_item('x', 'x')
    todo.remove_item('x', 'Housework')
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x

import os
from datetime import date
from collections import defaultdict

home = os.path.expanduser('~')

class Todo:
    def __init__(self):
        self.items = defaultdict(list)

    def __load_items(self):
        try:
            with open(home + '/.config/todo/list', 'r') as todo:
                for item in todo.readline():
                    # TODO: Need to figure out a way to store tags and items.
                    pass
        except IOError:
            print 'You do not have any items to load.'

    def __save_items(self):
        try:
            with open(home + '/.config/todo/list', 'w') as todo:
                # TODO: Implement saving items.
                pass

    def add_item(self, item, tag):
        self.items[tag].append(item)

    def remove_item(self, item, tag):
        if tag in self.items:
            if item in self.items[tag]:
                self.items[tag].remove(item)
            else:
                print "Item %s could not be found." % item
        else:
            print 'There is not tag named %s' % tag

    def print_all_items(self):
        for (tag, items) in self.items.items():
            print str(tag) + ':'
            for item in items:
                print ' ' + item
            print ''

if __name__ == '__main__':
    todo = Todo()
    # I actually need to do this, for real.
    todo.add_item('Get an oil change.', 'Car')
    todo.add_item('Plastidip my wheels.', 'Car')
    todo.add_item('Clean my room.', 'Housework')
    todo.print_all_items()
    todo.remove_item('Get an oil change.', 'Car')
    todo.remove_item('x', 'x')
    todo.remove_item('x', 'Housework')
    todo.print_all_items()

Prompt:
Add and remove now work with minimal error checking.

#!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x

from datetime import date
from collections import defaultdict

class Todo:
    def __init__(self):
        self.items = defaultdict(list)

    def add_item(self, item, tag):
        self.items[tag].append(item)

    def remove_item(self, item, tag):
        self.items[tag].remove(item)

    def print_all_items(self):
        for (tag, items) in self.items.items():
            print str(tag) + ':'
            for item in items:
                print ' ' + item
            print ''

if __name__ == '__main__':
    todo = Todo()
    # I actually need to do this, for real.
    todo.add_item('Get an oil change.', 'Car')
    todo.add_item('Plastidip my wheels.', 'Car')
    todo.add_item('Clean my room.', 'Housework')
    todo.print_all_items()
    todo.remove_item('Get an oil change.', 'Car')
    todo.print_all_items()


"""
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from dataclasses import dataclass
from typing import NewType
from uuid import UUID

TourneyCategoryID = NewType('TourneyCategoryID', UUID)

TourneyID = NewType('TourneyID', UUID)

MatchID = NewType('MatchID', UUID)

MatchCommentID = NewType('MatchCommentID', UUID)

ParticipantID = NewType('ParticipantID', UUID)

@dataclass(frozen=True)
class Match:
    id: MatchID

Response:
<INSERT> dataclasses import dataclass
from <INSERT_END> <REPLACE_OLD> UUID

from attr import attrs

TourneyCategoryID <REPLACE_NEW> UUID

TourneyCategoryID <REPLACE_END> <REPLACE_OLD> UUID)

@attrs(auto_attribs=True, frozen=True, slots=True)
class <REPLACE_NEW> UUID)

@dataclass(frozen=True)
class <REPLACE_END> <|endoftext|> """
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from dataclasses import dataclass
from typing import NewType
from uuid import UUID

TourneyCategoryID = NewType('TourneyCategoryID', UUID)

TourneyID = NewType('TourneyID', UUID)

MatchID = NewType('MatchID', UUID)

MatchCommentID = NewType('MatchCommentID', UUID)

ParticipantID = NewType('ParticipantID', UUID)

@dataclass(frozen=True)
class Match:
    id: MatchID

Prompt:
Change tourney match transfer model from `attrs` to `dataclass`

"""
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from typing import NewType
from uuid import UUID

from attr import attrs

TourneyCategoryID = NewType('TourneyCategoryID', UUID)

TourneyID = NewType('TourneyID', UUID)

MatchID = NewType('MatchID', UUID)

MatchCommentID = NewType('MatchCommentID', UUID)

ParticipantID = NewType('ParticipantID', UUID)

@attrs(auto_attribs=True, frozen=True, slots=True)
class Match:
    id: MatchID


from django.template.base import Library
from django.core.urlresolvers import reverse

from projects.models import ProjectBuild

register = Library()

@register.simple_tag()
def build_url(build_key):
    """
    Fetches the ProjectBuild for a given build_id, if any.
    """
    try:
        build = ProjectBuild.objects.get(build_key=build_key)
        return reverse(
            "project_projectbuild_detail",
            kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
    except ProjectBuild.DoesNotExist:
        return ""

Response:
<REPLACE_OLD> build_url(build_id):
 <REPLACE_NEW> build_url(build_key):
 <REPLACE_END> <REPLACE_OLD> ProjectBuild.objects.get(build_key=build_id)
 <REPLACE_NEW> ProjectBuild.objects.get(build_key=build_key)
 <REPLACE_END> <|endoftext|> from django.template.base import Library
from django.core.urlresolvers import reverse

from projects.models import ProjectBuild

register = Library()

@register.simple_tag()
def build_url(build_key):
    """
    Fetches the ProjectBuild for a given build_id, if any.
    """
    try:
        build = ProjectBuild.objects.get(build_key=build_key)
        return reverse(
            "project_projectbuild_detail",
            kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
    except ProjectBuild.DoesNotExist:
        return ""

Prompt:
Change the project_tags parameter to use build_key which makes it clearer.

from django.template.base import Library
from django.core.urlresolvers import reverse

from projects.models import ProjectBuild

register = Library()

@register.simple_tag()
def build_url(build_id):
    """
    Fetches the ProjectBuild for a given build_id, if any.
    """
    try:
        build = ProjectBuild.objects.get(build_key=build_id)
        return reverse(
            "project_projectbuild_detail",
            kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
    except ProjectBuild.DoesNotExist:
        return ""


from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  column_list = ('id', 'perspective', 'start_time')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text')

  column_list = ('id', 'gender', 'text', 'created_at')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class SubmissionModelView(ModelView):
  column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(SubmissionModelView, self).__init__(
      schema.Submission,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())

Fix list columns for all models

Fix list columns for all models

Response:
<INSERT> column_list = ('id', 'perspective', 'start_time')
  <INSERT_END> <INSERT> column_list = ('id', 'gender', 'text', 'created_at')

  <INSERT_END> <REPLACE_OLD> )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))
 <REPLACE_NEW> )

class SubmissionModelView(ModelView):
  column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(SubmissionModelView, self).__init__(
      schema.Submission,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())
 <REPLACE_END> <|endoftext|> from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  column_list = ('id', 'perspective', 'start_time')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text')

  column_list = ('id', 'gender', 'text', 'created_at')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class SubmissionModelView(ModelView):
  column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(SubmissionModelView, self).__init__(
      schema.Submission,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())

Prompt:
Fix list columns for all models

from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))


"""Make the functionalities of this package auto-discoverable by mara-app"""

def MARA_CONFIG_MODULES():
    from . import config
    return [config]

def MARA_FLASK_BLUEPRINTS():
    from . import views
    return [views.blueprint]

def MARA_AUTOMIGRATE_SQLALCHEMY_MODELS():
    return []

def MARA_ACL_RESOURCES():
    from . import views
    return {'DB Schema': views.acl_resource}

def MARA_CLICK_COMMANDS():
    from . import cli
    return [cli.migrate]

def MARA_NAVIGATION_ENTRIES():
    from . import views
    return {'DB Schema': views.navigation_entry()}

Response:
<INSERT> """Make the functionalities of this package auto-discoverable by mara-app"""

def MARA_CONFIG_MODULES():
    <INSERT_END> <REPLACE_OLD> mara_db <REPLACE_NEW> . <REPLACE_END> <REPLACE_OLD> config, views, cli

MARA_CONFIG_MODULES = [config]

MARA_NAVIGATION_ENTRY_FNS = [views.navigation_entry]

MARA_ACL_RESOURCES = [views.acl_resource]

MARA_FLASK_BLUEPRINTS = [views.blueprint]

MARA_CLICK_COMMANDS = [cli.migrate]
 <REPLACE_NEW> config
    return [config]

def MARA_FLASK_BLUEPRINTS():
    from . import views
    return [views.blueprint]

def MARA_AUTOMIGRATE_SQLALCHEMY_MODELS():
    return []

def MARA_ACL_RESOURCES():
    from . import views
    return {'DB Schema': views.acl_resource}

def MARA_CLICK_COMMANDS():
    from . import cli
    return [cli.migrate]

def MARA_NAVIGATION_ENTRIES():
    from . import views
    return {'DB Schema': views.navigation_entry()}
 <REPLACE_END> <|endoftext|> """Make the functionalities of this package auto-discoverable by mara-app"""

def MARA_CONFIG_MODULES():
    from . import config
    return [config]

def MARA_FLASK_BLUEPRINTS():
    from . import views
    return [views.blueprint]

def MARA_AUTOMIGRATE_SQLALCHEMY_MODELS():
    return []

def MARA_ACL_RESOURCES():
    from . import views
    return {'DB Schema': views.acl_resource}

def MARA_CLICK_COMMANDS():
    from . import cli
    return [cli.migrate]

def MARA_NAVIGATION_ENTRIES():
    from . import views
    return {'DB Schema': views.navigation_entry()}

Prompt:
Change MARA_XXX variables to functions to delay importing of imports (requires updating mara-app to 2.0.0)

from mara_db import config, views, cli

MARA_CONFIG_MODULES = [config]

MARA_NAVIGATION_ENTRY_FNS = [views.navigation_entry]

MARA_ACL_RESOURCES = [views.acl_resource]

MARA_FLASK_BLUEPRINTS = [views.blueprint]

MARA_CLICK_COMMANDS = [cli.migrate]


from django.test import TestCase
from billjobs.admin import UserAdmin

class EmailExportTestCase(TestCase):
    """ Tests for email account export """

    def test_action_is_avaible(self):
        """ Test admin can select the action in dropdown list """
        self.assertTrue(hasattr(UserAdmin, 'export_email'))

Add test for email account export

Add test for email account export

Response:
<INSERT> from django.test import TestCase
from billjobs.admin import UserAdmin

class EmailExportTestCase(TestCase):
 <INSERT_END> <INSERT>   """ Tests for email account export """

    def test_action_is_avaible(self):
        """ Test admin can select the action in dropdown list """
        self.assertTrue(hasattr(UserAdmin, 'export_email'))
 <INSERT_END> <|endoftext|> from django.test import TestCase
from billjobs.admin import UserAdmin

class EmailExportTestCase(TestCase):
    """ Tests for email account export """

    def test_action_is_avaible(self):
        """ Test admin can select the action in dropdown list """
        self.assertTrue(hasattr(UserAdmin, 'export_email'))

Prompt: Add test for email account export


import sys
import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def transpose(xs):
    return zip(*xs)

def read_sides(line):
    return map(int, line.split())

def valid_triangle((a, b, c)):
    return a + b > c and b + c > a and a + c > b

if __name__ == '__main__':
    print len(filter(valid_triangle,
                     grouper(
                         itertools.chain.from_iterable(
                             transpose(map(read_sides, sys.stdin))), 3)))

Response:
<REPLACE_OLD> sys

def <REPLACE_NEW> sys
import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def transpose(xs):
    return zip(*xs)

def <REPLACE_END> <REPLACE_OLD> len(filter(valid_triangle, map(read_sides, sys.stdin)))
 <REPLACE_NEW> len(filter(valid_triangle,
                     grouper(
                         itertools.chain.from_iterable(
                             transpose(map(read_sides, sys.stdin))), 3)))
 <REPLACE_END> <|endoftext|> import sys
import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def transpose(xs):
    return zip(*xs)

def read_sides(line):
    return map(int, line.split())

def valid_triangle((a, b, c)):
    return a + b > c and b + c > a and a + c > b

if __name__ == '__main__':
    print len(filter(valid_triangle,
                     grouper(
                         itertools.chain.from_iterable(
                             transpose(map(read_sides, sys.stdin))), 3)))

Prompt:
Implement part 2 of day 3 Python solution.

import sys

def read_sides(line):
    return map(int, line.split())

def valid_triangle((a, b, c)):
    return a + b > c and b + c > a and a + c > b

if __name__ == '__main__':
    print len(filter(valid_triangle, map(read_sides, sys.stdin)))


#!/usr/bin/env python
#
# resize_ranges
# Resizes ranges in a  BED file around a center point
#

import sys
import argparse
import csv

def resize_row(row, width):
    start, end = int(row[1]), int(row[2])
    original_range = end-start
    margin = (original_range - width) / 2
    start = start + margin
    end = end - margin
    row[1] = start
    row[2] = end
    return row

def resize_ranges(input, output, width):
    """
    Resizes regions in a bed file to the given width
    :param input: An input stream or open file
    :param output: An output stream
    :param width: the desired width
    :return:
    """
    reader = csv.reader(input, delimiter='\t')
    writer = csv.writer(output, delimiter='\t')
    for row in reader:
        writer.writerow(resize_row(row, width))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Resize ranges in a BED file')
    parser.add_argument('inputfile', type=argparse.FileType('rb'))
    parser.add_argument('width', type=int)
    parser.add_argument_group()
    args = parser.parse_args()
    resize_ranges(args.inputfile, sys.stdout, args.width)

Add python script to resize regions

Add python script to resize regions

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
#
# resize_ranges
# Resizes ranges in a  BED file around a center point
#

import sys
import argparse
import csv

def resize_row(row, width):
    start, end = int(row[1]), int(row[2])
    original_range = end-start
    margin = (original_range - width) / 2
    start = start + margin
    end = end - margin
    row[1] = start
    row[2] = end
    return row

def resize_ranges(input, output, width):
    """
    Resizes regions in a bed file to the given width
    :param input: An input stream or open file
    :param output: An output stream
    :param width: the desired width
    :return:
    """
    reader = csv.reader(input, delimiter='\t')
    writer = csv.writer(output, delimiter='\t')
    for row in reader:
        writer.writerow(resize_row(row, width))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Resize ranges in a BED file')
    parser.add_argument('inputfile', type=argparse.FileType('rb'))
    parser.add_argument('width', type=int)
    parser.add_argument_group()
    args = parser.parse_args()
    resize_ranges(args.inputfile, sys.stdout, args.width)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# resize_ranges
# Resizes ranges in a  BED file around a center point
#

import sys
import argparse
import csv

def resize_row(row, width):
    start, end = int(row[1]), int(row[2])
    original_range = end-start
    margin = (original_range - width) / 2
    start = start + margin
    end = end - margin
    row[1] = start
    row[2] = end
    return row

def resize_ranges(input, output, width):
    """
    Resizes regions in a bed file to the given width
    :param input: An input stream or open file
    :param output: An output stream
    :param width: the desired width
    :return:
    """
    reader = csv.reader(input, delimiter='\t')
    writer = csv.writer(output, delimiter='\t')
    for row in reader:
        writer.writerow(resize_row(row, width))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Resize ranges in a BED file')
    parser.add_argument('inputfile', type=argparse.FileType('rb'))
    parser.add_argument('width', type=int)
    parser.add_argument_group()
    args = parser.parse_args()
    resize_ranges(args.inputfile, sys.stdout, args.width)

Prompt: Add python script to resize regions


"""An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
import hug
import requests

@hug.local()
@hug.cli()
@hug.get()
def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
    """Returns the top post from the provided section"""
    content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
    text = content.decode('utf-8')
    return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]

Add example of a write once API

Add example of a write once API

Response:
<INSERT> """An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
import hug
import requests

@hug.local()
@hug.cli()
@hug.get()
def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
 <INSERT_END> <INSERT>   """Returns the top post from the provided section"""
    content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
    text = content.decode('utf-8')
    return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]
 <INSERT_END> <|endoftext|> """An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
import hug
import requests

@hug.local()
@hug.cli()
@hug.get()
def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
    """Returns the top post from the provided section"""
    content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
    text = content.decode('utf-8')
    return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]

Prompt: Add example of a write once API


# Color Prefs for idle

class ColorPrefs:
    CNormal     = "black", "white"      # "purple", "white"
    CKeyword    = "#ff7700", None
    CComment    = "#dd0000", None
    CString     = "#00aa00", None
    CDefinition = "#0000ff", None
    CHilite     = "#000068", "#006868"
    CSync       = None, None            # None, "#ffff00"
    CTodo       = None, None            # None, "#cccccc"
    CBreak      = "#ff7777", None
    CHit        = "#ffffff", "#000000"
    CStdIn      = None, None            # None, "yellow"
    CStdOut     = "blue", None
    CStdErr     = "red", None
    CConsole    = "#770000", None
    CError      = None, "#ff7777"
    CCursor     = None, "black"

Response:
<REPLACE_OLD> "#007700", <REPLACE_NEW> "red", <REPLACE_END> <|endoftext|> # Color Prefs for idle

class ColorPrefs:
    CNormal     = "black", "white"      # "purple", "white"
    CKeyword    = "#ff7700", None
    CComment    = "#dd0000", None
    CString     = "#00aa00", None
    CDefinition = "#0000ff", None
    CHilite     = "#000068", "#006868"
    CSync       = None, None            # None, "#ffff00"
    CTodo       = None, None            # None, "#cccccc"
    CBreak      = "#ff7777", None
    CHit        = "#ffffff", "#000000"
    CStdIn      = None, None            # None, "yellow"
    CStdOut     = "blue", None
    CStdErr     = "red", None
    CConsole    = "#770000", None
    CError      = None, "#ff7777"
    CCursor     = None, "black"

Prompt:
Make the color for stderr red (i.e. the standard warning/danger/stop
color) rather than green.  Suggested by Sam Schulenburg.

# Color Prefs for idle

class ColorPrefs:
    CNormal     = "black", "white"      # "purple", "white"
    CKeyword    = "#ff7700", None
    CComment    = "#dd0000", None
    CString     = "#00aa00", None
    CDefinition = "#0000ff", None
    CHilite     = "#000068", "#006868"
    CSync       = None, None            # None, "#ffff00"
    CTodo       = None, None            # None, "#cccccc"
    CBreak      = "#ff7777", None
    CHit        = "#ffffff", "#000000"
    CStdIn      = None, None            # None, "yellow"
    CStdOut     = "blue", None
    CStdErr     = "#007700", None
    CConsole    = "#770000", None
    CError      = None, "#ff7777"
    CCursor     = None, "black"


#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

Add module for Terminal tests

Add module for Terminal tests

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

""" <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

Prompt: Add module for Terminal tests


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

from django.utils.translation import ugettext_lazy as _
import horizon

class Infrastructure(horizon.Dashboard):
    name = _("Infrastructure")
    slug = "infrastructure"
    panels = (
        'overview',
        'parameters',
        'roles',
        'nodes',
        'flavors',
        'images',
        'history',
    )
    default_panel = 'overview'
    permissions = ('openstack.roles.admin',)

horizon.register(Infrastructure)

Remove the Infrastructure panel group

Response:
<REPLACE_OLD> BasePanels(horizon.PanelGroup):
 <REPLACE_NEW> Infrastructure(horizon.Dashboard):
    name = _("Infrastructure")
 <REPLACE_END> <DELETE> name = _("Infrastructure")
    <DELETE_END> <DELETE> )

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

from django.utils.translation import ugettext_lazy as _
import horizon

class Infrastructure(horizon.Dashboard):
    name = _("Infrastructure")
    slug = "infrastructure"
    panels = (
        'overview',
        'parameters',
        'roles',
        'nodes',
        'flavors',
        'images',
        'history',
    )
    default_panel = 'overview'
    permissions = ('openstack.roles.admin',)

horizon.register(Infrastructure)

Prompt:
Remove the Infrastructure panel group

Remove the Infrastructure panel group, and place the panels
directly under the Infrastructure dashboard.

Change-Id: I321f9a84dd885732438ad58b6c62c480c9c10e37

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

from django.utils.translation import ugettext_lazy as _
import horizon

class BasePanels(horizon.PanelGroup):
    slug = "infrastructure"
    name = _("Infrastructure")
    panels = (
        'overview',
        'parameters',
        'roles',
        'nodes',
        'flavors',
        'images',
        'history',
    )

class Infrastructure(horizon.Dashboard):
    name = _("Infrastructure")
    slug = "infrastructure"
    panels = (
        BasePanels,
    )
    default_panel = 'overview'
    permissions = ('openstack.roles.admin',)

horizon.register(Infrastructure)


import pybedtools as bt
import six

def concat(bed_files, catted=None):
    """
    recursively concat a set of BED files, returning a
    sorted bedtools object of the result
    """
    bed_files = [x for x in bed_files if x]
    if len(bed_files) == 0:
        if catted:
            # move to a .bed extension for downstream tools if not already
            sorted_bed = catted.sort()
            if not sorted_bed.fn.endswith(".bed"):
                return sorted_bed.moveto(sorted_bed.fn + ".bed")
            else:
                return sorted_bed
        else:
            return catted

    if not catted:
        bed_files = list(bed_files)
        catted = bt.BedTool(bed_files.pop())
    else:
        catted = catted.cat(bed_files.pop(), postmerge=False,
                            force_truncate=False)

    return concat(bed_files, catted)

def merge(bedfiles):
    """
    given a BED file or list of BED files merge them an return a bedtools object
    """
    if isinstance(bedfiles, list):
        catted = concat(bedfiles)
    else:
        catted = concat([bedfiles])
    if catted:
        return concat(bedfiles).sort().merge()
    else:
        return catted

def minimize(bed_file):
    """
    strip a BED file down to its three necessary columns: chrom start end
    """
    if not bed_file:
        return bed_file
    else:
        return bt.BedTool(bed_file).cut(range(3))

Response:
<INSERT> if not bed_file:
        return bed_file
    else:
        <INSERT_END> <|endoftext|> import pybedtools as bt
import six

def concat(bed_files, catted=None):
    """
    recursively concat a set of BED files, returning a
    sorted bedtools object of the result
    """
    bed_files = [x for x in bed_files if x]
    if len(bed_files) == 0:
        if catted:
            # move to a .bed extension for downstream tools if not already
            sorted_bed = catted.sort()
            if not sorted_bed.fn.endswith(".bed"):
                return sorted_bed.moveto(sorted_bed.fn + ".bed")
            else:
                return sorted_bed
        else:
            return catted

    if not catted:
        bed_files = list(bed_files)
        catted = bt.BedTool(bed_files.pop())
    else:
        catted = catted.cat(bed_files.pop(), postmerge=False,
                            force_truncate=False)

    return concat(bed_files, catted)

def merge(bedfiles):
    """
    given a BED file or list of BED files merge them an return a bedtools object
    """
    if isinstance(bedfiles, list):
        catted = concat(bedfiles)
    else:
        catted = concat([bedfiles])
    if catted:
        return concat(bedfiles).sort().merge()
    else:
        return catted

def minimize(bed_file):
    """
    strip a BED file down to its three necessary columns: chrom start end
    """
    if not bed_file:
        return bed_file
    else:
        return bt.BedTool(bed_file).cut(range(3))

Prompt:
Return None if no bed file exists to be opened.

import pybedtools as bt
import six

def concat(bed_files, catted=None):
    """
    recursively concat a set of BED files, returning a
    sorted bedtools object of the result
    """
    bed_files = [x for x in bed_files if x]
    if len(bed_files) == 0:
        if catted:
            # move to a .bed extension for downstream tools if not already
            sorted_bed = catted.sort()
            if not sorted_bed.fn.endswith(".bed"):
                return sorted_bed.moveto(sorted_bed.fn + ".bed")
            else:
                return sorted_bed
        else:
            return catted

    if not catted:
        bed_files = list(bed_files)
        catted = bt.BedTool(bed_files.pop())
    else:
        catted = catted.cat(bed_files.pop(), postmerge=False,
                            force_truncate=False)

    return concat(bed_files, catted)

def merge(bedfiles):
    """
    given a BED file or list of BED files merge them an return a bedtools object
    """
    if isinstance(bedfiles, list):
        catted = concat(bedfiles)
    else:
        catted = concat([bedfiles])
    if catted:
        return concat(bedfiles).sort().merge()
    else:
        return catted

def minimize(bed_file):
    """
    strip a BED file down to its three necessary columns: chrom start end
    """
    return bt.BedTool(bed_file).cut(range(3))


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

from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack

class ChartsView(TemplateView):
    template_name = 'chartflo/charts.html'
    chart_type = "pie"
    title = ""

    def get_data(self):
        return {}

    def get_context_data(self, **kwargs):
        context = super(ChartsView, self).get_context_data(**kwargs)
        # get data
        P = ChartDataPack()
        dataset = self.get_data()
        # package the data
        datapack = P.package("chart_id", self.title, dataset)
        # options
        datapack['legend'] = True
        datapack['export'] = False
        context['datapack'] = datapack
        context["title"] = context["label"] = self.title
        context["chart_url"] = self._get_chart_url()
        return context

    def _get_chart_url(self):
        url = "chartflo/charts/" + self.chart_type + ".html"
        return url

Response:
<REPLACE_OLD> graph_type <REPLACE_NEW> chart_type <REPLACE_END> <DELETE> context["graph_type"] = self.graph_type
        <DELETE_END> <REPLACE_OLD> self.graph_type <REPLACE_NEW> self.chart_type <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack

class ChartsView(TemplateView):
    template_name = 'chartflo/charts.html'
    chart_type = "pie"
    title = ""

    def get_data(self):
        return {}

    def get_context_data(self, **kwargs):
        context = super(ChartsView, self).get_context_data(**kwargs)
        # get data
        P = ChartDataPack()
        dataset = self.get_data()
        # package the data
        datapack = P.package("chart_id", self.title, dataset)
        # options
        datapack['legend'] = True
        datapack['export'] = False
        context['datapack'] = datapack
        context["title"] = context["label"] = self.title
        context["chart_url"] = self._get_chart_url()
        return context

    def _get_chart_url(self):
        url = "chartflo/charts/" + self.chart_type + ".html"
        return url

Prompt:
Change graph_type for chart_type and remove it from context

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

from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack

class ChartsView(TemplateView):
    template_name = 'chartflo/charts.html'
    graph_type = "pie"
    title = ""

    def get_data(self):
        return {}

    def get_context_data(self, **kwargs):
        context = super(ChartsView, self).get_context_data(**kwargs)
        # get data
        P = ChartDataPack()
        dataset = self.get_data()
        # package the data
        datapack = P.package("chart_id", self.title, dataset)
        # options
        datapack['legend'] = True
        datapack['export'] = False
        context['datapack'] = datapack
        context["graph_type"] = self.graph_type
        context["title"] = context["label"] = self.title
        context["chart_url"] = self._get_chart_url()
        return context

    def _get_chart_url(self):
        url = "chartflo/charts/" + self.graph_type + ".html"
        return url


import os
from setuptools import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(name='windpowerlib',
      version='0.1.3',
      description='Creating time series of wind power plants.',
      url='http://github.com/wind-python/windpowerlib',
      author='oemof developer group',
      author_email='windpowerlib@rl-institut.de',
      license=None,
      packages=['windpowerlib'],
      package_data={
          'windpowerlib': [os.path.join('data', '*.csv')]},
      long_description=read('README.rst'),
      long_description_content_type='text/rst',
      zip_safe=False,
      install_requires=['pandas >= 0.19.1, < 0.26',
                        'requests < 3.0'],
      extras_require={
          'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})

Add content type of long description

Add content type of long description

Response:
<INSERT> long_description_content_type='text/rst',
      <INSERT_END> <|endoftext|> import os
from setuptools import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(name='windpowerlib',
      version='0.1.3',
      description='Creating time series of wind power plants.',
      url='http://github.com/wind-python/windpowerlib',
      author='oemof developer group',
      author_email='windpowerlib@rl-institut.de',
      license=None,
      packages=['windpowerlib'],
      package_data={
          'windpowerlib': [os.path.join('data', '*.csv')]},
      long_description=read('README.rst'),
      long_description_content_type='text/rst',
      zip_safe=False,
      install_requires=['pandas >= 0.19.1, < 0.26',
                        'requests < 3.0'],
      extras_require={
          'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})

Prompt:
Add content type of long description

import os
from setuptools import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(name='windpowerlib',
      version='0.1.3',
      description='Creating time series of wind power plants.',
      url='http://github.com/wind-python/windpowerlib',
      author='oemof developer group',
      author_email='windpowerlib@rl-institut.de',
      license=None,
      packages=['windpowerlib'],
      package_data={
          'windpowerlib': [os.path.join('data', '*.csv')]},
      long_description=read('README.rst'),
      zip_safe=False,
      install_requires=['pandas >= 0.19.1, < 0.26',
                        'requests < 3.0'],
      extras_require={
          'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})


"""
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_function

from mock import patch

@patch("sqlalchemy.create_engine")
def test_status_no_db_access(create_engine_mock):
    """
    Tests that status does not try to access the database
    """
    try:
        from kolibri.utils import cli

        cli.status.callback()
    except SystemExit:
        pass
    create_engine_mock.assert_not_called()

@patch("sqlalchemy.create_engine")
def test_stop_no_db_access(create_engine_mock):
    """
    Tests that status does not try to access the database
    """
    try:
        from kolibri.utils import cli

        cli.stop.callback()
    except SystemExit:
        pass
    create_engine_mock.assert_not_called()

@patch("kolibri.utils.options.read_options_file")
def test_import_no_options_evaluation(read_options_mock):
    from kolibri.utils import cli  # noqa F401

    read_options_mock.assert_not_called()

Response:
<REPLACE_OLD> create_engine_mock.assert_not_called()
 <REPLACE_NEW> create_engine_mock.assert_not_called()

@patch("kolibri.utils.options.read_options_file")
def test_import_no_options_evaluation(read_options_mock):
    from kolibri.utils import cli  # noqa F401

    read_options_mock.assert_not_called()
 <REPLACE_END> <|endoftext|> """
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_function

from mock import patch

@patch("sqlalchemy.create_engine")
def test_status_no_db_access(create_engine_mock):
    """
    Tests that status does not try to access the database
    """
    try:
        from kolibri.utils import cli

        cli.status.callback()
    except SystemExit:
        pass
    create_engine_mock.assert_not_called()

@patch("sqlalchemy.create_engine")
def test_stop_no_db_access(create_engine_mock):
    """
    Tests that status does not try to access the database
    """
    try:
        from kolibri.utils import cli

        cli.stop.callback()
    except SystemExit:
        pass
    create_engine_mock.assert_not_called()

@patch("kolibri.utils.options.read_options_file")
def test_import_no_options_evaluation(read_options_mock):
    from kolibri.utils import cli  # noqa F401

    read_options_mock.assert_not_called()

Prompt:
Add regression test against options evaluation during import in cli.

"""
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_function

from mock import patch

@patch("sqlalchemy.create_engine")
def test_status_no_db_access(create_engine_mock):
    """
    Tests that status does not try to access the database
    """
    try:
        from kolibri.utils import cli

        cli.status.callback()
    except SystemExit:
        pass
    create_engine_mock.assert_not_called()

@patch("sqlalchemy.create_engine")
def test_stop_no_db_access(create_engine_mock):
    """
    Tests that status does not try to access the database
    """
    try:
        from kolibri.utils import cli

        cli.stop.callback()
    except SystemExit:
        pass
    create_engine_mock.assert_not_called()


from django.db import models

from bulletin.models import Post

class Event(Post):

    start_date = models.DateTimeField()
    end_date = models.DateTimeField(null=True, blank=True)
    time = models.CharField(max_length=255,
                            null=True, blank=True)
    organization = models.CharField(max_length=255,
                                    null=True, blank=True)
    location = models.CharField(max_length=255)

class Job(Post):

    organization = models.CharField(max_length=255)

class NewResource(Post):

    blurb = models.TextField()
    verbose_name = 'newresource'

class Opportunity(Post):

    blurb = models.TextField()

    class Meta:
        verbose_name_plural = 'opportunities'

class Story(Post):

    blurb = models.TextField()
    date = models.DateTimeField()

    class Meta:
        verbose_name_plural = 'stories'

Set verbose name of NewResource.

Set verbose name of NewResource.

Response:
<REPLACE_OLD> models.TextField()

class <REPLACE_NEW> models.TextField()
    verbose_name = 'newresource'

class <REPLACE_END> <|endoftext|> from django.db import models

from bulletin.models import Post

class Event(Post):

    start_date = models.DateTimeField()
    end_date = models.DateTimeField(null=True, blank=True)
    time = models.CharField(max_length=255,
                            null=True, blank=True)
    organization = models.CharField(max_length=255,
                                    null=True, blank=True)
    location = models.CharField(max_length=255)

class Job(Post):

    organization = models.CharField(max_length=255)

class NewResource(Post):

    blurb = models.TextField()
    verbose_name = 'newresource'

class Opportunity(Post):

    blurb = models.TextField()

    class Meta:
        verbose_name_plural = 'opportunities'

class Story(Post):

    blurb = models.TextField()
    date = models.DateTimeField()

    class Meta:
        verbose_name_plural = 'stories'

Prompt:
Set verbose name of NewResource.

from django.db import models

from bulletin.models import Post

class Event(Post):

    start_date = models.DateTimeField()
    end_date = models.DateTimeField(null=True, blank=True)
    time = models.CharField(max_length=255,
                            null=True, blank=True)
    organization = models.CharField(max_length=255,
                                    null=True, blank=True)
    location = models.CharField(max_length=255)

class Job(Post):

    organization = models.CharField(max_length=255)

class NewResource(Post):

    blurb = models.TextField()

class Opportunity(Post):

    blurb = models.TextField()

    class Meta:
        verbose_name_plural = 'opportunities'

class Story(Post):

    blurb = models.TextField()
    date = models.DateTimeField()

    class Meta:
        verbose_name_plural = 'stories'


#!/usr/bin/env python
#
# Copyright 2021 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Merges dEQP sharded test results in the ANGLE testing infrastucture."""

import os
import sys

d = os.path.dirname
THIS_DIR = d(os.path.abspath(__file__))
ANGLE_SRC_DIR = d(THIS_DIR)
sys.path.insert(0, os.path.join(ANGLE_SRC_DIR, 'testing', 'merge_scripts'))
CHROMIUM_SRC_DIR = d(d(ANGLE_SRC_DIR))
sys.path.insert(0, os.path.join(CHROMIUM_SRC_DIR, 'testing', 'merge_scripts'))

import merge_api
import standard_isolated_script_merge

def main(raw_args):

    parser = merge_api.ArgumentParser()
    args = parser.parse_args(raw_args)

    # TODO(jmadill): Merge QPA files into one. http://anglebug.com/5236

    return standard_isolated_script_merge.StandardIsolatedScriptMerge(
        args.output_json, args.summary_json, args.jsons_to_merge)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Add dEQP test merge script.

testing: Add dEQP test merge script.

This script will allow ANGLE to process custom logic when we complete
a suite  of dEQP tests on the bots. The first customization step we
can do is merge the myriad batch QPA files into one master QPA file.

This script is currently a no-op and will let us set up the merge step
so we can test the logic pre-commit.

Bug: angleproject:5236
Change-Id: I38d0e359ff7fc6f6f91b5193387c13ff0fc77aa6
Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2664247
Commit-Queue: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
Reviewed-by: Yuly Novikov <36f5580f63d0a3eacc17e89a61d11e2f646630d2@chromium.org>

Response:
<INSERT> #!/usr/bin/env python
#
# Copyright 2021 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Merges dEQP sharded test results in the ANGLE testing infrastucture."""

import os
import sys

d = os.path.dirname
THIS_DIR = d(os.path.abspath(__file__))
ANGLE_SRC_DIR = d(THIS_DIR)
sys.path.insert(0, os.path.join(ANGLE_SRC_DIR, 'testing', 'merge_scripts'))
CHROMIUM_SRC_DIR = d(d(ANGLE_SRC_DIR))
sys.path.insert(0, os.path.join(CHROMIUM_SRC_DIR, 'testing', 'merge_scripts'))

import merge_api
import standard_isolated_script_merge

def main(raw_args):

 <INSERT_END> <INSERT>   parser = merge_api.ArgumentParser()
    args = parser.parse_args(raw_args)

    # TODO(jmadill): Merge QPA files into one. http://anglebug.com/5236

    return standard_isolated_script_merge.StandardIsolatedScriptMerge(
        args.output_json, args.summary_json, args.jsons_to_merge)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
#
# Copyright 2021 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Merges dEQP sharded test results in the ANGLE testing infrastucture."""

import os
import sys

d = os.path.dirname
THIS_DIR = d(os.path.abspath(__file__))
ANGLE_SRC_DIR = d(THIS_DIR)
sys.path.insert(0, os.path.join(ANGLE_SRC_DIR, 'testing', 'merge_scripts'))
CHROMIUM_SRC_DIR = d(d(ANGLE_SRC_DIR))
sys.path.insert(0, os.path.join(CHROMIUM_SRC_DIR, 'testing', 'merge_scripts'))

import merge_api
import standard_isolated_script_merge

def main(raw_args):

    parser = merge_api.ArgumentParser()
    args = parser.parse_args(raw_args)

    # TODO(jmadill): Merge QPA files into one. http://anglebug.com/5236

    return standard_isolated_script_merge.StandardIsolatedScriptMerge(
        args.output_json, args.summary_json, args.jsons_to_merge)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Prompt:
testing: Add dEQP test merge script.

This script will allow ANGLE to process custom logic when we complete
a suite  of dEQP tests on the bots. The first customization step we
can do is merge the myriad batch QPA files into one master QPA file.

This script is currently a no-op and will let us set up the merge step
so we can test the logic pre-commit.

Bug: angleproject:5236
Change-Id: I38d0e359ff7fc6f6f91b5193387c13ff0fc77aa6
Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2664247
Commit-Queue: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
Reviewed-by: Yuly Novikov <36f5580f63d0a3eacc17e89a61d11e2f646630d2@chromium.org>


"""
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from byceps.services.authorization import service as authorization_service

from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_to_user

class AuthorizationServiceTestCase(AbstractAppTestCase):

    def test_get_permission_ids_for_user(self):
        user = self.create_user()

        permissions_before = authorization_service.get_permission_ids_for_user(user.id)
        assert permissions_before == frozenset()

        assign_permissions_to_user(user.id, 'board_moderator', {
            'board_topic_hide',
            'board_topic_pin',
        })
        assign_permissions_to_user(user.id, 'news_editor', {
            'news_item_create',
        })

        permissions_after = authorization_service.get_permission_ids_for_user(user.id)
        assert permissions_after == {
            'board_topic_hide',
            'board_topic_pin',
            'news_item_create',
        }

Response:
<REPLACE_OLD> AbstractAppTestCase

class <REPLACE_NEW> AbstractAppTestCase
from tests.helpers import assign_permissions_to_user

class <REPLACE_END> <DELETE>        board_moderator_role = create_role_with_permissions('board_moderator', [
            'board_topic_hide',
            'board_topic_pin',
        ])
        news_editor_role = create_role_with_permissions('news_editor', [
            'news_item_create',
        ])

 <DELETE_END> <REPLACE_OLD> assign_roles_to_user(user.id, {board_moderator_role, news_editor_role})

 <REPLACE_NEW> assign_permissions_to_user(user.id, 'board_moderator', {
            'board_topic_hide',
            'board_topic_pin',
        })
        assign_permissions_to_user(user.id, 'news_editor', {
            'news_item_create',
        })

 <REPLACE_END> <REPLACE_OLD> }

def create_role_with_permissions(role_id, permission_ids):
    role = authorization_service.create_role(role_id, role_id)

    for permission_id in permission_ids:
        permission = authorization_service.create_permission(permission_id,
                                                             permission_id)
        authorization_service.assign_permission_to_role(permission.id, role.id)

    return role

def assign_roles_to_user(user_id, roles):
    for role in roles:
        authorization_service.assign_role_to_user(user_id, role.id)
 <REPLACE_NEW> }
 <REPLACE_END> <|endoftext|> """
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from byceps.services.authorization import service as authorization_service

from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_to_user

class AuthorizationServiceTestCase(AbstractAppTestCase):

    def test_get_permission_ids_for_user(self):
        user = self.create_user()

        permissions_before = authorization_service.get_permission_ids_for_user(user.id)
        assert permissions_before == frozenset()

        assign_permissions_to_user(user.id, 'board_moderator', {
            'board_topic_hide',
            'board_topic_pin',
        })
        assign_permissions_to_user(user.id, 'news_editor', {
            'news_item_create',
        })

        permissions_after = authorization_service.get_permission_ids_for_user(user.id)
        assert permissions_after == {
            'board_topic_hide',
            'board_topic_pin',
            'news_item_create',
        }

Prompt:
Use existing test helper to create and assign permissions and roles

"""
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from byceps.services.authorization import service as authorization_service

from tests.base import AbstractAppTestCase

class AuthorizationServiceTestCase(AbstractAppTestCase):

    def test_get_permission_ids_for_user(self):
        board_moderator_role = create_role_with_permissions('board_moderator', [
            'board_topic_hide',
            'board_topic_pin',
        ])
        news_editor_role = create_role_with_permissions('news_editor', [
            'news_item_create',
        ])

        user = self.create_user()

        permissions_before = authorization_service.get_permission_ids_for_user(user.id)
        assert permissions_before == frozenset()

        assign_roles_to_user(user.id, {board_moderator_role, news_editor_role})

        permissions_after = authorization_service.get_permission_ids_for_user(user.id)
        assert permissions_after == {
            'board_topic_hide',
            'board_topic_pin',
            'news_item_create',
        }

def create_role_with_permissions(role_id, permission_ids):
    role = authorization_service.create_role(role_id, role_id)

    for permission_id in permission_ids:
        permission = authorization_service.create_permission(permission_id,
                                                             permission_id)
        authorization_service.assign_permission_to_role(permission.id, role.id)

    return role

def assign_roles_to_user(user_id, roles):
    for role in roles:
        authorization_service.assign_role_to_user(user_id, role.id)


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

try:
    from pypandoc import convert
    long_description = convert('README.md', 'rst')
except:
    """
    Don't fail if pandoc or pypandoc are not installed.
    However, it is better to publish the package with
    a formatted README.
    """
    print("""
Warning: Missing pandoc, which is used to format \
the README. Install pypandoc and pandoc before publishing \
a new version.""")
    long_description = open('README.md').read()

from chargehound.version import VERSION

setup(
    name='chargehound',
    version=VERSION,
    author='Chargehound',
    author_email='support@chargehound.com',
    packages=['chargehound'],
    description='Chargehound Python Bindings',
    long_description=long_description,
    url='https://www.chargehound.com',
    license='MIT',
    test_suite='test.all',
    install_requires=[
        'requests'
        ],
    )

Add warning for missing pandoc

Add warning for missing pandoc

Response:
<INSERT>    print("""
Warning: Missing pandoc, which is used to format \
the README. Install pypandoc and pandoc before publishing \
a new version.""")
 <INSERT_END> <|endoftext|> try:
    from setuptools import setup
except ImportError:
    from disutils.core import setup

try:
    from pypandoc import convert
    long_description = convert('README.md', 'rst')
except:
    """
    Don't fail if pandoc or pypandoc are not installed.
    However, it is better to publish the package with
    a formatted README.
    """
    print("""
Warning: Missing pandoc, which is used to format \
the README. Install pypandoc and pandoc before publishing \
a new version.""")
    long_description = open('README.md').read()

from chargehound.version import VERSION

setup(
    name='chargehound',
    version=VERSION,
    author='Chargehound',
    author_email='support@chargehound.com',
    packages=['chargehound'],
    description='Chargehound Python Bindings',
    long_description=long_description,
    url='https://www.chargehound.com',
    license='MIT',
    test_suite='test.all',
    install_requires=[
        'requests'
        ],
    )

Prompt:
Add warning for missing pandoc

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

try:
    from pypandoc import convert
    long_description = convert('README.md', 'rst')
except:
    """
    Don't fail if pandoc or pypandoc are not installed.
    However, it is better to publish the package with
    a formatted README.
    """
    long_description = open('README.md').read()

from chargehound.version import VERSION

setup(
    name='chargehound',
    version=VERSION,
    author='Chargehound',
    author_email='support@chargehound.com',
    packages=['chargehound'],
    description='Chargehound Python Bindings',
    long_description=long_description,
    url='https://www.chargehound.com',
    license='MIT',
    test_suite='test.all',
    install_requires=[
        'requests'
        ],
    )


# coding: utf-8
"""Test that longer and mixed texts are tokenized correctly."""

from __future__ import unicode_literals

import pytest

def test_tokenizer_handles_long_text(en_tokenizer):
    text = """Tributes pour in for late British Labour Party leader

Tributes poured in from around the world Thursday
to the late Labour Party leader John Smith, who died earlier from a massive
heart attack aged 55.

In Washington, the US State Department issued a statement regretting "the
untimely death" of the rapier-tongued Scottish barrister and parliamentarian.

"Mr. Smith, throughout his distinguished"""
    tokens = en_tokenizer(text)
    assert len(tokens) == 76

@pytest.mark.parametrize('text,length', [
    ("The U.S. Army likes Shock and Awe.", 8),
    ("U.N. regulations are not a part of their concern.", 10),
    ("“Isn't it?”", 6),
    ("""Yes! "I'd rather have a walk", Ms. Comble sighed. """, 15),
    ("""'Me too!', Mr. P. Delaware cried. """, 11),
    ("They ran about 10km.", 6),
    # ("But then the 6,000-year ice age came...", 10)
    ])
def test_tokenizer_handles_cnts(en_tokenizer, text, length):
    tokens = en_tokenizer(text)
    assert len(tokens) == length

Add tests for longer and mixed English texts

Response:
<INSERT> # coding: utf-8
"""Test that longer and mixed texts are tokenized correctly."""

from __future__ import unicode_literals

import pytest

def test_tokenizer_handles_long_text(en_tokenizer):
 <INSERT_END> <INSERT>   text = """Tributes pour in for late British Labour Party leader

Tributes poured in from around the world Thursday
to the late Labour Party leader John Smith, who died earlier from a massive
heart attack aged 55.

In Washington, the US State Department issued a statement regretting "the
untimely death" of the rapier-tongued Scottish barrister and parliamentarian.

"Mr. Smith, throughout his distinguished"""
    tokens = en_tokenizer(text)
    assert len(tokens) == 76

@pytest.mark.parametrize('text,length', [
    ("The U.S. Army likes Shock and Awe.", 8),
    ("U.N. regulations are not a part of their concern.", 10),
    ("“Isn't it?”", 6),
    ("""Yes! "I'd rather have a walk", Ms. Comble sighed. """, 15),
    ("""'Me too!', Mr. P. Delaware cried. """, 11),
    ("They ran about 10km.", 6),
    # ("But then the 6,000-year ice age came...", 10)
    ])
def test_tokenizer_handles_cnts(en_tokenizer, text, length):
    tokens = en_tokenizer(text)
    assert len(tokens) == length
 <INSERT_END> <|endoftext|> # coding: utf-8
"""Test that longer and mixed texts are tokenized correctly."""

from __future__ import unicode_literals

import pytest

def test_tokenizer_handles_long_text(en_tokenizer):
    text = """Tributes pour in for late British Labour Party leader

Tributes poured in from around the world Thursday
to the late Labour Party leader John Smith, who died earlier from a massive
heart attack aged 55.

In Washington, the US State Department issued a statement regretting "the
untimely death" of the rapier-tongued Scottish barrister and parliamentarian.

"Mr. Smith, throughout his distinguished"""
    tokens = en_tokenizer(text)
    assert len(tokens) == 76

@pytest.mark.parametrize('text,length', [
    ("The U.S. Army likes Shock and Awe.", 8),
    ("U.N. regulations are not a part of their concern.", 10),
    ("“Isn't it?”", 6),
    ("""Yes! "I'd rather have a walk", Ms. Comble sighed. """, 15),
    ("""'Me too!', Mr. P. Delaware cried. """, 11),
    ("They ran about 10km.", 6),
    # ("But then the 6,000-year ice age came...", 10)
    ])
def test_tokenizer_handles_cnts(en_tokenizer, text, length):
    tokens = en_tokenizer(text)
    assert len(tokens) == length

Prompt: Add tests for longer and mixed English texts