import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'pyramid',
    'pyramid_debugtoolbar',
    'waitress',
    # PyBit and dependencies
    'pybit',
    'psycopg2',
    'amqplib',
    'jsonpickle',
    ]

setup(name='acmeio',
      version='0.0',
      description='acmeio',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pyramid pylons',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="acmeio",
      entry_points="""\
      [paste.app_factory]
      main = acmeio:main
      """,
      )

Response:
<INSERT> # PyBit and dependencies
    'pybit',
    'psycopg2',
    'amqplib',
    'jsonpickle',
    <INSERT_END> <|endoftext|> import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'pyramid',
    'pyramid_debugtoolbar',
    'waitress',
    # PyBit and dependencies
    'pybit',
    'psycopg2',
    'amqplib',
    'jsonpickle',
    ]

setup(name='acmeio',
      version='0.0',
      description='acmeio',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pyramid pylons',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="acmeio",
      entry_points="""\
      [paste.app_factory]
      main = acmeio:main
      """,
      )

Prompt:
Add pybit and its dependencies to this package's dependency list.

import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'pyramid',
    'pyramid_debugtoolbar',
    'waitress',
    ]

setup(name='acmeio',
      version='0.0',
      description='acmeio',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pyramid pylons',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="acmeio",
      entry_points="""\
      [paste.app_factory]
      main = acmeio:main
      """,
      )


#!/usr/bin/python

from __future__ import print_function
import sys

env_vars = {}

def read_file(path):
    try:
        with open(path, 'r') as f:
            return f.read().strip()
    except IOError:
        return None

def get_memory_limit():
    limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
    if limit is None:
        print("Warning: Can't detect memory limit from cgroups",
              file=sys.stderr)
        return
    env_vars['MEMORY_LIMIT_IN_BYTES'] = limit

def get_number_of_cores():
    core_count = 0

    line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
    if line is None:
        print("Warning: Can't detect number of CPU cores from cgroups",
              file=sys.stderr)
        return

    for group in line.split(','):
        core_ids = list(map(int, group.split('-')))
        if len(core_ids) == 2:
            core_count += core_ids[1] - core_ids[0] + 1
        else:
            core_count += 1

    env_vars['NUMBER_OF_CORES'] = str(core_count)

get_memory_limit()
get_number_of_cores()

print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
    print("=".join(item))

Print warnings to standard error

Print warnings to standard error

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

env_vars <REPLACE_NEW> #!/usr/bin/python

from __future__ import print_function
import sys

env_vars <REPLACE_END> <REPLACE_OLD> limit:
     <REPLACE_NEW> limit is None:
        print("Warning: Can't detect memory limit from cgroups",
              file=sys.stderr)
        return
 <REPLACE_END> <INSERT>        print("Warning: Can't detect number of CPU cores from cgroups",
              file=sys.stderr)
 <INSERT_END> <|endoftext|> #!/usr/bin/python

from __future__ import print_function
import sys

env_vars = {}

def read_file(path):
    try:
        with open(path, 'r') as f:
            return f.read().strip()
    except IOError:
        return None

def get_memory_limit():
    limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
    if limit is None:
        print("Warning: Can't detect memory limit from cgroups",
              file=sys.stderr)
        return
    env_vars['MEMORY_LIMIT_IN_BYTES'] = limit

def get_number_of_cores():
    core_count = 0

    line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
    if line is None:
        print("Warning: Can't detect number of CPU cores from cgroups",
              file=sys.stderr)
        return

    for group in line.split(','):
        core_ids = list(map(int, group.split('-')))
        if len(core_ids) == 2:
            core_count += core_ids[1] - core_ids[0] + 1
        else:
            core_count += 1

    env_vars['NUMBER_OF_CORES'] = str(core_count)

get_memory_limit()
get_number_of_cores()

print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
    print("=".join(item))

Prompt:
Print warnings to standard error

#!/usr/bin/python

env_vars = {}

def read_file(path):
    try:
        with open(path, 'r') as f:
            return f.read().strip()
    except IOError:
        return None

def get_memory_limit():
    limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
    if limit:
        env_vars['MEMORY_LIMIT_IN_BYTES'] = limit

def get_number_of_cores():
    core_count = 0

    line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
    if line is None:
        return

    for group in line.split(','):
        core_ids = list(map(int, group.split('-')))
        if len(core_ids) == 2:
            core_count += core_ids[1] - core_ids[0] + 1
        else:
            core_count += 1

    env_vars['NUMBER_OF_CORES'] = str(core_count)

get_memory_limit()
get_number_of_cores()

print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
    print("=".join(item))


"""Generate fake data for testing purposes."""

from faker import Faker
from random import randint
from GoPlayer import Player
from pprint import pprint

fake = Faker()

names = [fake.name() for x in range(49)]
ids = [x for x in range(49)]
ranks = [randint(-30, 7) for x in range(49)]

player_info = list(zip(names, ids, ranks))

player_list = []

for rec in player_info:
    player_list.append(Player(name=rec[0], aga_id=rec[1],
                              aga_rating=rec[2]))

Create fake data for testing

Create fake data for testing

Response:
<INSERT> """Generate fake data for testing purposes."""

from faker import Faker
from random import randint
from GoPlayer import Player
from pprint import pprint

fake = Faker()

names = [fake.name() for x in range(49)]
ids = [x for x in range(49)]
ranks = [randint(-30, 7) for x in range(49)]

player_info = list(zip(names, ids, ranks))

player_list = []

for rec in player_info:
 <INSERT_END> <INSERT>   player_list.append(Player(name=rec[0], aga_id=rec[1],
                              aga_rating=rec[2]))

 <INSERT_END> <|endoftext|> """Generate fake data for testing purposes."""

from faker import Faker
from random import randint
from GoPlayer import Player
from pprint import pprint

fake = Faker()

names = [fake.name() for x in range(49)]
ids = [x for x in range(49)]
ranks = [randint(-30, 7) for x in range(49)]

player_info = list(zip(names, ids, ranks))

player_list = []

for rec in player_info:
    player_list.append(Player(name=rec[0], aga_id=rec[1],
                              aga_rating=rec[2]))

Prompt: Create fake data for testing


# -*- coding: utf-8 -*-
"""Generate random story using trigrams."""
import io
import string

def read_file():
    """Open and read file input."""
    f = io.open('sherlock_small.txt', 'r')
    lines = ''.join(f.readlines())
    # print(lines)
    return lines

def strip_punct(text):
    """Do stuff."""
    # strip punct from
    # print(type(text))
    for c in string.punctuation:
        text = text.replace(c, ' ')
    return text

text = read_file()
print(strip_punct(text))

Add return statement to strip_punct

Add return statement to strip_punct

Response:
<INSERT> # <INSERT_END> <INSERT> text = <INSERT_END> <REPLACE_OLD> ')

text <REPLACE_NEW> ')
    return text

text <REPLACE_END> <REPLACE_OLD> read_file()
strip_punct(text)
 <REPLACE_NEW> read_file()
