"""
==============
Edge operators
==============

Edge operators are used in image processing within edge detection algorithms.
They are discrete differentiation operators, computing an approximation of the
gradient of the image intensity function.

"""
import matplotlib.pyplot as plt

from skimage.data import camera
from skimage.filter import roberts, sobel

image = camera()
edge_roberts = roberts(image)
edge_sobel = sobel(image)

fig, (ax0, ax1) = plt.subplots(ncols=2)

ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off')

ax1.imshow(edge_sobel, cmap=plt.cm.gray)
ax1.set_title('Sobel Edge Detection')
ax1.axis('off')

plt.show()

Response:
<REPLACE_OLD> import <REPLACE_NEW> """
==============
Edge operators
==============

Edge operators are used in image processing within edge detection algorithms.
They are discrete differentiation operators, computing an approximation of the
gradient of the image intensity function.

"""
import <REPLACE_END> <|endoftext|> """
==============
Edge operators
==============

Edge operators are used in image processing within edge detection algorithms.
They are discrete differentiation operators, computing an approximation of the
gradient of the image intensity function.

"""
import matplotlib.pyplot as plt

from skimage.data import camera
from skimage.filter import roberts, sobel

image = camera()
edge_roberts = roberts(image)
edge_sobel = sobel(image)

fig, (ax0, ax1) = plt.subplots(ncols=2)

ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off')

ax1.imshow(edge_sobel, cmap=plt.cm.gray)
ax1.set_title('Sobel Edge Detection')
ax1.axis('off')

plt.show()

Prompt:
Add short description to edge filter example

import matplotlib.pyplot as plt

from skimage.data import camera
from skimage.filter import roberts, sobel

image = camera()
edge_roberts = roberts(image)
edge_sobel = sobel(image)

fig, (ax0, ax1) = plt.subplots(ncols=2)

ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off')

ax1.imshow(edge_sobel, cmap=plt.cm.gray)
ax1.set_title('Sobel Edge Detection')
ax1.axis('off')

plt.show()


import logging

from flask import (
	Flask,
	render_template,
	abort
)

from glanerbeard.server import Server

app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')

numeric_level = getattr(logging, app.config['LOGLEVEL'].upper(), None)
if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level)
log = logging.getLogger(__name__)

servers = Server.createFromConfig(app.config['SERVERS'], app.config['API_KEYS'])

@app.route('/')
def index():
	shows = [server.getShows() for server in servers]
	return render_template('json.html', json=shows)

Use a template to render json.

Use a template to render json.

Response:
<REPLACE_OLD> str(shows)

if __name__ == '__main__':
	app.debug = True
	app.run()
 <REPLACE_NEW> render_template('json.html', json=shows)
 <REPLACE_END> <|endoftext|> import logging

from flask import (
	Flask,
	render_template,
	abort
)

from glanerbeard.server import Server

app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')

numeric_level = getattr(logging, app.config['LOGLEVEL'].upper(), None)
if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level)
log = logging.getLogger(__name__)

servers = Server.createFromConfig(app.config['SERVERS'], app.config['API_KEYS'])

@app.route('/')
def index():
	shows = [server.getShows() for server in servers]
	return render_template('json.html', json=shows)

Prompt:
Use a template to render json.

import logging

from flask import (
	Flask,
	render_template,
	abort
)

from glanerbeard.server import Server

app = Flask(__name__)
app.config.from_object('glanerbeard.default_settings')
app.config.from_envvar('GLANERBEARD_SETTINGS')

numeric_level = getattr(logging, app.config['LOGLEVEL'].upper(), None)
if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level)
log = logging.getLogger(__name__)

servers = Server.createFromConfig(app.config['SERVERS'], app.config['API_KEYS'])

@app.route('/')
def index():
	shows = [server.getShows() for server in servers]
	return str(shows)

if __name__ == '__main__':
	app.debug = True
	app.run()


import re

class InvalidBoard(ValueError):
    pass

def board(b):
    if not is_valid_board(b):
        raise InvalidBoard("Board is malformed and thus invalid")
    b = [[ch for ch in row] for row in b]
    for i in range(1, len(b)-1):
        for j in range(1, len(b[0])-1):
            if b[i][j] == " ":
                m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2])
                count = m.count("*")
                if count:
                     b[i][j] = str(count)
    return list(map("".join, b))

def is_valid_board(b):
    width = "{" + str(len(b[0]) - 2) + "}"
    height = "{" + str(len(b) - 2) + "}"
    r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width,
                                                                   h=height))
    # bool is technically redundant here, but I'd rather that this function
    # return an explicit True/False
    return bool(r.match("".join(b)))

Response:
<INSERT> # bool is technically redundant here, but I'd rather that this function
    # return an explicit True/False
    <INSERT_END> <|endoftext|> import re

class InvalidBoard(ValueError):
    pass

def board(b):
    if not is_valid_board(b):
        raise InvalidBoard("Board is malformed and thus invalid")
    b = [[ch for ch in row] for row in b]
    for i in range(1, len(b)-1):
        for j in range(1, len(b[0])-1):
            if b[i][j] == " ":
                m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2])
                count = m.count("*")
                if count:
                     b[i][j] = str(count)
    return list(map("".join, b))

def is_valid_board(b):
    width = "{" + str(len(b[0]) - 2) + "}"
    height = "{" + str(len(b) - 2) + "}"
    r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width,
                                                                   h=height))
    # bool is technically redundant here, but I'd rather that this function
    # return an explicit True/False
    return bool(r.match("".join(b)))

Prompt:
Add note regarding use of bool in validation

import re

class InvalidBoard(ValueError):
    pass

def board(b):
    if not is_valid_board(b):
        raise InvalidBoard("Board is malformed and thus invalid")
    b = [[ch for ch in row] for row in b]
    for i in range(1, len(b)-1):
        for j in range(1, len(b[0])-1):
            if b[i][j] == " ":
                m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2])
                count = m.count("*")
                if count:
                     b[i][j] = str(count)
    return list(map("".join, b))

def is_valid_board(b):
    width = "{" + str(len(b[0]) - 2) + "}"
    height = "{" + str(len(b) - 2) + "}"
    r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width,
                                                                   h=height))
    return bool(r.match("".join(b)))


import numpy as np
import km3pipe as kp

class APump(kp.Pump):
    def configure(self):
        self.index = 0

    def process(self, blob):
        data = {'a': self.index * np.arange(5),
                'b': np.arange(5) ** self.index}
        data2 = {'c': self.index * np.arange(10, dtype='f4') + 0.1,
                 'd': np.arange(10, dtype='f4') ** self.index + 0.2}
        print(data2)
        blob['Tablelike'] = kp.Table(data,
                                     h5loc='/tablelike',
                                     name='2D Table')
        print(blob['Tablelike'])
        blob['Columnwise'] = kp.Table(data2,
                                      h5loc='/columnwise',
                                      split_h5=True,
                                      name='Column-wise Split')
        self.index += 1
        return blob

pipe = kp.Pipeline()
pipe.attach(APump)
pipe.attach(kp.io.HDF5Sink, filename='km3hdf5_example.h5')
pipe.drain(13)

Add a dummy script which creates an hdf5 file

Response:
<REPLACE_OLD>  <REPLACE_NEW> import numpy as np
import km3pipe as kp

class APump(kp.Pump):
    def configure(self):
        self.index = 0

    def process(self, blob):
        data = {'a': self.index * np.arange(5),
                'b': np.arange(5) ** self.index}
        data2 = {'c': self.index * np.arange(10, dtype='f4') + 0.1,
                 'd': np.arange(10, dtype='f4') ** self.index + 0.2}
        print(data2)
        blob['Tablelike'] = kp.Table(data,
                                     h5loc='/tablelike',
                                     name='2D Table')
        print(blob['Tablelike'])
        blob['Columnwise'] = kp.Table(data2,
                                      h5loc='/columnwise',
                                      split_h5=True,
                                      name='Column-wise Split')
        self.index += 1
        return blob

pipe = kp.Pipeline()
pipe.attach(APump)
pipe.attach(kp.io.HDF5Sink, filename='km3hdf5_example.h5')
pipe.drain(13)
 <REPLACE_END> <|endoftext|> import numpy as np
import km3pipe as kp

class APump(kp.Pump):
    def configure(self):
        self.index = 0

    def process(self, blob):
        data = {'a': self.index * np.arange(5),
                'b': np.arange(5) ** self.index}
        data2 = {'c': self.index * np.arange(10, dtype='f4') + 0.1,
                 'd': np.arange(10, dtype='f4') ** self.index + 0.2}
        print(data2)
        blob['Tablelike'] = kp.Table(data,
                                     h5loc='/tablelike',
                                     name='2D Table')
        print(blob['Tablelike'])
        blob['Columnwise'] = kp.Table(data2,
                                      h5loc='/columnwise',
                                      split_h5=True,
                                      name='Column-wise Split')
        self.index += 1
        return blob

pipe = kp.Pipeline()
pipe.attach(APump)
pipe.attach(kp.io.HDF5Sink, filename='km3hdf5_example.h5')
pipe.drain(13)

Prompt: Add a dummy script which creates an hdf5 file


class Observable(object):
    def __init__(self):
        self.observers = {}

    def notify_observers(self, action, *args, **kwargs):
        kwargs.setdefault('action', action)
        for callback in self.observers.get(action, ()):
            callback(*args, **kwargs)

    def observe(self, actions, callback):
        if not isinstance(actions, (tuple, list)):
            actions = (actions,)
        for action in actions:
            self.observers.setdefault(action, []).append(callback)