print(strip_punct(text))
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""Generate random story using trigrams."""
import io
import string

def read_file():
    """Open and read file input."""
    f = io.open('sherlock_small.txt', 'r')
    lines = ''.join(f.readlines())
    # print(lines)
    return lines

def strip_punct(text):
    """Do stuff."""
    # strip punct from
    # print(type(text))
    for c in string.punctuation:
        text = text.replace(c, ' ')
    return text

text = read_file()
print(strip_punct(text))

Prompt:
Add return statement to strip_punct

# -*- coding: utf-8 -*-
"""Generate random story using trigrams."""
import io
import string

def read_file():
    """Open and read file input."""
    f = io.open('sherlock_small.txt', 'r')
    lines = ''.join(f.readlines())
    print(lines)
    return lines

def strip_punct(text):
    """Do stuff."""
    # strip punct from
    # print(type(text))
    for c in string.punctuation:
        text.replace(c, ' ')

text = read_file()
strip_punct(text)


import sys
import time
from random import shuffle
from vania.fair_distributor import FairDistributor

def main():
    # User input for the number of targets and objects.
    users = ['user1', 'user2']
    tasks = ['task1', 'task2']
    preferences = [
        [1, 2],
        [2, 1],
    ]

    # Run solver
    distributor = FairDistributor(users, tasks, preferences)
    output = distributor.distribute(output='problem.lp')

    # Output
    print(output)

if __name__ == '__main__':
    main()

Response:
<DELETE> start_time = time.time()
    <DELETE_END> <REPLACE_OLD> distributor.distribute(output='problem.lp')
    elapsed_time = time.time() - start_time

 <REPLACE_NEW> distributor.distribute(output='problem.lp')

 <REPLACE_END> <|endoftext|> import sys
import time
from random import shuffle
from vania.fair_distributor import FairDistributor

def main():
    # User input for the number of targets and objects.
    users = ['user1', 'user2']
    tasks = ['task1', 'task2']
    preferences = [
        [1, 2],
        [2, 1],
    ]

    # Run solver
    distributor = FairDistributor(users, tasks, preferences)
    output = distributor.distribute(output='problem.lp')

    # Output
    print(output)

if __name__ == '__main__':
    main()

Prompt:
Remove time metrics from the simple example

import sys
import time
from random import shuffle
from vania.fair_distributor import FairDistributor

def main():
    # User input for the number of targets and objects.
    users = ['user1', 'user2']
    tasks = ['task1', 'task2']
    preferences = [
        [1, 2],
        [2, 1],
    ]

    # Run solver
    start_time = time.time()
    distributor = FairDistributor(users, tasks, preferences)
    output = distributor.distribute(output='problem.lp')
    elapsed_time = time.time() - start_time

    # Output
    print(output)

if __name__ == '__main__':
    main()


import numpy as np
from matplotlib import pylab as plt

np.random.seed(31415926)  # Set a seed for reproducibility

N_STEPS = 1000
random_data = np.random.randint(0, 2, N_STEPS)
# A symmetric random walk
random_walk = np.where(random_data > 0, 1, -1).cumsum()

N_WALKS = 1000
random_data_matrix = np.random.randint(0, 2, size=(N_WALKS, N_STEPS))

# Multiple symmetric random walks
multiple_random_walks = np.where(random_data_matrix > 0, 1, -1).cumsum(axis=1)

Add a symmetric random walk script

Add a symmetric random walk script

Response:
<INSERT> import numpy as np
from matplotlib import pylab as plt

np.random.seed(31415926) <INSERT_END> <INSERT> # Set a seed for reproducibility

N_STEPS = 1000
random_data = np.random.randint(0, 2, N_STEPS)
# A symmetric random walk
random_walk = np.where(random_data > 0, 1, -1).cumsum()

N_WALKS = 1000
random_data_matrix = np.random.randint(0, 2, size=(N_WALKS, N_STEPS))

# Multiple symmetric random walks
multiple_random_walks = np.where(random_data_matrix > 0, 1, -1).cumsum(axis=1)
 <INSERT_END> <|endoftext|> import numpy as np
from matplotlib import pylab as plt

np.random.seed(31415926)  # Set a seed for reproducibility

N_STEPS = 1000
random_data = np.random.randint(0, 2, N_STEPS)
# A symmetric random walk
random_walk = np.where(random_data > 0, 1, -1).cumsum()

N_WALKS = 1000
random_data_matrix = np.random.randint(0, 2, size=(N_WALKS, N_STEPS))

# Multiple symmetric random walks
multiple_random_walks = np.where(random_data_matrix > 0, 1, -1).cumsum(axis=1)

Prompt: Add a symmetric random walk script


from .dataset import Dataset, Volume, Vertex, VolumeRGB, VertexRGB, Volume2D, Vertex2D
from . import align, volume, quickflat, webgl, segment, options
from .database import db
from .utils import *
from .quickflat import make_figure as quickshow

try:
	from . import formats
except ImportError:
	raise ImportError("You are running pycortex from the source directory. Don't do that!")

load = Dataset.from_file

try:
	from . import webgl
	from .webgl import show as webshow
except ImportError:
	pass

try:
	from . import anat
except ImportError:
	pass

# Create deprecated interface for database
import warnings
class dep(object):
	def __getattr__(self, name):
		warnings.warn("cortex.surfs is deprecated, use cortex.db instead", Warning)
		return getattr(db, name)
	def __dir__(self):
		warnings.warn("cortex.surfs is deprecated, use cortex.db instead", Warning)
		return db.__dir__()
surfs = dep()

Add warning for source directory import

Add warning for source directory import

Response:
<REPLACE_OLD> quickshow

load <REPLACE_NEW> quickshow

try:
	from . import formats
except ImportError:
	raise ImportError("You are running pycortex from the source directory. Don't do that!")

load <REPLACE_END> <REPLACE_OLD> dep() <REPLACE_NEW> dep()
 <REPLACE_END> <|endoftext|> from .dataset import Dataset, Volume, Vertex, VolumeRGB, VertexRGB, Volume2D, Vertex2D
from . import align, volume, quickflat, webgl, segment, options
from .database import db
from .utils import *
from .quickflat import make_figure as quickshow

try:
	from . import formats
except ImportError:
	raise ImportError("You are running pycortex from the source directory. Don't do that!")

load = Dataset.from_file

try:
	from . import webgl
	from .webgl import show as webshow
except ImportError:
	pass

try:
	from . import anat
except ImportError:
	pass

# Create deprecated interface for database
import warnings
class dep(object):
	def __getattr__(self, name):
		warnings.warn("cortex.surfs is deprecated, use cortex.db instead", Warning)
		return getattr(db, name)
	def __dir__(self):
		warnings.warn("cortex.surfs is deprecated, use cortex.db instead", Warning)
		return db.__dir__()
surfs = dep()

Prompt:
Add warning for source directory import

from .dataset import Dataset, Volume, Vertex, VolumeRGB, VertexRGB, Volume2D, Vertex2D
from . import align, volume, quickflat, webgl, segment, options
from .database import db
from .utils import *
from .quickflat import make_figure as quickshow

load = Dataset.from_file

try:
	from . import webgl
	from .webgl import show as webshow
except ImportError:
	pass

try:
	from . import anat
except ImportError:
	pass

# Create deprecated interface for database
import warnings
class dep(object):
	def __getattr__(self, name):
		warnings.warn("cortex.surfs is deprecated, use cortex.db instead", Warning)
		return getattr(db, name)
	def __dir__(self):
		warnings.warn("cortex.surfs is deprecated, use cortex.db instead", Warning)
		return db.__dir__()
surfs = dep()


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

import unittest
import numpy as np
import numpy.testing as npt
from dipy.core.gradients import gradient_table
from generateSyntheticData import (generateSyntheticInputs,
                                   generateSyntheticOutputsFromMultiTensorModel)

class integration_test_generateSyntheticData(unittest.TestCase):

    def test_dataGeneration(self):
        voxelsInEachDim = (2, 3, 4)

        bvals=1500*np.ones(7)
        bvals[0]=0
        sq2=np.sqrt(2)/2
        bvecs=np.array([[0, 0, 0],
                        [1, 0, 0],
                        [0, 1, 0],
                        [0, 0, 1],
                        [sq2, sq2, 0],
                        [sq2, 0, sq2],
                        [0, sq2, sq2]])
        smallDelta = 12.9
        bigDelta = 21.8
        gtab = gradient_table(bvals, bvecs, big_delta=bigDelta,
                              small_delta=smallDelta)

        # Diffusion coefficients for white matter tracts, in mm^2/s
        #
        # Based roughly on values from:
        #
        #   Pierpaoli, Basser, "Towards a Quantitative Assessment of Diffusion
        #   Anisotropy", Magnetic Resonance in Medicine, 1996; 36(6):893-906.
        #
        whiteMatterDiffusionEigenvalues = np.array([1500e-6, 400e-6, 400e-6])
        tensorEigenvalues = np.tile(whiteMatterDiffusionEigenvalues, (2,1))

        inputs = generateSyntheticInputs(voxelsInEachDim, gtab)
        outputs = generateSyntheticOutputsFromMultiTensorModel(
            voxelsInEachDim, gtab, tensorEigenvalues)

        totalNumberOfSamples = np.prod(voxelsInEachDim)*len(bvals)
        npt.assert_array_equal(inputs.shape,
                               (totalNumberOfSamples, 7),
                               'Input shapes don\'t match')
        npt.assert_array_equal(outputs.shape, (totalNumberOfSamples,),
                               'Output shapes don\'t match')

        # add spatial correlations - easiest to mock an exact signal in each
        # voxel with known correlation.

def main():
    unittest.main()

if __name__ == '__main__':
    main()

Test that shapes of input and output match up

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

import unittest
import numpy as np
import numpy.testing as npt
from dipy.core.gradients import gradient_table
from generateSyntheticData import (generateSyntheticInputs,
                                   generateSyntheticOutputsFromMultiTensorModel)

class integration_test_generateSyntheticData(unittest.TestCase):

    def test_dataGeneration(self):
        voxelsInEachDim = (2, 3, 4)

        bvals=1500*np.ones(7)
        bvals[0]=0
        sq2=np.sqrt(2)/2
        bvecs=np.array([[0, 0, 0],
                        [1, 0, 0],
                        [0, 1, 0],
                        [0, 0, 1],
                        [sq2, sq2, 0],
                        [sq2, 0, sq2],
                        [0, sq2, sq2]])
        smallDelta = 12.9
        bigDelta = 21.8
        gtab = gradient_table(bvals, bvecs, big_delta=bigDelta,
                              small_delta=smallDelta)

        # Diffusion coefficients for white matter tracts, in mm^2/s
        #
        # Based roughly on values from:
        #
        #   Pierpaoli, Basser, "Towards a Quantitative Assessment of Diffusion
        #   Anisotropy", Magnetic Resonance in Medicine, 1996; 36(6):893-906.
        #
        whiteMatterDiffusionEigenvalues = np.array([1500e-6, 400e-6, 400e-6])
        tensorEigenvalues = np.tile(whiteMatterDiffusionEigenvalues, (2,1))

        inputs = generateSyntheticInputs(voxelsInEachDim, gtab)
        outputs = generateSyntheticOutputsFromMultiTensorModel(
            voxelsInEachDim, gtab, tensorEigenvalues)

        totalNumberOfSamples = np.prod(voxelsInEachDim)*len(bvals)
        npt.assert_array_equal(inputs.shape,
                               (totalNumberOfSamples, 7),
                               'Input shapes don\'t match')
        npt.assert_array_equal(outputs.shape, (totalNumberOfSamples,),
                               'Output shapes don\'t match')

        # add spatial correlations - easiest to mock an exact signal in each
        # voxel with known correlation.

def main():
    unittest.main()

if __name__ == '__main__':
    main() <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import unittest
import numpy as np
import numpy.testing as npt
from dipy.core.gradients import gradient_table
from generateSyntheticData import (generateSyntheticInputs,
                                   generateSyntheticOutputsFromMultiTensorModel)

class integration_test_generateSyntheticData(unittest.TestCase):

    def test_dataGeneration(self):
        voxelsInEachDim = (2, 3, 4)

        bvals=1500*np.ones(7)
        bvals[0]=0
        sq2=np.sqrt(2)/2
        bvecs=np.array([[0, 0, 0],
                        [1, 0, 0],
                        [0, 1, 0],
                        [0, 0, 1],
                        [sq2, sq2, 0],
                        [sq2, 0, sq2],
                        [0, sq2, sq2]])
        smallDelta = 12.9
        bigDelta = 21.8
        gtab = gradient_table(bvals, bvecs, big_delta=bigDelta,
                              small_delta=smallDelta)

        # Diffusion coefficients for white matter tracts, in mm^2/s
        #
        # Based roughly on values from:
        #
        #   Pierpaoli, Basser, "Towards a Quantitative Assessment of Diffusion
        #   Anisotropy", Magnetic Resonance in Medicine, 1996; 36(6):893-906.
        #
        whiteMatterDiffusionEigenvalues = np.array([1500e-6, 400e-6, 400e-6])
        tensorEigenvalues = np.tile(whiteMatterDiffusionEigenvalues, (2,1))

        inputs = generateSyntheticInputs(voxelsInEachDim, gtab)
        outputs = generateSyntheticOutputsFromMultiTensorModel(
            voxelsInEachDim, gtab, tensorEigenvalues)

        totalNumberOfSamples = np.prod(voxelsInEachDim)*len(bvals)
        npt.assert_array_equal(inputs.shape,
                               (totalNumberOfSamples, 7),
                               'Input shapes don\'t match')
        npt.assert_array_equal(outputs.shape, (totalNumberOfSamples,),
                               'Output shapes don\'t match')

        # add spatial correlations - easiest to mock an exact signal in each
        # voxel with known correlation.

def main():
    unittest.main()

if __name__ == '__main__':
    main()

Prompt: Test that shapes of input and output match up


from setuptools import setup

REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'

setup(
    author='Serenata de Amor',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Utilities',
    ],
    description='Toolbox for Serenata de Amor project',
    zip_safe=False,
    install_requires=[
        'aiofiles',
        'aiohttp',
        'boto3',
        'beautifulsoup4>=4.4',
        'lxml>=3.6',
        'pandas>=0.18',
        'tqdm'
    ],
    keywords='serenata de amor, data science, brazil, corruption',
    license='MIT',
    long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
    name='serenata-toolbox',
    packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'],
    url=REPO_URL,
    version='9.1.0'
)

Fix the version to correct one

Fix the version to correct one

Response:
<REPLACE_OLD> version='9.0.4'
)
 <REPLACE_NEW> version='9.1.0'
)
 <REPLACE_END> <|endoftext|> from setuptools import setup

REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'

setup(
    author='Serenata de Amor',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Utilities',
    ],
    description='Toolbox for Serenata de Amor project',
    zip_safe=False,
    install_requires=[
        'aiofiles',
        'aiohttp',
        'boto3',
        'beautifulsoup4>=4.4',
        'lxml>=3.6',
        'pandas>=0.18',
        'tqdm'
    ],
    keywords='serenata de amor, data science, brazil, corruption',
    license='MIT',
    long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
    name='serenata-toolbox',
    packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'],
    url=REPO_URL,
    version='9.1.0'
)

Prompt:
Fix the version to correct one

from setuptools import setup

REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'

setup(
    author='Serenata de Amor',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Utilities',
    ],
    description='Toolbox for Serenata de Amor project',
    zip_safe=False,
    install_requires=[
        'aiofiles',
        'aiohttp',
        'boto3',
        'beautifulsoup4>=4.4',
        'lxml>=3.6',
        'pandas>=0.18',
        'tqdm'
    ],
    keywords='serenata de amor, data science, brazil, corruption',
    license='MIT',
    long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
    name='serenata-toolbox',
    packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'],
    url=REPO_URL,
    version='9.0.4'
)


import webbrowser

import tweepy

"""
    Query the user for their consumer key/secret
    then attempt to fetch a valid access token.