Response:
<REPLACE_OLD> # Taken from https://github.com/delivero/lymph-storage/blob/master/lymph/storage/observables.py
class <REPLACE_NEW>
class <REPLACE_END> <INSERT> kwargs.setdefault('action', action)
        <INSERT_END> <REPLACE_OLD> action, <REPLACE_NEW> actions, <REPLACE_END> <INSERT>        if not isinstance(actions, (tuple, list)):
            actions = (actions,)
        for action in actions:
     <INSERT_END> <|endoftext|>
class Observable(object):
    def __init__(self):
        self.observers = {}

    def notify_observers(self, action, *args, **kwargs):
        kwargs.setdefault('action', action)
        for callback in self.observers.get(action, ()):
            callback(*args, **kwargs)

    def observe(self, actions, callback):
        if not isinstance(actions, (tuple, list)):
            actions = (actions,)
        for action in actions:
            self.observers.setdefault(action, []).append(callback)

Prompt:
Allow observing more than one action at once

# Taken from https://github.com/delivero/lymph-storage/blob/master/lymph/storage/observables.py
class Observable(object):
    def __init__(self):
        self.observers = {}

    def notify_observers(self, action, *args, **kwargs):
        for callback in self.observers.get(action, ()):
            callback(*args, **kwargs)

    def observe(self, action, callback):
        self.observers.setdefault(action, []).append(callback)


import os
import sys

from setuptools import setup, find_packages

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

sys.path.insert(0, here)

from titlecase import __version__

setup(name='titlecase',
    version=__version__,
    description="Python Port of John Gruber's titlecase.pl",
    long_description=README,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Topic :: Text Processing :: Filters",
    ],
    keywords='string formatting',
    author="Stuart Colville",
    author_email="pypi@muffinresearch.co.uk",
    url="http://muffinresearch.co.uk/",
    license="MIT",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    tests_require=['nose'],
    setup_requires=['nose>=1.0'],
    test_suite="titlecase.tests",
    entry_points = """\
    """
)

Add python3 support for nosetests

Add python3 support for nosetests

Response:
<INSERT> setup_requires=['nose>=1.0'],
    <INSERT_END> <|endoftext|> import os
import sys

from setuptools import setup, find_packages

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

sys.path.insert(0, here)

from titlecase import __version__

setup(name='titlecase',
    version=__version__,
    description="Python Port of John Gruber's titlecase.pl",
    long_description=README,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Topic :: Text Processing :: Filters",
    ],
    keywords='string formatting',
    author="Stuart Colville",
    author_email="pypi@muffinresearch.co.uk",
    url="http://muffinresearch.co.uk/",
    license="MIT",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    tests_require=['nose'],
    setup_requires=['nose>=1.0'],
    test_suite="titlecase.tests",
    entry_points = """\
    """
)

Prompt:
Add python3 support for nosetests

import os
import sys

from setuptools import setup, find_packages

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

sys.path.insert(0, here)

from titlecase import __version__

setup(name='titlecase',
    version=__version__,
    description="Python Port of John Gruber's titlecase.pl",
    long_description=README,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Topic :: Text Processing :: Filters",
    ],
    keywords='string formatting',
    author="Stuart Colville",
    author_email="pypi@muffinresearch.co.uk",
    url="http://muffinresearch.co.uk/",
    license="MIT",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    tests_require=['nose'],
    test_suite="titlecase.tests",
    entry_points = """\
    """
)


import sys

from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer

def main(argv=None):
    debug = None
    try:
        all_argv, run_argv, command_argv = partition_argv(argv)
        cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
        run_args = read_run_args(run)
        run_args.update(cli_args)
        debug = run_args.get('debug', run.parameters['debug'].default)
        run.implementation(
            None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
            cli_args=cli_args, **run_args)
    except RunCommandsError as exc:
        if debug or debug is None:
            # User specified --debug OR processing didn't get far enough
            # to determine whether user specified --debug.
            raise
        printer.error(exc, file=sys.stderr)
        return 1
    return 0

if __name__ == '__main__':
    sys.exit(main())

Response:
<INSERT> debug = None
    <INSERT_END> <INSERT>        debug = run_args.get('debug', run.parameters['debug'].default)
 <INSERT_END> <INSERT>        if debug or debug is None:
            # User specified --debug OR processing didn't get far enough
            # to determine whether user specified --debug.
            raise
 <INSERT_END> <|endoftext|> import sys

from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer

def main(argv=None):
    debug = None
    try:
        all_argv, run_argv, command_argv = partition_argv(argv)
        cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
        run_args = read_run_args(run)
        run_args.update(cli_args)
        debug = run_args.get('debug', run.parameters['debug'].default)
        run.implementation(
            None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
            cli_args=cli_args, **run_args)
    except RunCommandsError as exc:
        if debug or debug is None:
            # User specified --debug OR processing didn't get far enough
            # to determine whether user specified --debug.
            raise
        printer.error(exc, file=sys.stderr)
        return 1
    return 0

if __name__ == '__main__':
    sys.exit(main())

Prompt:
Raise exception when --debug is specified to main script

I.e., instead of printing the exception and then exiting.

import sys

from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer

def main(argv=None):
    try:
        all_argv, run_argv, command_argv = partition_argv(argv)
        cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
        run_args = read_run_args(run)
        run_args.update(cli_args)
        run.implementation(
            None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
            cli_args=cli_args, **run_args)
    except RunCommandsError as exc:
        printer.error(exc, file=sys.stderr)
        return 1
    return 0

if __name__ == '__main__':
    sys.exit(main())


import hashlib

from digestive.io import Sink

class HashDigest(Sink):
    def __init__(self, name, digest):
        super().__init__(name)
        self._digest = digest

    def update(self, data):
        self._digest.update(data)

    def digest(self):
        return self._digest.hexdigest()

class MD5(HashDigest):
    def __init__(self):
        super().__init__('md5', hashlib.md5())

class SHA1(HashDigest):
    def __init__(self):
        super().__init__('sha1', hashlib.sha1())

class SHA256(HashDigest):
    def __init__(self):
        super().__init__('sha256', hashlib.sha256())

class SHA512(HashDigest):
    def __init__(self):
        super().__init__('sha512', hashlib.sha512())