"""

if __name__ == "__main__":

    consumer_key = raw_input('Consumer key: ').strip()
    consumer_secret = raw_input('Consumer secret: ').strip()
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

    # Open authorization URL in browser
    webbrowser.open(auth.get_authorization_url())

    # Ask user for verifier pin
    pin = raw_input('Verification pin number from twitter.com: ').strip()

    # Get access token
    token = auth.get_access_token(verifier=pin)

    # Give user the access token
    print 'Access token:'
    print '  Key: %s' % token.key
    print '  Secret: %s' % token.secret

Add an oauth example script.

Add an oauth example script.

Response:
<INSERT> import webbrowser

import tweepy

"""
 <INSERT_END> <INSERT>   Query the user for their consumer key/secret
    then attempt to fetch a valid access token.
"""

if __name__ == "__main__":

    consumer_key = raw_input('Consumer key: ').strip()
    consumer_secret = raw_input('Consumer secret: ').strip()
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

    # Open authorization URL in browser
    webbrowser.open(auth.get_authorization_url())

    # Ask user for verifier pin
    pin = raw_input('Verification pin number from twitter.com: ').strip()

    # Get access token
    token = auth.get_access_token(verifier=pin)

    # Give user the access token
    print 'Access token:'
    print '  Key: %s' % token.key
    print '  Secret: %s' % token.secret

 <INSERT_END> <|endoftext|> import webbrowser

import tweepy

"""
    Query the user for their consumer key/secret
    then attempt to fetch a valid access token.