Response:
<REPLACE_OLD> super().__init__('sha2-256', <REPLACE_NEW> super().__init__('sha256', <REPLACE_END> <REPLACE_OLD> super().__init__('sha2-512', <REPLACE_NEW> super().__init__('sha512', <REPLACE_END> <|endoftext|> import hashlib

from digestive.io import Sink

class HashDigest(Sink):
    def __init__(self, name, digest):
        super().__init__(name)
        self._digest = digest

    def update(self, data):
        self._digest.update(data)

    def digest(self):
        return self._digest.hexdigest()

class MD5(HashDigest):
    def __init__(self):
        super().__init__('md5', hashlib.md5())

class SHA1(HashDigest):
    def __init__(self):
        super().__init__('sha1', hashlib.sha1())

class SHA256(HashDigest):
    def __init__(self):
        super().__init__('sha256', hashlib.sha256())

class SHA512(HashDigest):
    def __init__(self):
        super().__init__('sha512', hashlib.sha512())

Prompt:
Make sha256 and sha512 sink names correspond to their commandline arguments

import hashlib

from digestive.io import Sink

class HashDigest(Sink):
    def __init__(self, name, digest):
        super().__init__(name)
        self._digest = digest

    def update(self, data):
        self._digest.update(data)

    def digest(self):
        return self._digest.hexdigest()

class MD5(HashDigest):
    def __init__(self):
        super().__init__('md5', hashlib.md5())

class SHA1(HashDigest):
    def __init__(self):
        super().__init__('sha1', hashlib.sha1())

class SHA256(HashDigest):
    def __init__(self):
        super().__init__('sha2-256', hashlib.sha256())

class SHA512(HashDigest):
    def __init__(self):
        super().__init__('sha2-512', hashlib.sha512())


from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep

def red(text):
    RED = '\033[91m'
    END = '\033[0m'
    return RED + text + END

def log(*args):
    print(*args, file=sys.stderr)
    sys.stderr.flush()

class HowLong(object):
    def __init__(self):
        parser = argparse.ArgumentParser(description='Time a process')
        parser.add_argument('-i', type=float, nargs='?', metavar='interval',
                            help='the timer interval, defaults to 1 second')
        parser.add_argument('command', metavar='C', type=str, nargs='+',
                            help='a valid command')
        self.parsed_args = parser.parse_args()

        self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1

        self.readable_command = " ".join(self.parsed_args.command)

    def run(self):
        log("Running", self.readable_command)

        process = Popen(self.parsed_args.command)
        start_time = time()
        while process.poll() is None:
            sleep(self.timer_interval)
            elapsed_time = (time() - start_time) * 1000
            log(red(str(timedelta(milliseconds=elapsed_time))))

        log("Finished", self.readable_command)

def howlong():
    HowLong().run()

if __name__ == "__main__": howlong()

Print debug info to stderr

MINOR: Print debug info to stderr

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

import <REPLACE_NEW> from __future__ import print_function
import sys
import <REPLACE_END> <REPLACE_OLD> END

class <REPLACE_NEW> END

def log(*args):
    print(*args, file=sys.stderr)
    sys.stderr.flush()

class <REPLACE_END> <REPLACE_OLD> print("Running", <REPLACE_NEW> log("Running", <REPLACE_END> <REPLACE_OLD> print(red(str(timedelta(milliseconds=elapsed_time))))

        print("Finished", self.readable_command)

def <REPLACE_NEW> log(red(str(timedelta(milliseconds=elapsed_time))))

        log("Finished", self.readable_command)

def <REPLACE_END> <REPLACE_OLD> HowLong().run()

if <REPLACE_NEW> HowLong().run()

if <REPLACE_END> <|endoftext|> from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep

def red(text):
    RED = '\033[91m'
    END = '\033[0m'
    return RED + text + END

def log(*args):
    print(*args, file=sys.stderr)
    sys.stderr.flush()

class HowLong(object):
    def __init__(self):
        parser = argparse.ArgumentParser(description='Time a process')
        parser.add_argument('-i', type=float, nargs='?', metavar='interval',
                            help='the timer interval, defaults to 1 second')
        parser.add_argument('command', metavar='C', type=str, nargs='+',
                            help='a valid command')
        self.parsed_args = parser.parse_args()

        self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1

        self.readable_command = " ".join(self.parsed_args.command)

    def run(self):
        log("Running", self.readable_command)

        process = Popen(self.parsed_args.command)
        start_time = time()
        while process.poll() is None:
            sleep(self.timer_interval)
            elapsed_time = (time() - start_time) * 1000
            log(red(str(timedelta(milliseconds=elapsed_time))))

        log("Finished", self.readable_command)

def howlong():
    HowLong().run()

if __name__ == "__main__": howlong()

Prompt:
MINOR: Print debug info to stderr

#!/usr/bin/env python3

import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep

def red(text):
    RED = '\033[91m'
    END = '\033[0m'
    return RED + text + END

class HowLong(object):
    def __init__(self):
        parser = argparse.ArgumentParser(description='Time a process')
        parser.add_argument('-i', type=float, nargs='?', metavar='interval',
                            help='the timer interval, defaults to 1 second')
        parser.add_argument('command', metavar='C', type=str, nargs='+',
                            help='a valid command')
        self.parsed_args = parser.parse_args()

        self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1

        self.readable_command = " ".join(self.parsed_args.command)

    def run(self):
        print("Running", self.readable_command)

        process = Popen(self.parsed_args.command)
        start_time = time()
        while process.poll() is None:
            sleep(self.timer_interval)
            elapsed_time = (time() - start_time) * 1000
            print(red(str(timedelta(milliseconds=elapsed_time))))

        print("Finished", self.readable_command)

def howlong():
    HowLong().run()

if __name__ == "__main__": howlong()


import socket
import os

try:
    from django.conf import settings
except ImportError:
    settings = None

from client import StatsClient

__all__ = ['StatsClient', 'statsd']

VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))

if settings:
    try:
        host = getattr(settings, 'STATSD_HOST', 'localhost')
        port = getattr(settings, 'STATSD_PORT', 8125)
        prefix = getattr(settings, 'STATSD_PREFIX', None)
        statsd = StatsClient(host, port, prefix)
    except (socket.error, socket.gaierror, ImportError):
        try:
            host = os.environ['STATSD_HOST']
            port = os.environ['STATSD_PORT']
            prefix = os.environ.get('STATSD_PREFIX')
            statsd = StatsClient(host, port, prefix)
        except (socket.error, socket.gaierror, KeyError):
            statsd = None

Response:
<REPLACE_OLD> socket

try:
 <REPLACE_NEW> socket
import os

try:
 <REPLACE_END> <INSERT> try:
            host = os.environ['STATSD_HOST']
            port = os.environ['STATSD_PORT']
            prefix = os.environ.get('STATSD_PREFIX')
            <INSERT_END> <REPLACE_OLD> None
 <REPLACE_NEW> StatsClient(host, port, prefix)
        except (socket.error, socket.gaierror, KeyError):
            statsd = None

 <REPLACE_END> <|endoftext|> import socket
import os

try:
    from django.conf import settings
except ImportError:
    settings = None

from client import StatsClient

__all__ = ['StatsClient', 'statsd']

VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))

if settings:
    try:
        host = getattr(settings, 'STATSD_HOST', 'localhost')
        port = getattr(settings, 'STATSD_PORT', 8125)
        prefix = getattr(settings, 'STATSD_PREFIX', None)
        statsd = StatsClient(host, port, prefix)
    except (socket.error, socket.gaierror, ImportError):
        try:
            host = os.environ['STATSD_HOST']
            port = os.environ['STATSD_PORT']
            prefix = os.environ.get('STATSD_PREFIX')
            statsd = StatsClient(host, port, prefix)
        except (socket.error, socket.gaierror, KeyError):
            statsd = None

Prompt:
Read settings from environment, if available

import socket

try:
    from django.conf import settings
except ImportError:
    settings = None

from client import StatsClient

__all__ = ['StatsClient', 'statsd']

VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))

if settings:
    try:
        host = getattr(settings, 'STATSD_HOST', 'localhost')
        port = getattr(settings, 'STATSD_PORT', 8125)
        prefix = getattr(settings, 'STATSD_PREFIX', None)
        statsd = StatsClient(host, port, prefix)
    except (socket.error, socket.gaierror, ImportError):
        statsd = None


import logbook

class LazyDatabaseMixin(object):
    """
    A mixin class that gives the subclass lazy access to the database layer

    The lazy attribute self.db is added, and the database class is gotten from
    self.config, and an instance is made and returned.

    """

    _db = None

    @property
    def db(self):
        assert self.config is not None, \
            'Database accessed before self.config was set.'

        if self._db is None:
            self._db = self.config.get_database()
            self._db.setup()

        return self._db

# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
    """
    Abstract class representing a persistance layer

    """

    def __init__(self):
        self.log = logbook.Logger(self.__class__.__name__)

    def init(self, ns, config):
        raise NotImplementedError()

class DbCLI(object):
    def __init__(self, cls):
        self.cls = cls
        self.log = logbook.Logger(self.__class__.__name__)

    def compose(self, parser):  # pragma: nocover
        db = parser.add_parser('db', help='Perform database tasks')

        sub = db.add_subparsers(help='Database commands', dest="db_command")
        sub.add_parser('init', help='Do the initial setup of the database')

        return 'db', self.run

    def run(self, ns, config):
        self.cls.init(ns, config)
        return 0

Response:
<REPLACE_OLD> logbook

# <REPLACE_NEW> logbook

class LazyDatabaseMixin(object):
    """
    A mixin class that gives the subclass lazy access to the database layer

    The lazy attribute self.db is added, and the database class is gotten from
    self.config, and an instance is made and returned.

    """

    _db = None

    @property
    def db(self):
        assert self.config is not None, \
            'Database accessed before self.config was set.'

        if self._db is None:
            self._db = self.config.get_database()
            self._db.setup()

        return self._db

# <REPLACE_END> <|endoftext|> import logbook

class LazyDatabaseMixin(object):
    """
    A mixin class that gives the subclass lazy access to the database layer

    The lazy attribute self.db is added, and the database class is gotten from
    self.config, and an instance is made and returned.

    """

    _db = None

    @property
    def db(self):
        assert self.config is not None, \
            'Database accessed before self.config was set.'

        if self._db is None:
            self._db = self.config.get_database()
            self._db.setup()

        return self._db

# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
    """
    Abstract class representing a persistance layer

    """

    def __init__(self):
        self.log = logbook.Logger(self.__class__.__name__)

    def init(self, ns, config):
        raise NotImplementedError()

class DbCLI(object):
    def __init__(self, cls):
        self.cls = cls
        self.log = logbook.Logger(self.__class__.__name__)

    def compose(self, parser):  # pragma: nocover
        db = parser.add_parser('db', help='Perform database tasks')

        sub = db.add_subparsers(help='Database commands', dest="db_command")
        sub.add_parser('init', help='Do the initial setup of the database')

        return 'db', self.run

    def run(self, ns, config):
        self.cls.init(ns, config)
        return 0

Prompt:
Add first iteration of LazyDatabaseMixin()

import logbook

# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
    """
    Abstract class representing a persistance layer

    """

    def __init__(self):
        self.log = logbook.Logger(self.__class__.__name__)

    def init(self, ns, config):
        raise NotImplementedError()

class DbCLI(object):
    def __init__(self, cls):
        self.cls = cls
        self.log = logbook.Logger(self.__class__.__name__)

    def compose(self, parser):  # pragma: nocover
        db = parser.add_parser('db', help='Perform database tasks')

        sub = db.add_subparsers(help='Database commands', dest="db_command")
        sub.add_parser('init', help='Do the initial setup of the database')

        return 'db', self.run

    def run(self, ns, config):
        self.cls.init(ns, config)
        return 0


from django import forms

class SignupForm(forms.Form):
    field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']

    first_name = forms.CharField(max_length=30,
                                 label='First name (optional)',
                                 required=False,
                                 widget=forms.TextInput(attrs={
                                     'placeholder': 'First name'
                                 }))

    last_name = forms.CharField(max_length=30,
                                label='Last name (optional)',
                                required=False,
                                widget=forms.TextInput(attrs={
                                    'placeholder': 'Last name'
                                }))

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