"""

if __name__ == "__main__":

    consumer_key = raw_input('Consumer key: ').strip()
    consumer_secret = raw_input('Consumer secret: ').strip()
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

    # Open authorization URL in browser
    webbrowser.open(auth.get_authorization_url())

    # Ask user for verifier pin
    pin = raw_input('Verification pin number from twitter.com: ').strip()

    # Get access token
    token = auth.get_access_token(verifier=pin)

    # Give user the access token
    print 'Access token:'
    print '  Key: %s' % token.key
    print '  Secret: %s' % token.secret

Prompt: Add an oauth example script.


from django.conf.urls import patterns, include, url
from tastypie.api import Api
from tracker.api import UserResource, TaskResource, WorkSessionResource, \
    RegistrationResource

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

# tracker API.
v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(RegistrationResource())
v1_api.register(TaskResource())
v1_api.register(WorkSessionResource())

urlpatterns = patterns('',
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include(v1_api.urls)),
)

Response:
<REPLACE_OLD> WorkSessionResource

# <REPLACE_NEW> WorkSessionResource, \
    RegistrationResource

# <REPLACE_END> <REPLACE_OLD> Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(TaskResource())
v1_api.register(WorkSessionResource())

urlpatterns <REPLACE_NEW> Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(RegistrationResource())
v1_api.register(TaskResource())
v1_api.register(WorkSessionResource())

urlpatterns <REPLACE_END> <REPLACE_OLD> include(v1_api.urls())),
)
 <REPLACE_NEW> include(v1_api.urls)),
)
 <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include, url
from tastypie.api import Api
from tracker.api import UserResource, TaskResource, WorkSessionResource, \
    RegistrationResource

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

# tracker API.
v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(RegistrationResource())
v1_api.register(TaskResource())
v1_api.register(WorkSessionResource())

urlpatterns = patterns('',
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include(v1_api.urls)),
)

Prompt:
Fix minor issue, reorganize imports, and register the RegistrationResource with the API.

from django.conf.urls import patterns, include, url
from tastypie.api import Api
from tracker.api import UserResource, TaskResource, WorkSessionResource

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

# tracker API.
v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(TaskResource())
v1_api.register(WorkSessionResource())

urlpatterns = patterns('',
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include(v1_api.urls())),
)


#!/usr/bin/env python

# Copyright 2019 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.

import sys
import json

full_search = len(sys.argv) > 3 and sys.argv[3] == '--full'

with open(sys.argv[1]) as f:
    data = f.readlines()
    thread = None
    for entry in data:
        entry = json.loads(entry)
        if thread and "thread" in entry:
            if entry["thread"] == thread:
                print(json.dumps(entry))
                if "action" in entry and entry["action"] == "test_end":
                    thread = None
        else:
            if "action" in entry and \
               entry["action"] == "test_start" and \
               entry["test"] == sys.argv[2]:
                thread = entry["thread"]
                print(json.dumps(entry))
            elif full_search and \
                 "command" in entry and \
                 sys.argv[2] in entry["command"]:
                thread = entry["thread"]
                print(json.dumps(entry))

Add a script to extra logs for particular test filenames from full WPT logs.

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

# Copyright 2019 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.

import sys
import json

full_search = len(sys.argv) > 3 and sys.argv[3] == '--full'

with open(sys.argv[1]) as f:
    data = f.readlines()
    thread = None
    for entry in data:
        entry = json.loads(entry)
        if thread and "thread" in entry:
            if entry["thread"] == thread:
                print(json.dumps(entry))
                if "action" in entry and entry["action"] == "test_end":
                    thread = None
        else:
            if "action" in entry and \
               entry["action"] == "test_start" and \
               entry["test"] == sys.argv[2]:
                thread = entry["thread"]
                print(json.dumps(entry))
            elif full_search and \
                 "command" in entry and \
                 sys.argv[2] in entry["command"]:
                thread = entry["thread"]
                print(json.dumps(entry))
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

# Copyright 2019 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.

import sys
import json

full_search = len(sys.argv) > 3 and sys.argv[3] == '--full'

with open(sys.argv[1]) as f:
    data = f.readlines()
    thread = None
    for entry in data:
        entry = json.loads(entry)
        if thread and "thread" in entry:
            if entry["thread"] == thread:
                print(json.dumps(entry))
                if "action" in entry and entry["action"] == "test_end":
                    thread = None
        else:
            if "action" in entry and \
               entry["action"] == "test_start" and \
               entry["test"] == sys.argv[2]:
                thread = entry["thread"]
                print(json.dumps(entry))
            elif full_search and \
                 "command" in entry and \
                 sys.argv[2] in entry["command"]:
                thread = entry["thread"]
                print(json.dumps(entry))

Prompt: Add a script to extra logs for particular test filenames from full WPT logs.


# -*- coding: utf-8 -*-
msg = {
	'en': {
                'commons-file-moved' : u'[[:File:%s|File]] moved to [[:commons:File:%s|commons]].',
                'commons-file-now-available' : u'File is now available on Wikimedia Commons.',
	},
	'qqq': {
		'commons-file-now-available' : u'Edit summary when the bot has moved a file to Commons and adds the NowCommons template.',
                'commons-file-moved' : u'Edit summary when the bot replaces usage of an image available under a different name.',
	},
}

Remove the template for now.

Response:
<REPLACE_OLD> Commons.',
                'commons-nowcommons-template' <REPLACE_NEW> Commons.',
	},
	'qqq': {
		'commons-file-now-available' <REPLACE_END> <DELETE> 'en': u'{{subst:ncd|%s}}',
	},
	'qqq': {
		'commons-file-now-available': <DELETE_END> <REPLACE_OLD> 'commons-file-moved': <REPLACE_NEW> 'commons-file-moved' : <REPLACE_END> <REPLACE_OLD> name.',
                'commons-nowcommons-template' : 'en': u'The template to be added by the bot when a file is available at Commons. %s is the filename at Commons.',
	},
}
 <REPLACE_NEW> name.',
	},
}
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
msg = {
	'en': {
                'commons-file-moved' : u'[[:File:%s|File]] moved to [[:commons:File:%s|commons]].',
                'commons-file-now-available' : u'File is now available on Wikimedia Commons.',
	},
	'qqq': {
		'commons-file-now-available' : u'Edit summary when the bot has moved a file to Commons and adds the NowCommons template.',
                'commons-file-moved' : u'Edit summary when the bot replaces usage of an image available under a different name.',
	},
}

Prompt:
Remove the template for now.

git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@9344 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6

# -*- coding: utf-8 -*-
msg = {
	'en': {
                'commons-file-moved' : u'[[:File:%s|File]] moved to [[:commons:File:%s|commons]].',
                'commons-file-now-available' : u'File is now available on Wikimedia Commons.',
                'commons-nowcommons-template' : 'en': u'{{subst:ncd|%s}}',
	},
	'qqq': {
		'commons-file-now-available': u'Edit summary when the bot has moved a file to Commons and adds the NowCommons template.',
                'commons-file-moved': u'Edit summary when the bot replaces usage of an image available under a different name.',
                'commons-nowcommons-template' : 'en': u'The template to be added by the bot when a file is available at Commons. %s is the filename at Commons.',
	},
}


#!/usr/bin/env python

import os
import pprint

import preconditions as precond
from gr1_specification import GR1Specification
from gr1_formulas import GR1Formula, FastSlowFormula

"""
Module's docstring #TODO
"""

VIGIR_ROOT_DIR = os.environ['VIGIR_ROOT_DIR']

class TaskSpecification(GR1Specification):
	"""..."""

	def __init__(self, spec_name = '', env_props = [], sys_props = []):
		super(TaskSpecification, self).__init__(spec_name, env_props, sys_props)

# =========================================================
# Entry point
# =========================================================

def main():

	my_spec = TaskSpecification()

	print 'Environment props:\t', my_spec.env_props
	print 'System props:\t\t', my_spec.sys_props

if __name__ == "__main__":
	main()

Add module for task-specific specs

[vigir_ltl_specification] Add module for task-specific specs

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

import os
import pprint

import preconditions as precond
from gr1_specification import GR1Specification
from gr1_formulas import GR1Formula, FastSlowFormula

"""
Module's docstring #TODO
"""

VIGIR_ROOT_DIR = os.environ['VIGIR_ROOT_DIR']

class TaskSpecification(GR1Specification):
	"""..."""

	def __init__(self, spec_name = '', env_props = [], sys_props = []):
		super(TaskSpecification, self).__init__(spec_name, env_props, sys_props)

# =========================================================
# Entry point
# =========================================================

def main():

	my_spec = TaskSpecification()

	print 'Environment props:\t', my_spec.env_props
	print 'System props:\t\t', my_spec.sys_props

if __name__ == "__main__":
	main()
	 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os
import pprint

import preconditions as precond
from gr1_specification import GR1Specification
from gr1_formulas import GR1Formula, FastSlowFormula

"""
Module's docstring #TODO
"""

VIGIR_ROOT_DIR = os.environ['VIGIR_ROOT_DIR']

class TaskSpecification(GR1Specification):
	"""..."""

	def __init__(self, spec_name = '', env_props = [], sys_props = []):
		super(TaskSpecification, self).__init__(spec_name, env_props, sys_props)

# =========================================================
# Entry point
# =========================================================

def main():

	my_spec = TaskSpecification()

	print 'Environment props:\t', my_spec.env_props
	print 'System props:\t\t', my_spec.sys_props

if __name__ == "__main__":
	main()

Prompt: [vigir_ltl_specification] Add module for task-specific specs


"""FreeBSD port building infrastructure."""

from __future__ import absolute_import

from . import event

def stop(kill=False, kill_clean=False):
  """Stop building ports and cleanup."""
  from os import killpg
  from signal import SIGTERM, SIGKILL
  from .builder import builders
  from .env import cpus, flags
  from .queue import attr_queue, clean_queue, queues
  from .subprocess import children

  if flags["no_op"]:
    raise SystemExit(254)

  flags["mode"] = "clean"

  if kill_clean:
    cleaning = ()
  else:
    cleaning = set(i.pid for i in clean_queue.active)

  # Kill all active children
  for pid in children():
    if pid not in cleaning:
      try:
        killpg(pid, SIGKILL if kill else SIGTERM)
      except OSError:
        pass

  # Stop all queues
  attr_queue.load = 0
  for queue in queues:
    queue.load = 0

  # Make cleaning go a bit faster
  if kill_clean:
    clean_queue.load = 0
    return
  else:
    clean_queue.load = cpus

  # Wait for all active ports to finish so that they may be cleaned
  active = set()
  for queue in queues:
    for job in queue.active:
      port = job.port
      active.add(port)
      port.stage_completed.connect(lambda x: x.clean())

  # Clean all other outstanding ports
  for builder in builders:
    for port in builder.ports:
      if port not in active:
        port.clean()

Response:
<REPLACE_OLD> exit(254)

 <REPLACE_NEW> raise SystemExit(254)

 <REPLACE_END> <|endoftext|> """FreeBSD port building infrastructure."""

from __future__ import absolute_import

from . import event

def stop(kill=False, kill_clean=False):
  """Stop building ports and cleanup."""
  from os import killpg
  from signal import SIGTERM, SIGKILL
  from .builder import builders
  from .env import cpus, flags
  from .queue import attr_queue, clean_queue, queues
  from .subprocess import children

  if flags["no_op"]:
    raise SystemExit(254)

  flags["mode"] = "clean"

  if kill_clean:
    cleaning = ()
  else:
    cleaning = set(i.pid for i in clean_queue.active)

  # Kill all active children
  for pid in children():
    if pid not in cleaning:
      try:
        killpg(pid, SIGKILL if kill else SIGTERM)
      except OSError:
        pass

  # Stop all queues
  attr_queue.load = 0
  for queue in queues:
    queue.load = 0

  # Make cleaning go a bit faster
  if kill_clean:
    clean_queue.load = 0
    return
  else:
    clean_queue.load = cpus

  # Wait for all active ports to finish so that they may be cleaned
  active = set()
  for queue in queues:
    for job in queue.active:
      port = job.port
      active.add(port)
      port.stage_completed.connect(lambda x: x.clean())

  # Clean all other outstanding ports
  for builder in builders:
    for port in builder.ports:
      if port not in active:
        port.clean()

Prompt:
Use SystemExit, not exit() to initiate a shutdown.

exit() has unintented side affects, such as closing stdin, that are
undesired as stdin is assumed to be writable while libpb/event/run
unwinds (i.e. Top monitor).

"""FreeBSD port building infrastructure."""

from __future__ import absolute_import

from . import event

def stop(kill=False, kill_clean=False):
  """Stop building ports and cleanup."""
  from os import killpg
  from signal import SIGTERM, SIGKILL
  from .builder import builders
  from .env import cpus, flags
  from .queue import attr_queue, clean_queue, queues
  from .subprocess import children

  if flags["no_op"]:
    exit(254)

  flags["mode"] = "clean"

  if kill_clean:
    cleaning = ()
  else:
    cleaning = set(i.pid for i in clean_queue.active)

  # Kill all active children
  for pid in children():
    if pid not in cleaning:
      try:
        killpg(pid, SIGKILL if kill else SIGTERM)
      except OSError:
        pass

  # Stop all queues
  attr_queue.load = 0
  for queue in queues:
    queue.load = 0

  # Make cleaning go a bit faster
  if kill_clean:
    clean_queue.load = 0
    return
  else:
    clean_queue.load = cpus

  # Wait for all active ports to finish so that they may be cleaned
  active = set()
  for queue in queues:
    for job in queue.active:
      port = job.port
      active.add(port)
      port.stage_completed.connect(lambda x: x.clean())

  # Clean all other outstanding ports
  for builder in builders:
    for port in builder.ports:
      if port not in active:
        port.clean()


import madam
from flask import Flask

app = Flask(__name__)
app.from_object('config')

asset_manager = madam.Madam()
asset_storage = madam.core.ShelveStorage(app.config['ASSET_STORAGE_PATH'])

from madam_rest import views

Create shelve asset storage by default.

Create shelve asset storage by default.

Response:
<REPLACE_OLD> from <REPLACE_NEW> import madam
from <REPLACE_END> <REPLACE_OLD> Flask
from madam import Madam

app <REPLACE_NEW> Flask

app <REPLACE_END> <REPLACE_OLD> Madam()
asset_storage <REPLACE_NEW> madam.Madam()
asset_storage <REPLACE_END> <REPLACE_OLD> app.config['ASSET_STORAGE']

from <REPLACE_NEW> madam.core.ShelveStorage(app.config['ASSET_STORAGE_PATH'])

from <REPLACE_END> <|endoftext|> import madam
from flask import Flask

app = Flask(__name__)
app.from_object('config')

asset_manager = madam.Madam()
asset_storage = madam.core.ShelveStorage(app.config['ASSET_STORAGE_PATH'])

from madam_rest import views

Prompt:
Create shelve asset storage by default.

from flask import Flask
from madam import Madam

app = Flask(__name__)
app.from_object('config')

asset_manager = Madam()
asset_storage = app.config['ASSET_STORAGE']

from madam_rest import views


# -*- coding:utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Developers
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Spyder unitest plugin."""