Response:
<REPLACE_OLD> forms.CharField(max_length=30, <REPLACE_NEW> forms.CharField(max_length=30,
                                 <REPLACE_END> <REPLACE_OLD> (optional)', required=False)
 <REPLACE_NEW> (optional)',
                                 required=False,
                                 widget=forms.TextInput(attrs={
                                     'placeholder': 'First name'
                                 }))

 <REPLACE_END> <REPLACE_OLD> forms.CharField(max_length=30, <REPLACE_NEW> forms.CharField(max_length=30,
                                <REPLACE_END> <REPLACE_OLD> (optional)', required=False)

 <REPLACE_NEW> (optional)',
                                required=False,
                                widget=forms.TextInput(attrs={
                                    'placeholder': 'Last name'
                                }))

 <REPLACE_END> <|endoftext|> from django import forms

class SignupForm(forms.Form):
    field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']

    first_name = forms.CharField(max_length=30,
                                 label='First name (optional)',
                                 required=False,
                                 widget=forms.TextInput(attrs={
                                     'placeholder': 'First name'
                                 }))

    last_name = forms.CharField(max_length=30,
                                label='Last name (optional)',
                                required=False,
                                widget=forms.TextInput(attrs={
                                    'placeholder': 'Last name'
                                }))

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

Prompt:
Add placeholder to first_name and last_name fields in signup form

from django import forms

class SignupForm(forms.Form):
    field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']

    first_name = forms.CharField(max_length=30, label='First name (optional)', required=False)
    last_name = forms.CharField(max_length=30, label='Last name (optional)', required=False)

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()


import scholarly
import requests

_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
    """Search by scholar query and return a generator of Publication objects"""
    url = _EXACT_SEARCH.format(requests.utils.quote(query))
    if start_year:
        url += _START_YEAR.format(start_year)
    if end_year:
        url += _END_YEAR.format(end_year)
    soup = scholarly._get_soup(url)
    return scholarly._search_scholar_soup(soup)

if __name__ == '__main__':
    s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
    num = 0
    for x in s:
        x.fill()
        stuff = ['title', 'author', 'journal', 'volume', 'issue']
        for thing in stuff:
            if thing in x.bib:
                print("{}: {}".format(thing, x.bib[thing]))
        num += 1

    print("Number of results:", num)

Response:
<REPLACE_OLD> requests

_SEARCH <REPLACE_NEW> requests

_EXACT_SEARCH <REPLACE_END> <REPLACE_OLD> '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def <REPLACE_NEW> '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def <REPLACE_END> <REPLACE_OLD> start_year, end_year):
 <REPLACE_NEW> exact=True, start_year=None, end_year=None):
 <REPLACE_END> <REPLACE_OLD> soup <REPLACE_NEW> url <REPLACE_END> <REPLACE_OLD> scholarly._get_soup(
 <REPLACE_NEW> _EXACT_SEARCH.format(requests.utils.quote(query))
    if start_year:
 <REPLACE_END> <REPLACE_OLD> _SEARCH.format(requests.utils.quote(query),
 <REPLACE_NEW> url += _START_YEAR.format(start_year)
    if end_year:
 <REPLACE_END> <INSERT> url += _END_YEAR.format(end_year)
 <INSERT_END> <REPLACE_OLD>             str(start_year), str(end_year)))
 <REPLACE_NEW> soup = scholarly._get_soup(url)
 <REPLACE_END> <REPLACE_OLD> 2015, 2015)
 <REPLACE_NEW> start_year=2015, end_year=2015)
 <REPLACE_END> <|endoftext|> import scholarly
import requests

_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
    """Search by scholar query and return a generator of Publication objects"""
    url = _EXACT_SEARCH.format(requests.utils.quote(query))
    if start_year:
        url += _START_YEAR.format(start_year)
    if end_year:
        url += _END_YEAR.format(end_year)
    soup = scholarly._get_soup(url)
    return scholarly._search_scholar_soup(soup)

if __name__ == '__main__':
    s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
    num = 0
    for x in s:
        x.fill()
        stuff = ['title', 'author', 'journal', 'volume', 'issue']
        for thing in stuff:
            if thing in x.bib:
                print("{}: {}".format(thing, x.bib[thing]))
        num += 1

    print("Number of results:", num)

Prompt:
Make year range arguments optional in search

import scholarly
import requests

_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def search(query, start_year, end_year):
    """Search by scholar query and return a generator of Publication objects"""
    soup = scholarly._get_soup(
        _SEARCH.format(requests.utils.quote(query),
                       str(start_year), str(end_year)))
    return scholarly._search_scholar_soup(soup)

if __name__ == '__main__':
    s = search("Cure Alzheimer's Fund", 2015, 2015)
    num = 0
    for x in s:
        x.fill()
        stuff = ['title', 'author', 'journal', 'volume', 'issue']
        for thing in stuff:
            if thing in x.bib:
                print("{}: {}".format(thing, x.bib[thing]))
        num += 1

    print("Number of results:", num)


"""Test the Reporter base class."""

import pytest

@pytest.fixture
def klass():
    """Return the CUT."""
    from agile_analytics.reporters import Reporter
    return Reporter

def test_klass(klass):
    """Ensure the CUT exists."""
    assert klass

@pytest.fixture
def instance(klass, days_ago):
    """Return a pre-init'd CUT."""
    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)
    return k

def test_init(klass, days_ago):
    """Verify we can init it correctly."""

    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert k
    assert k.start_date == a_month_ago
    assert k.end_date == now

def test_valid_start_date(klass, days_ago):
    """Verify valid_start_date returns whatever is passed."""

    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert now == k.valid_start_date(now)

def test_valid_end_date(klass, days_ago):
    """Verify valid_end_date returns whatever is passed."""
    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert a_month_ago == k.valid_end_date(a_month_ago)

def test_filter_issues(instance):
    """Verify that filter_issues raises NotImplementedError."""
    with pytest.raises(NotImplementedError):
        instance.filter_issues([])

def test_report_on(instance):
    """Verify that report_on raises NotImplementedError."""
    with pytest.raises(NotImplementedError):
        instance.report_on([])

Add tests for base class.

Add tests for base class.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Test the Reporter base class."""

import pytest

@pytest.fixture
def klass():
    """Return the CUT."""
    from agile_analytics.reporters import Reporter
    return Reporter

def test_klass(klass):
    """Ensure the CUT exists."""
    assert klass

@pytest.fixture
def instance(klass, days_ago):
    """Return a pre-init'd CUT."""
    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)
    return k

def test_init(klass, days_ago):
    """Verify we can init it correctly."""

    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert k
    assert k.start_date == a_month_ago
    assert k.end_date == now

def test_valid_start_date(klass, days_ago):
    """Verify valid_start_date returns whatever is passed."""

    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert now == k.valid_start_date(now)

def test_valid_end_date(klass, days_ago):
    """Verify valid_end_date returns whatever is passed."""
    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert a_month_ago == k.valid_end_date(a_month_ago)

def test_filter_issues(instance):
    """Verify that filter_issues raises NotImplementedError."""
    with pytest.raises(NotImplementedError):
        instance.filter_issues([])

def test_report_on(instance):
    """Verify that report_on raises NotImplementedError."""
    with pytest.raises(NotImplementedError):
        instance.report_on([])
 <REPLACE_END> <|endoftext|> """Test the Reporter base class."""

import pytest

@pytest.fixture
def klass():
    """Return the CUT."""
    from agile_analytics.reporters import Reporter
    return Reporter

def test_klass(klass):
    """Ensure the CUT exists."""
    assert klass

@pytest.fixture
def instance(klass, days_ago):
    """Return a pre-init'd CUT."""
    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)
    return k

def test_init(klass, days_ago):
    """Verify we can init it correctly."""

    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert k
    assert k.start_date == a_month_ago
    assert k.end_date == now

def test_valid_start_date(klass, days_ago):
    """Verify valid_start_date returns whatever is passed."""

    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert now == k.valid_start_date(now)

def test_valid_end_date(klass, days_ago):
    """Verify valid_end_date returns whatever is passed."""
    now = days_ago(0)
    a_month_ago = days_ago(30)

    k = klass(title="Foo", start_date=a_month_ago, end_date=now)

    assert a_month_ago == k.valid_end_date(a_month_ago)

def test_filter_issues(instance):
    """Verify that filter_issues raises NotImplementedError."""
    with pytest.raises(NotImplementedError):
        instance.filter_issues([])

def test_report_on(instance):
    """Verify that report_on raises NotImplementedError."""
    with pytest.raises(NotImplementedError):
        instance.report_on([])

Prompt: Add tests for base class.


"""empty message

Revision ID: 0028_add_default_permissions
Revises: 0027_add_service_permission
Create Date: 2016-02-26 10:33:20.536362

"""

# revision identifiers, used by Alembic.
revision = '0028_add_default_permissions'
down_revision = '0027_add_service_permission'
import uuid
from datetime import datetime
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    user_services = conn.execute("SELECT * FROM user_to_service").fetchall()
    for entry in user_services:
        id_ = uuid.uuid4()
        created_at = datetime.now().isoformat().replace('T', ' ')
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'manage_service', '{}')").format(id_, entry[0], entry[1], created_at))
        id_ = uuid.uuid4()
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'send_messages', '{}')").format(id_, entry[0], entry[1], created_at))
        id_ = uuid.uuid4()
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'manage_api_keys', '{}')").format(id_, entry[0], entry[1], created_at))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    conn.execute("DELETE FROM permissions")

    ### end Alembic commands ###

Add default permissions for existing services.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """empty message

Revision ID: 0028_add_default_permissions
Revises: 0027_add_service_permission
Create Date: 2016-02-26 10:33:20.536362

"""

# revision identifiers, used by Alembic.
revision = '0028_add_default_permissions'
down_revision = '0027_add_service_permission'
import uuid
from datetime import datetime
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    user_services = conn.execute("SELECT * FROM user_to_service").fetchall()
    for entry in user_services:
        id_ = uuid.uuid4()
        created_at = datetime.now().isoformat().replace('T', ' ')
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'manage_service', '{}')").format(id_, entry[0], entry[1], created_at))
        id_ = uuid.uuid4()
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'send_messages', '{}')").format(id_, entry[0], entry[1], created_at))
        id_ = uuid.uuid4()
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'manage_api_keys', '{}')").format(id_, entry[0], entry[1], created_at))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    conn.execute("DELETE FROM permissions")

    ### end Alembic commands ### <REPLACE_END> <|endoftext|> """empty message