# Local imports
from .unittest import UnitTestPlugin as PLUGIN_CLASS

VERSION_INFO = (0, 1, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))

Add version information and header

Add version information and header

Response:
<REPLACE_OLD> from <REPLACE_NEW> # -*- coding:utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Developers
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Spyder unitest plugin."""

# Local imports
from <REPLACE_END> <REPLACE_OLD> PLUGIN_CLASS
 <REPLACE_NEW> PLUGIN_CLASS

VERSION_INFO = (0, 1, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))
 <REPLACE_END> <|endoftext|> # -*- coding:utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Developers
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Spyder unitest plugin."""

# Local imports
from .unittest import UnitTestPlugin as PLUGIN_CLASS

VERSION_INFO = (0, 1, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))

Prompt:
Add version information and header
from .unittest import UnitTestPlugin as PLUGIN_CLASS


from setuptools import setup
#from osrm import __version__

with open("requirements.txt") as f:
    requirements = f.read().split('\n')

setup(
    author_email="ustroetz@gmail.com",
    author="Uli Strötz, mthh",
    description="A Python wrapper around the OSRM API",
    install_requires=requirements,
    name='osrm',
    packages=['osrm'],
    test_suite="tests",
    url="https://github.com/ustroetz/python-osrm",
    version='0.11.3'
)

Fix typo in author name

Fix typo in author name

Response:
<REPLACE_OLD> author="Ulric Stroetz, <REPLACE_NEW> author="Uli Strötz, <REPLACE_END> <|endoftext|> from setuptools import setup
#from osrm import __version__

with open("requirements.txt") as f:
    requirements = f.read().split('\n')

setup(
    author_email="ustroetz@gmail.com",
    author="Uli Strötz, mthh",
    description="A Python wrapper around the OSRM API",
    install_requires=requirements,
    name='osrm',
    packages=['osrm'],
    test_suite="tests",
    url="https://github.com/ustroetz/python-osrm",
    version='0.11.3'
)

Prompt:
Fix typo in author name

from setuptools import setup
#from osrm import __version__

with open("requirements.txt") as f:
    requirements = f.read().split('\n')

setup(
    author_email="ustroetz@gmail.com",
    author="Ulric Stroetz, mthh",
    description="A Python wrapper around the OSRM API",
    install_requires=requirements,
    name='osrm',
    packages=['osrm'],
    test_suite="tests",
    url="https://github.com/ustroetz/python-osrm",
    version='0.11.3'
)


from django.core.management.base import BaseCommand
from app.models import Tunnel

class Command(BaseCommand):
    help = "Create superuser if missing (Non Interactive)."

    def add_arguments(self, parser):
        parser.add_argument('tunnel', nargs='*', type=int)

    def handle(self, *args, **kwargs):
        if kwargs['tunnel']:
            tunnels = Tunnel.objects.filter(id__in=kwargs['tunnel'])
        else:
            tunnels = Tunnel.objects.all()
        for tunnel in tunnels:
            self.stdout.write("Resetting tunnel %d..." % tunnel.id)
            tunnel.reset()

Add reset tunnels management command

Add reset tunnels management command

Response:
<INSERT> from django.core.management.base import BaseCommand
from app.models import Tunnel

class Command(BaseCommand):
 <INSERT_END> <INSERT>   help = "Create superuser if missing (Non Interactive)."

    def add_arguments(self, parser):
        parser.add_argument('tunnel', nargs='*', type=int)

    def handle(self, *args, **kwargs):
        if kwargs['tunnel']:
            tunnels = Tunnel.objects.filter(id__in=kwargs['tunnel'])
        else:
            tunnels = Tunnel.objects.all()
        for tunnel in tunnels:
            self.stdout.write("Resetting tunnel %d..." % tunnel.id)
            tunnel.reset()
 <INSERT_END> <|endoftext|> from django.core.management.base import BaseCommand
from app.models import Tunnel

class Command(BaseCommand):
    help = "Create superuser if missing (Non Interactive)."

    def add_arguments(self, parser):
        parser.add_argument('tunnel', nargs='*', type=int)

    def handle(self, *args, **kwargs):
        if kwargs['tunnel']:
            tunnels = Tunnel.objects.filter(id__in=kwargs['tunnel'])
        else:
            tunnels = Tunnel.objects.all()
        for tunnel in tunnels:
            self.stdout.write("Resetting tunnel %d..." % tunnel.id)
            tunnel.reset()

Prompt: Add reset tunnels management command


# Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015  Mercier Pierre-Olivier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from nemubot.message import Command, DirectAsk, Text
from nemubot.message.printer.socket import Socket as SocketVisitor

class TestSocketPrinter(unittest.TestCase):

    def setUp(self):
        self.msgs = [
            # Texts
            (
                Text(message="TEXT",
                ),
                "TEXT"
            ),
            (
                Text(message="TEXT TEXT2",
                ),
                "TEXT TEXT2"
            ),
            (
                Text(message="TEXT @ARG=1 TEXT2",
                ),
                "TEXT @ARG=1 TEXT2"
            ),

            # DirectAsk
            (
                DirectAsk(message="TEXT",
                          designated="someone",
                          to=["#somechannel"]
                ),
                "someone: TEXT"
            ),
            (
                # Private message to someone
                DirectAsk(message="TEXT",
                          designated="someone",
                          to=["someone"]
                ),
                "TEXT"
            ),

            # Commands
            (
                Command(cmd="COMMAND",
                ),
                "!COMMAND"
            ),
            (
                Command(cmd="COMMAND",
                        args=["TEXT"],
                ),
                "!COMMAND TEXT"
            ),
        ]

    def test_printer(self):
        for msg, pp in self.msgs:
            sv = SocketVisitor()
            msg.accept(sv)
            self.assertEqual(sv.pp, pp)

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

Add test for socket printer

Add test for socket printer

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015  Mercier Pierre-Olivier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from nemubot.message import Command, DirectAsk, Text
from nemubot.message.printer.socket import Socket as SocketVisitor

class TestSocketPrinter(unittest.TestCase):

    def setUp(self):
        self.msgs = [
            # Texts
            (
                Text(message="TEXT",
                ),
                "TEXT"
            ),
            (
                Text(message="TEXT TEXT2",
                ),
                "TEXT TEXT2"
            ),
            (
                Text(message="TEXT @ARG=1 TEXT2",
                ),
                "TEXT @ARG=1 TEXT2"
            ),

            # DirectAsk
            (
                DirectAsk(message="TEXT",
                          designated="someone",
                          to=["#somechannel"]
                ),
                "someone: TEXT"
            ),
            (
                # Private message to someone
                DirectAsk(message="TEXT",
                          designated="someone",
                          to=["someone"]
                ),
                "TEXT"
            ),

            # Commands
            (
                Command(cmd="COMMAND",
                ),
                "!COMMAND"
            ),
            (
                Command(cmd="COMMAND",
                        args=["TEXT"],
                ),
                "!COMMAND TEXT"
            ),
        ]

    def test_printer(self):
        for msg, pp in self.msgs:
            sv = SocketVisitor()
            msg.accept(sv)
            self.assertEqual(sv.pp, pp)

if __name__ == '__main__':
    unittest.main()
 <REPLACE_END> <|endoftext|> # Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015  Mercier Pierre-Olivier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from nemubot.message import Command, DirectAsk, Text
from nemubot.message.printer.socket import Socket as SocketVisitor

class TestSocketPrinter(unittest.TestCase):

    def setUp(self):
        self.msgs = [
            # Texts
            (
                Text(message="TEXT",
                ),
                "TEXT"
            ),
            (
                Text(message="TEXT TEXT2",
                ),
                "TEXT TEXT2"
            ),
            (
                Text(message="TEXT @ARG=1 TEXT2",
                ),
                "TEXT @ARG=1 TEXT2"
            ),

            # DirectAsk
            (
                DirectAsk(message="TEXT",
                          designated="someone",
                          to=["#somechannel"]
                ),
                "someone: TEXT"
            ),
            (
                # Private message to someone
                DirectAsk(message="TEXT",
                          designated="someone",
                          to=["someone"]
                ),
                "TEXT"
            ),

            # Commands
            (
                Command(cmd="COMMAND",
                ),
                "!COMMAND"
            ),
            (
                Command(cmd="COMMAND",
                        args=["TEXT"],
                ),
                "!COMMAND TEXT"
            ),
        ]

    def test_printer(self):
        for msg, pp in self.msgs:
            sv = SocketVisitor()
            msg.accept(sv)
            self.assertEqual(sv.pp, pp)

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

Prompt: Add test for socket printer


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

import os
from distutils.core import setup

setup(
    name='regulations-parser',
    url='https://github.com/cfpb/regulations-parser',
    author='CFPB',
    author_email='tech@cfpb.gov',
    license='CC0',
    version='0.1.0',
    description='eCFR Parser for eRegulations',
    long_description=open('README.md').read()
            if os.path.exists('README.md') else '',

    packages=['regparser', ],
    include_package_data=True,
    install_requires=[
        'lxml',
        'pyparsing',
        'inflection',
        'requests',
        'GitPython',
        'python-constraint',
    ],
    setup_requires=[
        'nose>=1.0'
    ],

    test_suite='xtdiff.tests',
)

Make the parser an installable Python package

Response:
<INSERT> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from distutils.core import setup

setup(
 <INSERT_END> <INSERT>   name='regulations-parser',
    url='https://github.com/cfpb/regulations-parser',
    author='CFPB',
    author_email='tech@cfpb.gov',
    license='CC0',
    version='0.1.0',
    description='eCFR Parser for eRegulations',
    long_description=open('README.md').read()
            if os.path.exists('README.md') else '',

    packages=['regparser', ],
    include_package_data=True,
    install_requires=[
        'lxml',
        'pyparsing',
        'inflection',
        'requests',
        'GitPython',
        'python-constraint',
    ],
    setup_requires=[
        'nose>=1.0'
    ],

    test_suite='xtdiff.tests',
)
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from distutils.core import setup

setup(
    name='regulations-parser',
    url='https://github.com/cfpb/regulations-parser',
    author='CFPB',
    author_email='tech@cfpb.gov',
    license='CC0',
    version='0.1.0',
    description='eCFR Parser for eRegulations',
    long_description=open('README.md').read()
            if os.path.exists('README.md') else '',

    packages=['regparser', ],
    include_package_data=True,
    install_requires=[
        'lxml',
        'pyparsing',
        'inflection',
        'requests',
        'GitPython',
        'python-constraint',
    ],
    setup_requires=[
        'nose>=1.0'
    ],

    test_suite='xtdiff.tests',
)

Prompt: Make the parser an installable Python package


import enum

from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum

from virtool.postgres import Base

class UploadType(str, enum.Enum):
    hmm = "hmm"
    reference = "reference"
    reads = "reads"
    subtraction = "subtraction"

class Upload(Base):
    __tablename__ = "uploads"

    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    name = Column(String)
    name_on_disk = Column(String, unique=True)
    ready = Column(Boolean)
    removed = Column(Boolean)
    removed_at = Column(DateTime)
    reserved = Column(Boolean)
    size = Column(Integer)
    type = Column(Enum(UploadType))
    user = Column(String)
    uploaded_at = Column(DateTime)

    def __repr__(self):
        return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \
               f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \
               f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \
               f"uploaded_at={self.uploaded_at})>"

Fix format issue with `__repr__`

Fix format issue with `__repr__`

Response:
<REPLACE_OLD> f"uploaded_at={self.uploaded_at}>"
 <REPLACE_NEW> f"uploaded_at={self.uploaded_at})>"
 <REPLACE_END> <|endoftext|> import enum

from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum

from virtool.postgres import Base

class UploadType(str, enum.Enum):
    hmm = "hmm"
    reference = "reference"
    reads = "reads"
    subtraction = "subtraction"

class Upload(Base):
    __tablename__ = "uploads"

    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    name = Column(String)
    name_on_disk = Column(String, unique=True)
    ready = Column(Boolean)
    removed = Column(Boolean)
    removed_at = Column(DateTime)
    reserved = Column(Boolean)
    size = Column(Integer)
    type = Column(Enum(UploadType))
    user = Column(String)
    uploaded_at = Column(DateTime)

    def __repr__(self):
        return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \
               f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \
               f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \
               f"uploaded_at={self.uploaded_at})>"

Prompt:
Fix format issue with `__repr__`

import enum

from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum

from virtool.postgres import Base

class UploadType(str, enum.Enum):
    hmm = "hmm"
    reference = "reference"
    reads = "reads"
    subtraction = "subtraction"

class Upload(Base):
    __tablename__ = "uploads"

    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    name = Column(String)
    name_on_disk = Column(String, unique=True)
    ready = Column(Boolean)
    removed = Column(Boolean)
    removed_at = Column(DateTime)
    reserved = Column(Boolean)
    size = Column(Integer)
    type = Column(Enum(UploadType))
    user = Column(String)
    uploaded_at = Column(DateTime)

    def __repr__(self):
        return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \
               f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \
               f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \
               f"uploaded_at={self.uploaded_at}>"


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

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

import contractions.views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'pregnancy.views.home', name='home'),
    # url(r'^pregnancy/', include('pregnancy.foo.urls')),
    url(r'^$', contractions.views.ContractionList.as_view(), name='ContractionList'),
    url(r'^contractions/$', contractions.views.ContractionList.as_view(), name='ContractionList'),
    url(r'^update_intensity/(?P<pk>\d+)/$', contractions.views.UpdateIntensity.as_view(), name='UpdateIntensity'),
    url(r'^update_intensity2/(?P<pk>\d+)/$', contractions.views.UpdateIntensity2.as_view(), name='UpdateIntensity2'),
    url(r'^ContractionListTable/$', contractions.views.ContractionListTable.as_view(), name='ContractionListTable'),
    url(r'^StartContraction/$', contractions.views.StartContraction.as_view(), name='StartContraction'),
    url(r'^StopContraction/(?P<pk>\d+)/$', contractions.views.StopContraction.as_view(), name='StopContraction'),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

Response:
<INSERT>    url(r'^$', contractions.views.ContractionList.as_view(), name='ContractionList'),
 <INSERT_END> <|endoftext|> from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

import contractions.views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'pregnancy.views.home', name='home'),
    # url(r'^pregnancy/', include('pregnancy.foo.urls')),
    url(r'^$', contractions.views.ContractionList.as_view(), name='ContractionList'),
    url(r'^contractions/$', contractions.views.ContractionList.as_view(), name='ContractionList'),
    url(r'^update_intensity/(?P<pk>\d+)/$', contractions.views.UpdateIntensity.as_view(), name='UpdateIntensity'),
    url(r'^update_intensity2/(?P<pk>\d+)/$', contractions.views.UpdateIntensity2.as_view(), name='UpdateIntensity2'),
    url(r'^ContractionListTable/$', contractions.views.ContractionListTable.as_view(), name='ContractionListTable'),
    url(r'^StartContraction/$', contractions.views.StartContraction.as_view(), name='StartContraction'),
    url(r'^StopContraction/(?P<pk>\d+)/$', contractions.views.StopContraction.as_view(), name='StopContraction'),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

Prompt:
Update url to point / to the contractions app

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

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

import contractions.views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'pregnancy.views.home', name='home'),
    # url(r'^pregnancy/', include('pregnancy.foo.urls')),
    url(r'^contractions/$', contractions.views.ContractionList.as_view(), name='ContractionList'),
    url(r'^update_intensity/(?P<pk>\d+)/$', contractions.views.UpdateIntensity.as_view(), name='UpdateIntensity'),
    url(r'^update_intensity2/(?P<pk>\d+)/$', contractions.views.UpdateIntensity2.as_view(), name='UpdateIntensity2'),
    url(r'^ContractionListTable/$', contractions.views.ContractionListTable.as_view(), name='ContractionListTable'),
    url(r'^StartContraction/$', contractions.views.StartContraction.as_view(), name='StartContraction'),
    url(r'^StopContraction/(?P<pk>\d+)/$', contractions.views.StopContraction.as_view(), name='StopContraction'),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)