Revision ID: 0028_add_default_permissions
Revises: 0027_add_service_permission
Create Date: 2016-02-26 10:33:20.536362

"""

# revision identifiers, used by Alembic.
revision = '0028_add_default_permissions'
down_revision = '0027_add_service_permission'
import uuid
from datetime import datetime
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    user_services = conn.execute("SELECT * FROM user_to_service").fetchall()
    for entry in user_services:
        id_ = uuid.uuid4()
        created_at = datetime.now().isoformat().replace('T', ' ')
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'manage_service', '{}')").format(id_, entry[0], entry[1], created_at))
        id_ = uuid.uuid4()
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'send_messages', '{}')").format(id_, entry[0], entry[1], created_at))
        id_ = uuid.uuid4()
        conn.execute((
            "INSERT INTO permissions (id, user_id, service_id, permission, created_at)"
            " VALUES ('{}', '{}', '{}', 'manage_api_keys', '{}')").format(id_, entry[0], entry[1], created_at))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    conn.execute("DELETE FROM permissions")

    ### end Alembic commands ###

Prompt: Add default permissions for existing services.


import datetime
import math

from core import test_helper

# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
    # Write code here
    pass

# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
    # Write code here
    pass

def main():
    print "\nRunning playing_with_dt_one function..."
    test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))

    print "\nRunning playing_with_dt_one function..."
    test_helper(playing_with_math(), math.pi)

if __name__ == '__main__':
    main()

Revert "Added solutions for lesson 4"

Response:
<REPLACE_OLD> return datetime.datetime(2015, 06, 01)

# <REPLACE_NEW> # Write code here
    pass

# <REPLACE_END> <REPLACE_OLD> return math.pi

def <REPLACE_NEW> # Write code here
    pass

def <REPLACE_END> <|endoftext|> import datetime
import math

from core import test_helper

# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
    # Write code here
    pass

# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
    # Write code here
    pass

def main():
    print "\nRunning playing_with_dt_one function..."
    test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))

    print "\nRunning playing_with_dt_one function..."
    test_helper(playing_with_math(), math.pi)

if __name__ == '__main__':
    main()

Prompt:
Revert "Added solutions for lesson 4"

This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.

import datetime
import math

from core import test_helper

# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
    return datetime.datetime(2015, 06, 01)

# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
    return math.pi

def main():
    print "\nRunning playing_with_dt_one function..."
    test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))

    print "\nRunning playing_with_dt_one function..."
    test_helper(playing_with_math(), math.pi)

if __name__ == '__main__':
    main()


from ..utils import *

##
# Minions

# Dalaran Aspirant
class AT_006:
	inspire = Buff(SELF, "AT_006e")

# Spellslinger
class AT_007:
	play = Give(ALL_PLAYERS, RandomSpell())

# Rhonin
class AT_009:
	deathrattle = Give(CONTROLLER, "EX1_277") * 3

##
# Spells

# Flame Lance
class AT_001:
	play = Hit(TARGET, 8)

# Arcane Blast
class AT_004:
	play = Hit(TARGET, 2)

# Polymorph: Boar
class AT_005:
	play = Morph(TARGET, "AT_005t")

##
# Secrets

# Effigy
class AT_002:
	events = Death(FRIENDLY + MINION).on(
		lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
	)

Response:
<INSERT> Minions

# Dalaran Aspirant
class AT_006:
	inspire = Buff(SELF, "AT_006e")

# Spellslinger
class AT_007:
	play = Give(ALL_PLAYERS, RandomSpell())

# Rhonin
class AT_009:
	deathrattle = Give(CONTROLLER, "EX1_277") * 3

##
# Spells

# Flame Lance
class AT_001:
	play = Hit(TARGET, 8)

# Arcane Blast
class AT_004:
	play = Hit(TARGET, 2)

# Polymorph: Boar
class AT_005:
	play = Morph(TARGET, "AT_005t")

##
# <INSERT_END> <|endoftext|> from ..utils import *

##
# Minions

# Dalaran Aspirant
class AT_006:
	inspire = Buff(SELF, "AT_006e")

# Spellslinger
class AT_007:
	play = Give(ALL_PLAYERS, RandomSpell())

# Rhonin
class AT_009:
	deathrattle = Give(CONTROLLER, "EX1_277") * 3

##
# Spells

# Flame Lance
class AT_001:
	play = Hit(TARGET, 8)

# Arcane Blast
class AT_004:
	play = Hit(TARGET, 2)

# Polymorph: Boar
class AT_005:
	play = Morph(TARGET, "AT_005t")

##
# Secrets

# Effigy
class AT_002:
	events = Death(FRIENDLY + MINION).on(
		lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
	)

Prompt:
Implement Mage cards for The Grand Tournament

from ..utils import *

##
# Secrets

# Effigy
class AT_002:
	events = Death(FRIENDLY + MINION).on(
		lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
	)


from gratipay.wireup import db, env
from gratipay.models.team import Team, AlreadyMigrated

db = db(env())

slugs = db.all("""
    SELECT slug
      FROM teams
     WHERE is_approved IS TRUE
""")

for slug in slugs:
    team = Team.from_slug(slug)
    try:
        team.migrate_tips()
        print("Migrated tips for '%s'" % slug)
    except AlreadyMigrated:
        print("'%s' already migrated." % slug)

print("Done.")

Add script for migrating tips to new teams

Response:
<INSERT> from gratipay.wireup import db, env
from gratipay.models.team import Team, AlreadyMigrated

db = db(env())

slugs = db.all("""
 <INSERT_END> <INSERT>   SELECT slug
      FROM teams
     WHERE is_approved IS TRUE
""")

for slug in slugs:
    team = Team.from_slug(slug)
    try:
        team.migrate_tips()
        print("Migrated tips for '%s'" % slug)
    except AlreadyMigrated:
        print("'%s' already migrated." % slug)

print("Done.")
 <INSERT_END> <|endoftext|> from gratipay.wireup import db, env
from gratipay.models.team import Team, AlreadyMigrated

db = db(env())

slugs = db.all("""
    SELECT slug
      FROM teams
     WHERE is_approved IS TRUE
""")

for slug in slugs:
    team = Team.from_slug(slug)
    try:
        team.migrate_tips()
        print("Migrated tips for '%s'" % slug)
    except AlreadyMigrated:
        print("'%s' already migrated." % slug)

print("Done.")

Prompt: Add script for migrating tips to new teams


"""
This is a setup.py script generated by py2applet

Usage:
    python setup.py py2app
"""

from setuptools import setup
from glob import glob
import syncplay

APP = ['syncplayClient.py']
DATA_FILES = [
    ('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
	'iconfile':'resources/icon.icns',
	'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
    'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
    'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
	'plist': {
		'CFBundleName':'Syncplay',
		'CFBundleShortVersionString':syncplay.version,
		'CFBundleIdentifier':'pl.syncplay.Syncplay',
		'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
	}
}

setup(
    app=APP,
    name='Syncplay',
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

Update py2app script for Qt 5.11

Update py2app script for Qt 5.11

Response:
<REPLACE_OLD> 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
	'plist': <REPLACE_NEW> 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
	'plist': <REPLACE_END> <|endoftext|> """
This is a setup.py script generated by py2applet

Usage:
    python setup.py py2app
"""

from setuptools import setup
from glob import glob
import syncplay

APP = ['syncplayClient.py']
DATA_FILES = [
    ('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
	'iconfile':'resources/icon.icns',
	'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
    'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
    'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
	'plist': {
		'CFBundleName':'Syncplay',
		'CFBundleShortVersionString':syncplay.version,
		'CFBundleIdentifier':'pl.syncplay.Syncplay',
		'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
	}
}

setup(
    app=APP,
    name='Syncplay',
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

Prompt:
Update py2app script for Qt 5.11

"""
This is a setup.py script generated by py2applet

Usage:
    python setup.py py2app
"""

from setuptools import setup
from glob import glob
import syncplay

APP = ['syncplayClient.py']
DATA_FILES = [
    ('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
	'iconfile':'resources/icon.icns',
	'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
    'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
    'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
	'plist': {
		'CFBundleName':'Syncplay',
		'CFBundleShortVersionString':syncplay.version,
		'CFBundleIdentifier':'pl.syncplay.Syncplay',
		'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
	}
}

setup(
    app=APP,
    name='Syncplay',
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)


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

import os
import unittest

from helper.read_data_file import read_int_array
from sorting.heap_sort import sort

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

class InsertionSortTester(unittest.TestCase):

    # Test sort in default order, i.e., in ascending order.
    def test_sort_default(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array)
        expect = [65, 76, 86, 113, 140, 417, 444, 445, 567, 589, 637, 647, 702, 864, 969]
        self.assertEqual(expect, array)

    # Test sort in ascending order.
    def test_sort_ascending(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array, 'asc')
        expect = [65, 76, 86, 113, 140, 417, 444, 445, 567, 589, 637, 647, 702, 864, 969]
        self.assertEqual(expect, array)

    # Test sort in descending order.
    def test_sort_descending(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array, 'desc')
        expect = [969, 864, 702, 647, 637, 589, 567, 445, 444, 417, 140, 113, 86, 76, 65]
        self.assertEqual(expect, array)

if __name__ == '__main__':

    unittest.main()

Add unit test for heap sort implementation.

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

import os
import unittest

from helper.read_data_file import read_int_array
from sorting.heap_sort import sort

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

class InsertionSortTester(unittest.TestCase):

    # Test sort in default order, i.e., in ascending order.
    def test_sort_default(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array)
        expect = [65, 76, 86, 113, 140, 417, 444, 445, 567, 589, 637, 647, 702, 864, 969]
        self.assertEqual(expect, array)

    # Test sort in ascending order.
    def test_sort_ascending(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array, 'asc')
        expect = [65, 76, 86, 113, 140, 417, 444, 445, 567, 589, 637, 647, 702, 864, 969]
        self.assertEqual(expect, array)

    # Test sort in descending order.
    def test_sort_descending(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array, 'desc')
        expect = [969, 864, 702, 647, 637, 589, 567, 445, 444, 417, 140, 113, 86, 76, 65]
        self.assertEqual(expect, array)

if __name__ == '__main__':

    unittest.main()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import unittest

from helper.read_data_file import read_int_array
from sorting.heap_sort import sort

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

class InsertionSortTester(unittest.TestCase):

    # Test sort in default order, i.e., in ascending order.
    def test_sort_default(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array)
        expect = [65, 76, 86, 113, 140, 417, 444, 445, 567, 589, 637, 647, 702, 864, 969]
        self.assertEqual(expect, array)

    # Test sort in ascending order.
    def test_sort_ascending(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array, 'asc')
        expect = [65, 76, 86, 113, 140, 417, 444, 445, 567, 589, 637, 647, 702, 864, 969]
        self.assertEqual(expect, array)

    # Test sort in descending order.
    def test_sort_descending(self):

        array = read_int_array(os.path.join(BASE_DIR, 'data1.data'))
        array = sort(array, 'desc')
        expect = [969, 864, 702, 647, 637, 589, 567, 445, 444, 417, 140, 113, 86, 76, 65]
        self.assertEqual(expect, array)

if __name__ == '__main__':

    unittest.main()

Prompt: Add unit test for heap sort implementation.


import requests
import bs4
import os
import urllib.request
import shutil
import re

base_url = 'http://www.jav11b.com/cn/vl_searchbyid.php?keyword='
srcDir = 'H:\\temp'
filterWord = "video_jacket_img"

filenames = os.listdir(srcDir)
for filename in filenames:
    preFileName = filename.split(".")[0]
    if (preFileName[-1] == "A" or preFileName[-1] == "B" or preFileName[-1] == "C"):
        preFileName = preFileName[0:len(preFileName) - 1]
    destPicName = srcDir + os.sep + preFileName + '.jpg'
    if (os.path.isfile(destPicName)):
        print(destPicName + ' already here.\n')
    else:
        full_url = base_url + preFileName
        response = requests.get(full_url)
        soup = bs4.BeautifulSoup(response.text, "html.parser")
        try:
            imgsrc = soup.find(id = filterWord)['src']
            print(preFileName + "\n" + imgsrc)

            print(destPicName + "\n")
            if not (os.path.isfile(destPicName)):
                urllib.request.urlretrieve(imgsrc, destPicName)
        except:
            print('Can not find picture of ' + filename + '\n')

Update the pic download base url.

Update the pic download base url.

Response:
<REPLACE_OLD> 'http://www.j8vlib.com/cn/vl_searchbyid.php?keyword='
srcDir = 'F:\\utorrent\\WEST'
filterWord <REPLACE_NEW> 'http://www.jav11b.com/cn/vl_searchbyid.php?keyword='
srcDir = 'H:\\temp'
filterWord <REPLACE_END> <|endoftext|> import requests
import bs4
import os
import urllib.request
import shutil
import re

base_url = 'http://www.jav11b.com/cn/vl_searchbyid.php?keyword='
srcDir = 'H:\\temp'
filterWord = "video_jacket_img"

filenames = os.listdir(srcDir)
for filename in filenames:
    preFileName = filename.split(".")[0]
    if (preFileName[-1] == "A" or preFileName[-1] == "B" or preFileName[-1] == "C"):
        preFileName = preFileName[0:len(preFileName) - 1]
    destPicName = srcDir + os.sep + preFileName + '.jpg'
    if (os.path.isfile(destPicName)):
        print(destPicName + ' already here.\n')
    else:
        full_url = base_url + preFileName
        response = requests.get(full_url)
        soup = bs4.BeautifulSoup(response.text, "html.parser")
        try:
            imgsrc = soup.find(id = filterWord)['src']
            print(preFileName + "\n" + imgsrc)

            print(destPicName + "\n")
            if not (os.path.isfile(destPicName)):
                urllib.request.urlretrieve(imgsrc, destPicName)
        except:
            print('Can not find picture of ' + filename + '\n')

Prompt:
Update the pic download base url.

import requests
import bs4
import os
import urllib.request
import shutil
import re

base_url = 'http://www.j8vlib.com/cn/vl_searchbyid.php?keyword='
srcDir = 'F:\\utorrent\\WEST'
filterWord = "video_jacket_img"

filenames = os.listdir(srcDir)
for filename in filenames:
    preFileName = filename.split(".")[0]
    if (preFileName[-1] == "A" or preFileName[-1] == "B" or preFileName[-1] == "C"):
        preFileName = preFileName[0:len(preFileName) - 1]
    destPicName = srcDir + os.sep + preFileName + '.jpg'
    if (os.path.isfile(destPicName)):
        print(destPicName + ' already here.\n')
    else:
        full_url = base_url + preFileName
        response = requests.get(full_url)
        soup = bs4.BeautifulSoup(response.text, "html.parser")
        try:
            imgsrc = soup.find(id = filterWord)['src']
            print(preFileName + "\n" + imgsrc)

            print(destPicName + "\n")
            if not (os.path.isfile(destPicName)):
                urllib.request.urlretrieve(imgsrc, destPicName)
        except:
            print('Can not find picture of ' + filename + '\n')


"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger(object):
   def isInteger(self):
       """
       @return True if this NestedInteger holds a single integer, rather than a nested list.
       :rtype bool
       """

   def getInteger(self):
       """
       @return the single integer that this NestedInteger holds, if it holds a single integer
       Return None if this NestedInteger holds a nested list
       :rtype int
       """

   def getList(self):
       """
       @return the nested list that this NestedInteger holds, if it holds a nested list
       Return None if this NestedInteger holds a single integer
       :rtype List[NestedInteger]
       """

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.stack = [[nestedList, 0]]

    def next(self):
        """
        :rtype: int
        """
        nestedList, i = self.stack[-1]
        self.stack[-1][1] += 1
        return nestedList[i].getInteger()

    def hasNext(self):
        """
        :rtype: bool
        """
        stk = self.stack
        while stk:
            nestedList, i = stk[-1]
            if i == len(nestedList):
                stk.pop()
            else:
                val = nestedList[i]
                if val.isInteger():
                    return True
                else:
                    stk[-1][1] += 1
                    stk.append([val.getList(), 0])
        return False

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

Use stack to solve the problem

Use stack to solve the problem

Response:
<REPLACE_OLD>  <REPLACE_NEW> """
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger(object):
   def isInteger(self):
       """
       @return True if this NestedInteger holds a single integer, rather than a nested list.
       :rtype bool
       """

   def getInteger(self):
       """
       @return the single integer that this NestedInteger holds, if it holds a single integer
       Return None if this NestedInteger holds a nested list
       :rtype int
       """

   def getList(self):
       """
       @return the nested list that this NestedInteger holds, if it holds a nested list
       Return None if this NestedInteger holds a single integer
       :rtype List[NestedInteger]
       """

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.stack = [[nestedList, 0]]

    def next(self):
        """
        :rtype: int
        """
        nestedList, i = self.stack[-1]
        self.stack[-1][1] += 1
        return nestedList[i].getInteger()

    def hasNext(self):
        """
        :rtype: bool
        """
        stk = self.stack
        while stk:
            nestedList, i = stk[-1]
            if i == len(nestedList):
                stk.pop()
            else:
                val = nestedList[i]
                if val.isInteger():
                    return True
                else:
                    stk[-1][1] += 1
                    stk.append([val.getList(), 0])
        return False

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
 <REPLACE_END> <|endoftext|> """
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger(object):
   def isInteger(self):
       """
       @return True if this NestedInteger holds a single integer, rather than a nested list.
       :rtype bool
       """

   def getInteger(self):
       """
       @return the single integer that this NestedInteger holds, if it holds a single integer
       Return None if this NestedInteger holds a nested list
       :rtype int
       """

   def getList(self):
       """
       @return the nested list that this NestedInteger holds, if it holds a nested list
       Return None if this NestedInteger holds a single integer
       :rtype List[NestedInteger]
       """

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.stack = [[nestedList, 0]]

    def next(self):
        """
        :rtype: int
        """
        nestedList, i = self.stack[-1]
        self.stack[-1][1] += 1
        return nestedList[i].getInteger()

    def hasNext(self):
        """
        :rtype: bool
        """
        stk = self.stack
        while stk:
            nestedList, i = stk[-1]
            if i == len(nestedList):
                stk.pop()
            else:
                val = nestedList[i]
                if val.isInteger():
                    return True
                else:
                    stk[-1][1] += 1
                    stk.append([val.getList(), 0])
        return False

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

Prompt: Use stack to solve the problem


"""MetricSource that serves dummy data."""

import random
from vumidash.base import MetricSource, UnknownMetricError

class DummyClient(MetricSource):
    """Serve dummy data."""

    def __init__(self):
        self.latest = None
        self.metric_prefix = "test"
        self.prev_values = {}  # map of metrics to previous values

    def new_value(self, metric):
        values = self.prev_values.setdefault(metric, [])
        values.insert(0, random.uniform(0, 100))
        return values

    def get_latest(self, metric, start, end, summary_size, skip_nulls=True):
        values = self.get_history(metric, start, end, summary_size, skip_nulls)
        return values[0], values[-1]

    def get_history(self, metric, start, end, summary_size, skip_nulls=True):
        if not metric.startswith(self.metric_prefix):
            raise UnknownMetricError("Uknown metric %r" % (metric,))
        steps = int(self.total_seconds((-start) - (-end))
                    / float(self.total_seconds(summary_size)))
        values = self.new_value(metric)
        while len(values) < steps:
            values = self.new_value(metric)
        return values[:steps]

Response:
<REPLACE_OLD> (self.total_seconds((-start) <REPLACE_NEW> int(self.total_seconds((-start) <REPLACE_END> <INSERT>    <INSERT_END> <|endoftext|> """MetricSource that serves dummy data."""

import random
from vumidash.base import MetricSource, UnknownMetricError

class DummyClient(MetricSource):
    """Serve dummy data."""

    def __init__(self):
        self.latest = None
        self.metric_prefix = "test"
        self.prev_values = {}  # map of metrics to previous values

    def new_value(self, metric):
        values = self.prev_values.setdefault(metric, [])
        values.insert(0, random.uniform(0, 100))
        return values

    def get_latest(self, metric, start, end, summary_size, skip_nulls=True):
        values = self.get_history(metric, start, end, summary_size, skip_nulls)
        return values[0], values[-1]

    def get_history(self, metric, start, end, summary_size, skip_nulls=True):
        if not metric.startswith(self.metric_prefix):
            raise UnknownMetricError("Uknown metric %r" % (metric,))
        steps = int(self.total_seconds((-start) - (-end))
                    / float(self.total_seconds(summary_size)))
        values = self.new_value(metric)
        while len(values) < steps:
            values = self.new_value(metric)
        return values[:steps]

Prompt:
Fix steps calculation in dummy client -- how did this work before?

"""MetricSource that serves dummy data."""

import random
from vumidash.base import MetricSource, UnknownMetricError

class DummyClient(MetricSource):
    """Serve dummy data."""

    def __init__(self):
        self.latest = None
        self.metric_prefix = "test"
        self.prev_values = {}  # map of metrics to previous values

    def new_value(self, metric):
        values = self.prev_values.setdefault(metric, [])
        values.insert(0, random.uniform(0, 100))
        return values

    def get_latest(self, metric, start, end, summary_size, skip_nulls=True):
        values = self.get_history(metric, start, end, summary_size, skip_nulls)
        return values[0], values[-1]

    def get_history(self, metric, start, end, summary_size, skip_nulls=True):
        if not metric.startswith(self.metric_prefix):
            raise UnknownMetricError("Uknown metric %r" % (metric,))
        steps = (self.total_seconds((-start) - (-end))
                 / float(self.total_seconds(summary_size)))
        values = self.new_value(metric)
        while len(values) < steps:
            values = self.new_value(metric)
        return values[:steps]


from django.forms.widgets import Select

class LayoutSelector(Select):
    """
    Modified `Select` class to select the original value.

    This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
    .py` in the `django-fluent-pages` app.
    """
    def render(self, name, value, attrs=None, *args, **kwargs):
        """
        Modified render to set the data original value.

        :param name: The name of the `Select` field.
        :param value: The value of the `Select` field.
        :param attrs: Additional attributes of the `Select` field.
        :param args: pass along any other arguments.
        :param kwargs: pass along any other keyword arguments.
        :return: HTML select.
        """
        if attrs:
            attrs['data-original-value'] = value
        return super(LayoutSelector, self).render(name, value, attrs, *args, **kwargs)

Response:
<REPLACE_OLD> choices=()):
 <REPLACE_NEW> *args, **kwargs):
 <REPLACE_END> <REPLACE_OLD> choices: Available choices for the `Select` field.
 <REPLACE_NEW> args: pass along any other arguments.
        :param kwargs: pass along any other keyword arguments.
 <REPLACE_END> <REPLACE_OLD> choices)
 <REPLACE_NEW> *args, **kwargs)
 <REPLACE_END> <|endoftext|> from django.forms.widgets import Select

class LayoutSelector(Select):
    """
    Modified `Select` class to select the original value.

    This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
    .py` in the `django-fluent-pages` app.
    """
    def render(self, name, value, attrs=None, *args, **kwargs):
        """
        Modified render to set the data original value.

        :param name: The name of the `Select` field.
        :param value: The value of the `Select` field.
        :param attrs: Additional attributes of the `Select` field.
        :param args: pass along any other arguments.
        :param kwargs: pass along any other keyword arguments.
        :return: HTML select.
        """
        if attrs:
            attrs['data-original-value'] = value
        return super(LayoutSelector, self).render(name, value, attrs, *args, **kwargs)

Prompt:
Remove keyword argument and allow generic argument passing.

from django.forms.widgets import Select

class LayoutSelector(Select):
    """
    Modified `Select` class to select the original value.

    This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
    .py` in the `django-fluent-pages` app.
    """
    def render(self, name, value, attrs=None, choices=()):
        """
        Modified render to set the data original value.

        :param name: The name of the `Select` field.
        :param value: The value of the `Select` field.
        :param attrs: Additional attributes of the `Select` field.
        :param choices: Available choices for the `Select` field.
        :return: HTML select.
        """
        if attrs:
            attrs['data-original-value'] = value
        return super(LayoutSelector, self).render(name, value, attrs, choices)


"""\
Perl code emitter for C'Dent
"""

from __future__ import absolute_import

from cdent.emitter import Emitter as Base

class Emitter(Base):
    LANGUAGE_ID = 'pm'

    def emit_includecdent(self, includecdent):
        self.writeln('use CDent::Run;')

    def emit_class(self, class_):
        name = class_.name
        self.writeln('package %s;' % name)
        self.writeln('use Moose;')
        self.writeln()
        self.emit(class_.has)
        self.writeln()
        self.writeln('1;')

    def emit_method(self, method):
        name = method.name
        self.writeln('sub %s {' % name)
        self.writeln('    my $self = shift;')
        self.emit(method.has, indent=True)
        self.writeln('}')

    def emit_println(self, println):
        self.write('print ', indent=True)
        self.emit(println.args)
        self.writeln(', "\\n";', indent=False)

    def emit_return(self, ret):
        self.writeln('return;')

Use Moose for Perl 5

Use Moose for Perl 5

Response:
<REPLACE_OLD> CDent::Class;')
 <REPLACE_NEW> Moose;')
 <REPLACE_END> <|endoftext|> """\
Perl code emitter for C'Dent
"""

from __future__ import absolute_import

from cdent.emitter import Emitter as Base

class Emitter(Base):
    LANGUAGE_ID = 'pm'

    def emit_includecdent(self, includecdent):
        self.writeln('use CDent::Run;')

    def emit_class(self, class_):
        name = class_.name
        self.writeln('package %s;' % name)
        self.writeln('use Moose;')
        self.writeln()
        self.emit(class_.has)
        self.writeln()
        self.writeln('1;')

    def emit_method(self, method):
        name = method.name
        self.writeln('sub %s {' % name)
        self.writeln('    my $self = shift;')
        self.emit(method.has, indent=True)
        self.writeln('}')

    def emit_println(self, println):
        self.write('print ', indent=True)
        self.emit(println.args)
        self.writeln(', "\\n";', indent=False)

    def emit_return(self, ret):
        self.writeln('return;')

Prompt:
Use Moose for Perl 5

"""\
Perl code emitter for C'Dent
"""

from __future__ import absolute_import

from cdent.emitter import Emitter as Base

class Emitter(Base):
    LANGUAGE_ID = 'pm'

    def emit_includecdent(self, includecdent):
        self.writeln('use CDent::Run;')

    def emit_class(self, class_):
        name = class_.name
        self.writeln('package %s;' % name)
        self.writeln('use CDent::Class;')
        self.writeln()
        self.emit(class_.has)
        self.writeln()
        self.writeln('1;')

    def emit_method(self, method):
        name = method.name
        self.writeln('sub %s {' % name)
        self.writeln('    my $self = shift;')
        self.emit(method.has, indent=True)
        self.writeln('}')

    def emit_println(self, println):
        self.write('print ', indent=True)
        self.emit(println.args)
        self.writeln(', "\\n";', indent=False)

    def emit_return(self, ret):
        self.writeln('return;')


import difflib

import numpy as np
import pytest

from mbuild.tests.base_test import BaseTest
from mbuild.utils.io import get_fn, import_
from mbuild.utils.validation import assert_port_exists

class TestUtils(BaseTest):

    def test_assert_port_exists(self, ch2):
        assert_port_exists('up', ch2)
        with pytest.raises(ValueError):
            assert_port_exists('dog', ch2)

    def test_structure_reproducibility(self, alkane_monolayer):
        filename = 'monolayer-tmp.pdb'
        alkane_monolayer.save(filename)
        with open(get_fn('monolayer.pdb')) as file1:
            with open('monolayer-tmp.pdb') as file2:
                diff = difflib.ndiff(file1.readlines(), file2.readlines())
        changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')]
        assert not changes

    def test_fn(self):
        get_fn('benzene.mol2')

        with pytest.raises((IOError, OSError)):
            get_fn('garbage_file_name.foo')

    def test_import(self):
        assert np == import_('numpy')

        with pytest.raises(ImportError):
            import_('garbagepackagename')

Add some unit test on utils.io

Add some unit test on utils.io

Response:
<REPLACE_OLD> difflib
import pytest
from <REPLACE_NEW> difflib

import numpy as np
import pytest

from <REPLACE_END> <REPLACE_OLD> get_fn
from <REPLACE_NEW> get_fn, import_
from <REPLACE_END> <REPLACE_OLD> changes
 <REPLACE_NEW> changes

    def test_fn(self):
        get_fn('benzene.mol2')

        with pytest.raises((IOError, OSError)):
            get_fn('garbage_file_name.foo')

    def test_import(self):
        assert np == import_('numpy')

        with pytest.raises(ImportError):
            import_('garbagepackagename')
 <REPLACE_END> <|endoftext|> import difflib

import numpy as np
import pytest

from mbuild.tests.base_test import BaseTest
from mbuild.utils.io import get_fn, import_
from mbuild.utils.validation import assert_port_exists

class TestUtils(BaseTest):

    def test_assert_port_exists(self, ch2):
        assert_port_exists('up', ch2)
        with pytest.raises(ValueError):
            assert_port_exists('dog', ch2)

    def test_structure_reproducibility(self, alkane_monolayer):
        filename = 'monolayer-tmp.pdb'
        alkane_monolayer.save(filename)
        with open(get_fn('monolayer.pdb')) as file1:
            with open('monolayer-tmp.pdb') as file2:
                diff = difflib.ndiff(file1.readlines(), file2.readlines())
        changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')]
        assert not changes

    def test_fn(self):
        get_fn('benzene.mol2')

        with pytest.raises((IOError, OSError)):
            get_fn('garbage_file_name.foo')

    def test_import(self):
        assert np == import_('numpy')

        with pytest.raises(ImportError):
            import_('garbagepackagename')

Prompt:
Add some unit test on utils.io

import difflib
import pytest
from mbuild.tests.base_test import BaseTest
from mbuild.utils.io import get_fn
from mbuild.utils.validation import assert_port_exists

class TestUtils(BaseTest):

    def test_assert_port_exists(self, ch2):
        assert_port_exists('up', ch2)
        with pytest.raises(ValueError):
            assert_port_exists('dog', ch2)

    def test_structure_reproducibility(self, alkane_monolayer):
        filename = 'monolayer-tmp.pdb'
        alkane_monolayer.save(filename)
        with open(get_fn('monolayer.pdb')) as file1:
            with open('monolayer-tmp.pdb') as file2:
                diff = difflib.ndiff(file1.readlines(), file2.readlines())
        changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')]
        assert not changes


import subprocess
import requests

def check_online():
    """Check whether the device has logged in.
    Return a dictionary containing:
        username
        byte
        duration (in seconds)
    Return False if no logged in
    """
    r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
                      data={'action': 'check_online'})
    if r:  # status: OK
        infos = r.text.split(',')
        if len(infos) == 5:  # Decode successfully
            return dict(username=infos[1],
                        byte=infos[2],
                        duration=infos[4])
    # Failed to get infos
    return False

def arp_scan():
    """Generate (IP, MAC) pairs using arp-scan"""
    proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE)
    out = proc.stdout
    # Skip the first two lines.
    next(out)
    next(out)
    # Parse IPs & MACs
    for line in out:
        infos = line.split()
        if not infos:  # Empty line at the end of the output
            return
        if len(infos) < 2:
            raise RuntimeError('Invalid output of arp-scan: "%s"' % line)
        yield (infos[0], infos[1])  # Generate (IP, MAC)

Change name: logged_in => check_online

Change name: logged_in => check_online

Response:
<REPLACE_OLD> logged_in():
 <REPLACE_NEW> check_online():
 <REPLACE_END> <|endoftext|> import subprocess
import requests

def check_online():
    """Check whether the device has logged in.
    Return a dictionary containing:
        username
        byte
        duration (in seconds)
    Return False if no logged in
    """
    r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
                      data={'action': 'check_online'})
    if r:  # status: OK
        infos = r.text.split(',')
        if len(infos) == 5:  # Decode successfully
            return dict(username=infos[1],
                        byte=infos[2],
                        duration=infos[4])
    # Failed to get infos
    return False

def arp_scan():
    """Generate (IP, MAC) pairs using arp-scan"""
    proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE)
    out = proc.stdout
    # Skip the first two lines.
    next(out)
    next(out)
    # Parse IPs & MACs
    for line in out:
        infos = line.split()
        if not infos:  # Empty line at the end of the output
            return
        if len(infos) < 2:
            raise RuntimeError('Invalid output of arp-scan: "%s"' % line)
        yield (infos[0], infos[1])  # Generate (IP, MAC)

Prompt:
Change name: logged_in => check_online

import subprocess
import requests

def logged_in():
    """Check whether the device has logged in.
    Return a dictionary containing:
        username
        byte
        duration (in seconds)
    Return False if no logged in
    """
    r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
                      data={'action': 'check_online'})
    if r:  # status: OK
        infos = r.text.split(',')
        if len(infos) == 5:  # Decode successfully
            return dict(username=infos[1],
                        byte=infos[2],
                        duration=infos[4])
    # Failed to get infos
    return False

def arp_scan():
    """Generate (IP, MAC) pairs using arp-scan"""
    proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE)
    out = proc.stdout
    # Skip the first two lines.
    next(out)
    next(out)
    # Parse IPs & MACs
    for line in out:
        infos = line.split()
        if not infos:  # Empty line at the end of the output
            return
        if len(infos) < 2:
            raise RuntimeError('Invalid output of arp-scan: "%s"' % line)
        yield (infos[0], infos[1])  # Generate (IP, MAC)


# Use the newer `setuptools.setup()`, if available.
try:
    from setuptools import setup
    kw = {
        'test_suite': 'tests',
        'tests_require': ['astunparse'],
    }
except ImportError:
    from distutils.core import setup
    kw = {}

setup(name='gast',  # gast, daou naer!
      version='0.2.0',
      packages=['gast'],
      description='Python AST that abstracts the underlying Python version',
      long_description='''
A generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST).

GAST provides a compatibility layer between the AST of various Python versions,
as produced by ``ast.parse`` from the standard ``ast`` module.''',
      author='serge-sans-paille',
      author_email='serge.guelton@telecom-bretagne.eu',
      license="BSD 3-Clause",
      classifiers=['Development Status :: 4 - Beta',
                   'Environment :: Console',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Natural Language :: English',
                   'Programming Language :: Python :: 2',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Programming Language :: Python :: 3.6',
                   ],
      python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
      **kw
      )

Response:
<REPLACE_OLD> 3'],
 <REPLACE_NEW> 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Programming Language :: Python :: 3.6',
                   ],
      python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
 <REPLACE_END> <|endoftext|> # Use the newer `setuptools.setup()`, if available.
try:
    from setuptools import setup
    kw = {
        'test_suite': 'tests',
        'tests_require': ['astunparse'],
    }
except ImportError:
    from distutils.core import setup
    kw = {}

setup(name='gast',  # gast, daou naer!
      version='0.2.0',
      packages=['gast'],
      description='Python AST that abstracts the underlying Python version',
      long_description='''
A generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST).

GAST provides a compatibility layer between the AST of various Python versions,
as produced by ``ast.parse`` from the standard ``ast`` module.''',
      author='serge-sans-paille',
      author_email='serge.guelton@telecom-bretagne.eu',
      license="BSD 3-Clause",
      classifiers=['Development Status :: 4 - Beta',
                   'Environment :: Console',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Natural Language :: English',
                   'Programming Language :: Python :: 2',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Programming Language :: Python :: 3.6',
                   ],
      python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
      **kw
      )

Prompt:
Add python_requires to help pip, and Trove classifiers

# Use the newer `setuptools.setup()`, if available.
try:
    from setuptools import setup
    kw = {
        'test_suite': 'tests',
        'tests_require': ['astunparse'],
    }
except ImportError:
    from distutils.core import setup
    kw = {}

setup(name='gast',  # gast, daou naer!
      version='0.2.0',
      packages=['gast'],
      description='Python AST that abstracts the underlying Python version',
      long_description='''
A generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST).

GAST provides a compatibility layer between the AST of various Python versions,
as produced by ``ast.parse`` from the standard ``ast`` module.''',
      author='serge-sans-paille',
      author_email='serge.guelton@telecom-bretagne.eu',
      license="BSD 3-Clause",
      classifiers=['Development Status :: 4 - Beta',
                   'Environment :: Console',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Natural Language :: English',
                   'Programming Language :: Python :: 2',
                   'Programming Language :: Python :: 3'],
      **kw
      )


# coding: utf-8
from openupgradelib import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    openupgrade.rename_tables(cr, [('survey', 'survey_survey')])
    openupgrade.rename_models(cr, [('survey', 'survey.survey')])

[ADD] Rename model to prevent crash during module upgrade in tests

Response:
<INSERT> # coding: utf-8
from openupgradelib import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
 <INSERT_END> <INSERT>   openupgrade.rename_tables(cr, [('survey', 'survey_survey')])
    openupgrade.rename_models(cr, [('survey', 'survey.survey')])
 <INSERT_END> <|endoftext|> # coding: utf-8
from openupgradelib import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    openupgrade.rename_tables(cr, [('survey', 'survey_survey')])
    openupgrade.rename_models(cr, [('survey', 'survey.survey')])

Prompt: [ADD] Rename model to prevent crash during module upgrade in tests


from django.conf import settings

def branding(request):
    return {
        "site_name": settings.SITE_NAME,
        "site_logo_url": settings.SITE_LOGO_URL,
    }

Response:
<DELETE> "site_root": settings.SITE_ROOT,
        <DELETE_END> <|endoftext|> from django.conf import settings

def branding(request):
    return {
        "site_name": settings.SITE_NAME,
        "site_logo_url": settings.SITE_LOGO_URL,
    }

Prompt:
Remove site_root from template context, it's never used

from django.conf import settings

def branding(request):
    return {
        "site_name": settings.SITE_NAME,
        "site_root": settings.SITE_ROOT,
        "site_logo_url": settings.SITE_LOGO_URL,
    }