import pytest

from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession

from virtool.postgres import Base

@pytest.fixture
def test_pg_connection_string(request):
    return request.config.getoption("postgres_connection_string")

@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
    pg_connection_string = test_pg_connection_string.split('/')
    pg_connection_string[-1] = 'virtool'
    engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
    async with engine.connect() as conn:
        try:
            await conn.execute(text("CREATE DATABASE test"))
        except ProgrammingError:
            pass
    return create_async_engine(test_pg_connection_string)

@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
    async with pg_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    session = AsyncSession(bind=pg_engine)
    yield session
    async with pg_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await session.close()

Response:
<INSERT> pg_connection_string = test_pg_connection_string.split('/')
    pg_connection_string[-1] = 'virtool'
    <INSERT_END> <REPLACE_OLD> create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", <REPLACE_NEW> create_async_engine('/'.join(pg_connection_string), <REPLACE_END> <|endoftext|> import pytest

from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession

from virtool.postgres import Base

@pytest.fixture
def test_pg_connection_string(request):
    return request.config.getoption("postgres_connection_string")

@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
    pg_connection_string = test_pg_connection_string.split('/')
    pg_connection_string[-1] = 'virtool'
    engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
    async with engine.connect() as conn:
        try:
            await conn.execute(text("CREATE DATABASE test"))
        except ProgrammingError:
            pass
    return create_async_engine(test_pg_connection_string)

@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
    async with pg_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    session = AsyncSession(bind=pg_engine)
    yield session
    async with pg_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await session.close()

Prompt:
Add connection string for connecting to virtool database in order to create a test database

import pytest

from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession

from virtool.postgres import Base

@pytest.fixture
def test_pg_connection_string(request):
    return request.config.getoption("postgres_connection_string")

@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
    engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
    async with engine.connect() as conn:
        try:
            await conn.execute(text("CREATE DATABASE test"))
        except ProgrammingError:
            pass
    return create_async_engine(test_pg_connection_string)

@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
    async with pg_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    session = AsyncSession(bind=pg_engine)
    yield session
    async with pg_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await session.close()


""" Test ``yatsm line``
"""
import os

from click.testing import CliRunner
import pytest

from yatsm.cli.main import cli

@pytest.mark.skipif("DISPLAY" not in os.environ, reason="requires display")
def test_cli_pixel_pass_1(example_timeseries):
    """ Correctly run for one pixel
    """
    runner = CliRunner()
    result = runner.invoke(
        cli,
        ['-v', 'pixel',
         '--band', '5',
         '--plot', 'TS',
         '--style', 'ggplot',
         example_timeseries['config'], '1', '1'
         ])
    assert result.exit_code == 0

Add test for pixel CLI

Add test for pixel CLI

Response:
<INSERT> """ Test ``yatsm line``
"""
import os

from click.testing import CliRunner
import pytest

from yatsm.cli.main import cli

@pytest.mark.skipif("DISPLAY" not in os.environ, reason="requires display")
def test_cli_pixel_pass_1(example_timeseries):
 <INSERT_END> <INSERT>   """ Correctly run for one pixel
    """
    runner = CliRunner()
    result = runner.invoke(
        cli,
        ['-v', 'pixel',
         '--band', '5',
         '--plot', 'TS',
         '--style', 'ggplot',
         example_timeseries['config'], '1', '1'
         ])
    assert result.exit_code == 0
 <INSERT_END> <|endoftext|> """ Test ``yatsm line``
"""
import os

from click.testing import CliRunner
import pytest

from yatsm.cli.main import cli

@pytest.mark.skipif("DISPLAY" not in os.environ, reason="requires display")
def test_cli_pixel_pass_1(example_timeseries):
    """ Correctly run for one pixel
    """
    runner = CliRunner()
    result = runner.invoke(
        cli,
        ['-v', 'pixel',
         '--band', '5',
         '--plot', 'TS',
         '--style', 'ggplot',
         example_timeseries['config'], '1', '1'
         ])
    assert result.exit_code == 0

Prompt: Add test for pixel CLI


"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt

def show(image, blocking=False, **kwargs):
    """Show *image*. If *blocking* is False the call is nonblocking.
    *kwargs* are passed to matplotlib's ``imshow`` function. This command
    always creates a new figure. Returns matplotlib's ``AxesImage``.
    """
    plt.figure()
    mpl_image = plt.imshow(image, **kwargs)
    plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
    plt.show(blocking)

    return mpl_image

def plot(*args, **kwargs):
    """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
    *kwargs* are infected with *blocking* and if False or not specified,
    the call is nonblocking. This command always creates a new figure.
    """
    blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
    plt.figure()
    plt.plot(*args, **kwargs)
    plt.show(blocking)

Create new figure in plot command

Create new figure in plot command

Response:
<REPLACE_OLD> nonblocking.
 <REPLACE_NEW> nonblocking. This command always creates a new figure.
 <REPLACE_END> <INSERT> plt.figure()
    <INSERT_END> <|endoftext|> """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt

def show(image, blocking=False, **kwargs):
    """Show *image*. If *blocking* is False the call is nonblocking.
    *kwargs* are passed to matplotlib's ``imshow`` function. This command
    always creates a new figure. Returns matplotlib's ``AxesImage``.
    """
    plt.figure()
    mpl_image = plt.imshow(image, **kwargs)
    plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
    plt.show(blocking)

    return mpl_image

def plot(*args, **kwargs):
    """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
    *kwargs* are infected with *blocking* and if False or not specified,
    the call is nonblocking. This command always creates a new figure.
    """
    blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
    plt.figure()
    plt.plot(*args, **kwargs)
    plt.show(blocking)

Prompt:
Create new figure in plot command

"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt

def show(image, blocking=False, **kwargs):
    """Show *image*. If *blocking* is False the call is nonblocking.
    *kwargs* are passed to matplotlib's ``imshow`` function. This command
    always creates a new figure. Returns matplotlib's ``AxesImage``.
    """
    plt.figure()
    mpl_image = plt.imshow(image, **kwargs)
    plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
    plt.show(blocking)

    return mpl_image

def plot(*args, **kwargs):
    """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
    *kwargs* are infected with *blocking* and if False or not specified,
    the call is nonblocking.
    """
    blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
    plt.plot(*args, **kwargs)
    plt.show(blocking)


# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import os
import unittest
from openquake.commonlib import nrml

def number_of(elem_name, tree):
    """
    Given an element name (including the namespaces prefix, if applicable),
    return the number of occurrences of the element in a given XML document.
    """
    expr = '//%s' % elem_name
    return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))

class BaseExportTestCase(unittest.TestCase):
    def _test_exported_file(self, filename):
        self.assertTrue(os.path.exists(filename))
        self.assertTrue(os.path.isabs(filename))
        self.assertTrue(os.path.getsize(filename) > 0)

Fix a broken export test

Fix a broken export test

Response:
<REPLACE_OLD> namespaces=nrml.PARSE_NS_MAP))

class <REPLACE_NEW> namespaces={'nrml': nrml.NRML05}))

class <REPLACE_END> <|endoftext|>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import os
import unittest
from openquake.commonlib import nrml

def number_of(elem_name, tree):
    """
    Given an element name (including the namespaces prefix, if applicable),
    return the number of occurrences of the element in a given XML document.
    """
    expr = '//%s' % elem_name
    return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))

class BaseExportTestCase(unittest.TestCase):
    def _test_exported_file(self, filename):
        self.assertTrue(os.path.exists(filename))
        self.assertTrue(os.path.isabs(filename))
        self.assertTrue(os.path.getsize(filename) > 0)

Prompt:
Fix a broken export test

# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import os
import unittest
from openquake.commonlib import nrml

def number_of(elem_name, tree):
    """
    Given an element name (including the namespaces prefix, if applicable),
    return the number of occurrences of the element in a given XML document.
    """
    expr = '//%s' % elem_name
    return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))

class BaseExportTestCase(unittest.TestCase):
    def _test_exported_file(self, filename):
        self.assertTrue(os.path.exists(filename))
        self.assertTrue(os.path.isabs(filename))
        self.assertTrue(os.path.getsize(filename) > 0)


from celery.task import task
from corehq.apps.users.models import CommCareUser

@task(queue='background_queue')
def create_user_cases(domain_name):
    from corehq.apps.callcenter.utils import sync_usercase
    for user in CommCareUser.by_domain(domain_name):
        sync_usercase(user)

Response:
<REPLACE_OLD> CommCareUser

@task
def <REPLACE_NEW> CommCareUser

@task(queue='background_queue')
def <REPLACE_END> <|endoftext|> from celery.task import task
from corehq.apps.users.models import CommCareUser

@task(queue='background_queue')
def create_user_cases(domain_name):
    from corehq.apps.callcenter.utils import sync_usercase
    for user in CommCareUser.by_domain(domain_name):
        sync_usercase(user)

Prompt:
Use background queue for creating user cases

from celery.task import task
from corehq.apps.users.models import CommCareUser

@task
def create_user_cases(domain_name):
    from corehq.apps.callcenter.utils import sync_usercase
    for user in CommCareUser.by_domain(domain_name):
        sync_usercase(user)


# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-11 16:37
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0002_auto_20170311_0811'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='session',
            unique_together=set([]),
        ),
    ]

Remove constraint on Session model

Remove constraint on Session model

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-11 16:37
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('app', '0002_auto_20170311_0811'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='session',
            unique_together=set([]),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-11 16:37
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0002_auto_20170311_0811'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='session',
            unique_together=set([]),
        ),
    ]

Prompt: Remove constraint on Session model


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

import mock

import ironicclient
import shade
from shade.tests import base

class TestShadeOperatorNoAuth(base.TestCase):
    def setUp(self):
        """Setup Noauth OperatorCloud tests

        Setup the test to utilize no authentication and an endpoint
        URL in the auth data.  This is permits testing of the basic
        mechanism that enables Ironic noauth mode to be utilized with
        Shade.
        """
        super(TestShadeOperatorNoAuth, self).setUp()
        self.cloud_noauth = shade.operator_cloud(
            auth_type='None',
            auth=dict(endpoint="http://localhost:6385")
        )

    @mock.patch.object(shade.OperatorCloud, 'get_endpoint')
    @mock.patch.object(ironicclient.client, 'Client')
    def test_ironic_noauth_selection_using_a_task(
            self, mock_client, mock_endpoint):
        """Test noauth selection for Ironic in OperatorCloud

        Utilize a task to trigger the client connection attempt
        and evaluate if get_endpoint was called while the client
        was still called.
        """
        self.cloud_noauth.patch_machine('name', {})
        self.assertFalse(mock_endpoint.called)
        self.assertTrue(mock_client.called)

Add test of OperatorCloud auth_type=None

Ironic features a noauth mode which is intended for use in isolated
trusted environments.  As this is not a normal use case for shade,
it is an increadibly important item to have a test for.

Change-Id: If86b9df238982d912105fb08dcd59c9c85b7de4a

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

import mock

import ironicclient
import shade
from shade.tests import base

class TestShadeOperatorNoAuth(base.TestCase):
    def setUp(self):
        """Setup Noauth OperatorCloud tests

        Setup the test to utilize no authentication and an endpoint
        URL in the auth data.  This is permits testing of the basic
        mechanism that enables Ironic noauth mode to be utilized with
        Shade.
        """
        super(TestShadeOperatorNoAuth, self).setUp()
        self.cloud_noauth = shade.operator_cloud(
            auth_type='None',
            auth=dict(endpoint="http://localhost:6385")
        )

    @mock.patch.object(shade.OperatorCloud, 'get_endpoint')
    @mock.patch.object(ironicclient.client, 'Client')
    def test_ironic_noauth_selection_using_a_task(
            self, mock_client, mock_endpoint):
        """Test noauth selection for Ironic in OperatorCloud

        Utilize a task to trigger the client connection attempt
        and evaluate if get_endpoint was called while the client
        was still called.
        """
        self.cloud_noauth.patch_machine('name', {})
        self.assertFalse(mock_endpoint.called)
        self.assertTrue(mock_client.called)
 <REPLACE_END> <|endoftext|> # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import mock

import ironicclient
import shade
from shade.tests import base

class TestShadeOperatorNoAuth(base.TestCase):
    def setUp(self):
        """Setup Noauth OperatorCloud tests

        Setup the test to utilize no authentication and an endpoint
        URL in the auth data.  This is permits testing of the basic
        mechanism that enables Ironic noauth mode to be utilized with
        Shade.
        """
        super(TestShadeOperatorNoAuth, self).setUp()
        self.cloud_noauth = shade.operator_cloud(
            auth_type='None',
            auth=dict(endpoint="http://localhost:6385")
        )

    @mock.patch.object(shade.OperatorCloud, 'get_endpoint')
    @mock.patch.object(ironicclient.client, 'Client')
    def test_ironic_noauth_selection_using_a_task(
            self, mock_client, mock_endpoint):
        """Test noauth selection for Ironic in OperatorCloud

        Utilize a task to trigger the client connection attempt
        and evaluate if get_endpoint was called while the client
        was still called.
        """
        self.cloud_noauth.patch_machine('name', {})
        self.assertFalse(mock_endpoint.called)
        self.assertTrue(mock_client.called)

Prompt:
Add test of OperatorCloud auth_type=None

Ironic features a noauth mode which is intended for use in isolated
trusted environments.  As this is not a normal use case for shade,
it is an increadibly important item to have a test for.

Change-Id: If86b9df238982d912105fb08dcd59c9c85b7de4a


from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField

from keybar.utils.crypto import encrypt, decrypt, get_salt

class Entry(models.Model):
    id = UUIDField(auto=True, primary_key=True)

    created_by = models.ForeignKey('keybar.User')
    title = models.TextField(_('Title'), blank=True, default='')
    url = models.URLField(blank=True, default='')

    identifier = models.TextField(_('Identifier for login'),
        help_text=_('Usually a username or email address'))
    value = models.TextField(_('The encrypted value for the entry.'),
        help_text=_('Usually a password.'))

    description = models.TextField(_('Description'), blank=True, default='')

    salt = models.BinaryField(null=True, blank=True)

    def set_value(self, password, value, salt=None):
        if salt is None:
            salt = get_salt()

        self.value = encrypt(value, password, salt)
        self.salt = salt

    def decrypt(self, password):
        return decrypt(self.value, password, bytes(self.salt))

Add decrypt helper to Entry

Add decrypt helper to Entry

Response:
<INSERT> decrypt, <INSERT_END> <REPLACE_OLD> salt
 <REPLACE_NEW> salt

    def decrypt(self, password):
        return decrypt(self.value, password, bytes(self.salt))
 <REPLACE_END> <|endoftext|> from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField

from keybar.utils.crypto import encrypt, decrypt, get_salt

class Entry(models.Model):
    id = UUIDField(auto=True, primary_key=True)

    created_by = models.ForeignKey('keybar.User')
    title = models.TextField(_('Title'), blank=True, default='')
    url = models.URLField(blank=True, default='')

    identifier = models.TextField(_('Identifier for login'),
        help_text=_('Usually a username or email address'))
    value = models.TextField(_('The encrypted value for the entry.'),
        help_text=_('Usually a password.'))

    description = models.TextField(_('Description'), blank=True, default='')

    salt = models.BinaryField(null=True, blank=True)

    def set_value(self, password, value, salt=None):
        if salt is None:
            salt = get_salt()

        self.value = encrypt(value, password, salt)
        self.salt = salt

    def decrypt(self, password):
        return decrypt(self.value, password, bytes(self.salt))

Prompt:
Add decrypt helper to Entry

from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField

from keybar.utils.crypto import encrypt, get_salt

class Entry(models.Model):
    id = UUIDField(auto=True, primary_key=True)

    created_by = models.ForeignKey('keybar.User')
    title = models.TextField(_('Title'), blank=True, default='')
    url = models.URLField(blank=True, default='')

    identifier = models.TextField(_('Identifier for login'),
        help_text=_('Usually a username or email address'))
    value = models.TextField(_('The encrypted value for the entry.'),
        help_text=_('Usually a password.'))

    description = models.TextField(_('Description'), blank=True, default='')

    salt = models.BinaryField(null=True, blank=True)

    def set_value(self, password, value, salt=None):
        if salt is None:
            salt = get_salt()

        self.value = encrypt(value, password, salt)
        self.salt = salt


Remove Request and Response classes

Remove Request and Response classes

Response:
<REPLACE_OLD> handler_options)

class Request(object):
    """Request class."""

    def __init__(self, url, action, request, **params):
        self.action = action
        self.request = request
        self.params = params
        self.params['url'] = url

class Response(object):
    """Response class."""

    def __init__(self, response):
        self.id = response.pop('requestId')
        self.action = response.pop('action')
        self.is_success = response.pop('status') == 'success'
        self.code = response.pop('code', None)
        self.error = response.pop('error', None)
        self.data = response
 <REPLACE_NEW> handler_options)
 <REPLACE_END> <|endoftext|> def init(name, data_format_class, data_format_options, handler_class,
         handler_options):
    transport_class_name = '%sTransport' % name.title()
    transport_module = __import__('devicehive.transports.%s_transport' % name,
                                  fromlist=[transport_class_name])
    return getattr(transport_module, transport_class_name)(data_format_class,
                                                           data_format_options,
                                                           handler_class,
                                                           handler_options)

Prompt:
Remove Request and Response classes

def init(name, data_format_class, data_format_options, handler_class,
         handler_options):
    transport_class_name = '%sTransport' % name.title()
    transport_module = __import__('devicehive.transports.%s_transport' % name,
                                  fromlist=[transport_class_name])
    return getattr(transport_module, transport_class_name)(data_format_class,
                                                           data_format_options,
                                                           handler_class,
                                                           handler_options)

class Request(object):
    """Request class."""

    def __init__(self, url, action, request, **params):
        self.action = action
        self.request = request
        self.params = params
        self.params['url'] = url

class Response(object):
    """Response class."""

    def __init__(self, response):
        self.id = response.pop('requestId')
        self.action = response.pop('action')
        self.is_success = response.pop('status') == 'success'
        self.code = response.pop('code', None)
        self.error = response.pop('error', None)
        self.data = response