# Django settings for example_project project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'example_project.sqlite3',
    }
}

SITE_ID = 1

SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

APPEND_SLASH = True

ROOT_URLCONF = 'example_project.urls'

STATIC_URL = '/static/'

DJANGO_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
)

THIRD_PARTY_APPS = (
    'embed_video',
)

LOCAL_APPS = (
    'example_project',
    'posts',
)

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

Append slash to urls in example project

Append slash to urls in example project

Response:
<REPLACE_OLD> 'django.template.loaders.app_directories.Loader',
)

ROOT_URLCONF <REPLACE_NEW> 'django.template.loaders.app_directories.Loader',
)

APPEND_SLASH = True

ROOT_URLCONF <REPLACE_END> <|endoftext|> # Django settings for example_project project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'example_project.sqlite3',
    }
}

SITE_ID = 1

SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

APPEND_SLASH = True

ROOT_URLCONF = 'example_project.urls'

STATIC_URL = '/static/'

DJANGO_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
)

THIRD_PARTY_APPS = (
    'embed_video',
)

LOCAL_APPS = (
    'example_project',
    'posts',
)

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

Prompt:
Append slash to urls in example project

# Django settings for example_project project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'example_project.sqlite3',
    }
}

SITE_ID = 1

SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

ROOT_URLCONF = 'example_project.urls'

STATIC_URL = '/static/'

DJANGO_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
)

THIRD_PARTY_APPS = (
    'embed_video',
)

LOCAL_APPS = (
    'example_project',
    'posts',
)

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS


from django import template
import markdown as md
import bleach
import copy

register = template.Library()

def markdown(value):
    """convert to markdown"""
    allowed_tags = bleach.ALLOWED_TAGS + ['blockquote', 'pre', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
    return bleach.clean(md.markdown(value), tags = allowed_tags)

register.filter('markdown', markdown)

Add pre tag to cloud notes

Add pre tag to cloud notes

Response:
<REPLACE_OLD> ['p', <REPLACE_NEW> ['blockquote', 'pre', 'p', <REPLACE_END> <REPLACE_OLD> markdown) <REPLACE_NEW> markdown)
 <REPLACE_END> <|endoftext|> from django import template
import markdown as md
import bleach
import copy

register = template.Library()

def markdown(value):
    """convert to markdown"""
    allowed_tags = bleach.ALLOWED_TAGS + ['blockquote', 'pre', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
    return bleach.clean(md.markdown(value), tags = allowed_tags)

register.filter('markdown', markdown)

Prompt:
Add pre tag to cloud notes

from django import template
import markdown as md
import bleach
import copy

register = template.Library()

def markdown(value):
    """convert to markdown"""
    allowed_tags = bleach.ALLOWED_TAGS + ['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
    return bleach.clean(md.markdown(value), tags = allowed_tags)

register.filter('markdown', markdown)


# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = os.path.join(here, 'README.rst')

install_requirements = [
    'requests',
    # PyBit and dependencies
    'pybit',
    # 'psycopg2',
    # 'amqplib',
    'jsonpickle',
    ]
test_requirements = []
# These requirements are specifically for the legacy module.
legacy_requirements = []

setup(
    name='roadrunners',
    version='1.0',
    author="Connexions/Rhaptos Team",
    author_email="info@cnx.org",
    long_description=open(README).read(),
    url='https://github.com/connexions/roadrunners',
    license='AGPL',  # See also LICENSE.txt
    packages=find_packages(),
    include_package_data=True,
    install_requires=install_requirements,
    extras_require={
        'tests': test_requirements,
        'legacy': legacy_requirements,
        },
    entry_points = """\
    """,
    )

Put in the necessary pybit dependenies

Put in the necessary pybit dependenies

Response:
<INSERT> 'requests',
    # PyBit and dependencies
    <INSERT_END> <REPLACE_OLD> 'jsonpickle',
 <REPLACE_NEW> # 'psycopg2',
 <REPLACE_END> <REPLACE_OLD> 'requests',
 <REPLACE_NEW> # 'amqplib',
    'jsonpickle',
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = os.path.join(here, 'README.rst')

install_requirements = [
    'requests',
    # PyBit and dependencies
    'pybit',
    # 'psycopg2',
    # 'amqplib',
    'jsonpickle',
    ]
test_requirements = []
# These requirements are specifically for the legacy module.
legacy_requirements = []

setup(
    name='roadrunners',
    version='1.0',
    author="Connexions/Rhaptos Team",
    author_email="info@cnx.org",
    long_description=open(README).read(),
    url='https://github.com/connexions/roadrunners',
    license='AGPL',  # See also LICENSE.txt
    packages=find_packages(),
    include_package_data=True,
    install_requires=install_requirements,
    extras_require={
        'tests': test_requirements,
        'legacy': legacy_requirements,
        },
    entry_points = """\
    """,
    )

Prompt:
Put in the necessary pybit dependenies

# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = os.path.join(here, 'README.rst')

install_requirements = [
    'pybit',
    'jsonpickle',
    'requests',
    ]
test_requirements = []
# These requirements are specifically for the legacy module.
legacy_requirements = []

setup(
    name='roadrunners',
    version='1.0',
    author="Connexions/Rhaptos Team",
    author_email="info@cnx.org",
    long_description=open(README).read(),
    url='https://github.com/connexions/roadrunners',
    license='AGPL',  # See also LICENSE.txt
    packages=find_packages(),
    include_package_data=True,
    install_requires=install_requirements,
    extras_require={
        'tests': test_requirements,
        'legacy': legacy_requirements,
        },
    entry_points = """\
    """,
    )


"""
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser

from invoke import task, run

DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')

@task
def docs(output='html', rebuild=False, show=True):
    """Build the docs and show them in default web browser."""
    build_cmd = 'sphinx-build -b {output} {all} docs docs/_build'.format(
        output=output,
        all='-a -E' if rebuild else '')
    run(build_cmd)

    if show:
        webbrowser.open_new_tab(os.path.join(DOCS_OUTPUT_DIR, 'index.html'))

Add more options to the `docs` task

Add more options to the `docs` task

Response:
<REPLACE_OLD> docs(show=True):
 <REPLACE_NEW> docs(output='html', rebuild=False, show=True):
 <REPLACE_END> <REPLACE_OLD> run('sphinx-build <REPLACE_NEW> build_cmd = 'sphinx-build -b {output} {all} <REPLACE_END> <REPLACE_OLD> docs/_build')
 <REPLACE_NEW> docs/_build'.format(
        output=output,
        all='-a -E' if rebuild else '')
    run(build_cmd)

 <REPLACE_END> <|endoftext|> """
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser

from invoke import task, run

DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')

@task
def docs(output='html', rebuild=False, show=True):
    """Build the docs and show them in default web browser."""
    build_cmd = 'sphinx-build -b {output} {all} docs docs/_build'.format(
        output=output,
        all='-a -E' if rebuild else '')
    run(build_cmd)

    if show:
        webbrowser.open_new_tab(os.path.join(DOCS_OUTPUT_DIR, 'index.html'))

Prompt:
Add more options to the `docs` task

"""
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser

from invoke import task, run

DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')

@task
def docs(show=True):
    """Build the docs and show them in default web browser."""
    run('sphinx-build docs docs/_build')
    if show:
        webbrowser.open_new_tab(os.path.join(DOCS_OUTPUT_DIR, 'index.html'))


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

import logging
import sys

logger = logging.getLogger('dbmigrator')
logger.setLevel(logging.INFO)

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('[%(levelname)s] %(name)s (%(filename)s) - %(message)s'))
logger.addHandler(handler)

Add a logger for dbmigrator that writes to stdout

For example in a migration file
20160128111115_mimetype_removal_from_module_files.py:

```
from dbmigrator import logger

logger.info('message from migration')
```

You will see this when you run the migration:

```
[INFO] dbmigrator (20160128111115_mimetype_removal_from_module_files.py) - message from migration
```

Close #3

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

import logging
import sys

logger = logging.getLogger('dbmigrator')
logger.setLevel(logging.INFO)

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('[%(levelname)s] %(name)s (%(filename)s) - %(message)s'))
logger.addHandler(handler)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import logging
import sys

logger = logging.getLogger('dbmigrator')
logger.setLevel(logging.INFO)

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('[%(levelname)s] %(name)s (%(filename)s) - %(message)s'))
logger.addHandler(handler)

Prompt:
Add a logger for dbmigrator that writes to stdout

For example in a migration file
20160128111115_mimetype_removal_from_module_files.py:

```
from dbmigrator import logger

logger.info('message from migration')
```

You will see this when you run the migration:

```
[INFO] dbmigrator (20160128111115_mimetype_removal_from_module_files.py) - message from migration
```

Close #3


Add back a deleted newline.

Add back a deleted newline.

Response:
<REPLACE_OLD> config

def <REPLACE_NEW> config

def <REPLACE_END> <|endoftext|> # Copyright 2016 Twitter. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
''' version.py '''
from heron.tools.cli.src.python.response import Response, Status
import heron.tools.cli.src.python.args as cli_args
import heron.tools.common.src.python.utils.config as config

def create_parser(subparsers):
  '''
  :param subparsers:
  :return:
  '''
  parser = subparsers.add_parser(
      'version',
      help='Print version of heron-cli',
      usage="%(prog)s",
      add_help=False)

  cli_args.add_titles(parser)

  parser.set_defaults(subcommand='version')
  return parser

# pylint: disable=unused-argument
def run(command, parser, args, unknown_args):
  '''
  :param command:
  :param parser:
  :param args:
  :param unknown_args:
  :return:
  '''
  config.print_build_info()
  return Response(Status.Ok)

Prompt:
Add back a deleted newline.

# Copyright 2016 Twitter. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
''' version.py '''
from heron.tools.cli.src.python.response import Response, Status
import heron.tools.cli.src.python.args as cli_args
import heron.tools.common.src.python.utils.config as config

def create_parser(subparsers):
  '''
  :param subparsers:
  :return:
  '''
  parser = subparsers.add_parser(
      'version',
      help='Print version of heron-cli',
      usage="%(prog)s",
      add_help=False)

  cli_args.add_titles(parser)

  parser.set_defaults(subcommand='version')
  return parser

# pylint: disable=unused-argument
def run(command, parser, args, unknown_args):
  '''
  :param command:
  :param parser:
  :param args:
  :param unknown_args:
  :return:
  '''
  config.print_build_info()
  return Response(Status.Ok)


from nose.tools import assert_greater, assert_less

import collections
import time
import cProfile
import pstats

import pandas as pd
import numpy as np
from numpy.random import normal

from phip import hit_calling

def test_speed(profile=False):
    starts = collections.OrderedDict()
    timings = collections.OrderedDict()
    profilers = collections.OrderedDict()

    def start(name):
        starts[name] = time.time()
        if profile:
            profilers[name] = cProfile.Profile()
            profilers[name].enable()

    def end(name):
        timings[name] = time.time() - starts[name]
        if profile:
            profilers[name].disable()

    num_clones = 100000
    num_beads_only = 8
    num_pull_down = 200
    num_hits = 1000

    data_df = pd.DataFrame(index=[
        "clone_%d" % (i + 1) for i in range(num_clones)
    ])
    means = np.random.normal(0, 10, num_clones)**2
    for i in range(num_beads_only):
        data_df["beads_only_%d" % (i + 1)] = np.random.poisson(means)
    for i in range(num_pull_down):
        data_df["pull_down_%d" % (i + 1)] = np.random.poisson(means)

    beads_only_samples = [c for c in data_df if c.startswith("beads")]
    pull_down_samples = [c for c in data_df if c.startswith("pull_down")]

    # Add some hits
    hit_pairs = set()  # set of (sample, clone)
    while len(hit_pairs) < num_hits:
        sample = np.random.choice(pull_down_samples)
        clone = np.random.choice(data_df.index)
        data_df.loc[clone, sample] = (
            data_df.loc[clone, sample]**2 + 100)
        hit_pairs.add((sample, clone))

    # Also to test that normalization works, make one beads-only sample way
    # bigger than th eother columns.
    data_df["beads_only_1"] *= 1e6

    start("hit_calling")
    hit_calling.do_hit_calling(data_df, beads_only_samples)
    end("hit_calling")

    print("SPEED BENCHMARK")
    print("Results:\n%s" % str(pd.Series(timings)))

    return dict(
        (key, pstats.Stats(value)) for (key, value) in profilers.items())

if __name__ == '__main__':
    # If run directly from python, do profiling and leave the user in a shell
    # to explore results.

    result = test_speed(profile=True)

    for (name, stats) in result.items():
        print("**** %s ****" % name)
        stats.sort_stats("cumtime").reverse_order().print_stats()
        print("")

    # Leave in ipython
    # locals().update(result)
    # import ipdb  # pylint: disable=import-error
    # ipdb.set_trace()

Add speed test for hit calling

Add speed test for hit calling

Response:
<REPLACE_OLD>  <REPLACE_NEW> from nose.tools import assert_greater, assert_less

import collections
import time
import cProfile
import pstats

import pandas as pd
import numpy as np
from numpy.random import normal

from phip import hit_calling

def test_speed(profile=False):
    starts = collections.OrderedDict()
    timings = collections.OrderedDict()
    profilers = collections.OrderedDict()

    def start(name):
        starts[name] = time.time()
        if profile:
            profilers[name] = cProfile.Profile()
            profilers[name].enable()

    def end(name):
        timings[name] = time.time() - starts[name]
        if profile:
            profilers[name].disable()

    num_clones = 100000
    num_beads_only = 8
    num_pull_down = 200
    num_hits = 1000

    data_df = pd.DataFrame(index=[
        "clone_%d" % (i + 1) for i in range(num_clones)
    ])
    means = np.random.normal(0, 10, num_clones)**2
    for i in range(num_beads_only):
        data_df["beads_only_%d" % (i + 1)] = np.random.poisson(means)
    for i in range(num_pull_down):
        data_df["pull_down_%d" % (i + 1)] = np.random.poisson(means)

    beads_only_samples = [c for c in data_df if c.startswith("beads")]
    pull_down_samples = [c for c in data_df if c.startswith("pull_down")]

    # Add some hits
    hit_pairs = set()  # set of (sample, clone)
    while len(hit_pairs) < num_hits:
        sample = np.random.choice(pull_down_samples)
        clone = np.random.choice(data_df.index)
        data_df.loc[clone, sample] = (
            data_df.loc[clone, sample]**2 + 100)
        hit_pairs.add((sample, clone))

    # Also to test that normalization works, make one beads-only sample way
    # bigger than th eother columns.
    data_df["beads_only_1"] *= 1e6

    start("hit_calling")
    hit_calling.do_hit_calling(data_df, beads_only_samples)
    end("hit_calling")

    print("SPEED BENCHMARK")
    print("Results:\n%s" % str(pd.Series(timings)))

    return dict(
        (key, pstats.Stats(value)) for (key, value) in profilers.items())

if __name__ == '__main__':
    # If run directly from python, do profiling and leave the user in a shell
    # to explore results.

    result = test_speed(profile=True)

    for (name, stats) in result.items():
        print("**** %s ****" % name)
        stats.sort_stats("cumtime").reverse_order().print_stats()
        print("")

    # Leave in ipython
    # locals().update(result)
    # import ipdb  # pylint: disable=import-error
    # ipdb.set_trace() <REPLACE_END> <|endoftext|> from nose.tools import assert_greater, assert_less

import collections
import time
import cProfile
import pstats

import pandas as pd
import numpy as np
from numpy.random import normal

from phip import hit_calling

def test_speed(profile=False):
    starts = collections.OrderedDict()
    timings = collections.OrderedDict()
    profilers = collections.OrderedDict()

    def start(name):
        starts[name] = time.time()
        if profile:
            profilers[name] = cProfile.Profile()
            profilers[name].enable()

    def end(name):
        timings[name] = time.time() - starts[name]
        if profile:
            profilers[name].disable()

    num_clones = 100000
    num_beads_only = 8
    num_pull_down = 200
    num_hits = 1000

    data_df = pd.DataFrame(index=[
        "clone_%d" % (i + 1) for i in range(num_clones)
    ])
    means = np.random.normal(0, 10, num_clones)**2
    for i in range(num_beads_only):
        data_df["beads_only_%d" % (i + 1)] = np.random.poisson(means)
    for i in range(num_pull_down):
        data_df["pull_down_%d" % (i + 1)] = np.random.poisson(means)

    beads_only_samples = [c for c in data_df if c.startswith("beads")]
    pull_down_samples = [c for c in data_df if c.startswith("pull_down")]

    # Add some hits
    hit_pairs = set()  # set of (sample, clone)
    while len(hit_pairs) < num_hits:
        sample = np.random.choice(pull_down_samples)
        clone = np.random.choice(data_df.index)
        data_df.loc[clone, sample] = (
            data_df.loc[clone, sample]**2 + 100)
        hit_pairs.add((sample, clone))

    # Also to test that normalization works, make one beads-only sample way
    # bigger than th eother columns.
    data_df["beads_only_1"] *= 1e6

    start("hit_calling")
    hit_calling.do_hit_calling(data_df, beads_only_samples)
    end("hit_calling")

    print("SPEED BENCHMARK")
    print("Results:\n%s" % str(pd.Series(timings)))

    return dict(
        (key, pstats.Stats(value)) for (key, value) in profilers.items())

if __name__ == '__main__':
    # If run directly from python, do profiling and leave the user in a shell
    # to explore results.

    result = test_speed(profile=True)

    for (name, stats) in result.items():
        print("**** %s ****" % name)
        stats.sort_stats("cumtime").reverse_order().print_stats()
        print("")

    # Leave in ipython
    # locals().update(result)
    # import ipdb  # pylint: disable=import-error
    # ipdb.set_trace()

Prompt: Add speed test for hit calling


__author__ = 'perks'

from xlutils.copy import copy
from xlrd import open_workbook
import xlsxwriter

def compose(input, output, mappings):
    START_ROW = 501
    END_ROW = 1000

    rb = open_workbook(input)
    r_sheet = rb.sheet_by_name("CLEAN")

    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet("Clients")

    dic = {}
    print "gothere"

    for col_index, mapping in enumerate(mappings):
        target_header = mapping[0]
        orig_header = mapping[1]

        for i in range(1, r_sheet.ncols):
            col_values = filter(None, r_sheet.col(i))
            col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values)
            col_head = col_values[0]

            if orig_header == col_head:
                migrate_col = [target_header] + col_values[START_ROW:END_ROW]
                dic.update({target_header: migrate_col})
                break

        if dic.has_key(target_header):
            for row_index, cell in enumerate(dic[target_header]):
                cell_write(worksheet, row_index, col_index, cell)

    workbook.close()

def cell_write(sheet,row_index, col_index, value):
        sheet.write(row_index, col_index, value)

if __name__ == '__main__':

    import argparse

    parser = argparse.ArgumentParser(
            description='Migrate columns from one spreadsheet to columns in a new spreadsheet.'
        )
    parser.add_argument(
            '-i',
            '--input',
            help='Input .xlsx file',
            required=True
        )
    parser.add_argument(
            '-o',
            '--output',
            help='Output .xlsx file name',
            default='xlsxcompose.xlsx'
        )
    parser.add_argument(
            '-m',
            '--mappings',
            help='File with map configurations inform of TargetCol=OriginalCol',
            required=True
        )
    args = parser.parse_args()

    try:
        lines = [line.strip() for line in open(args.mappings)]
        mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]]
        compose(args.input, args.output, mappings)
    except Exception,e:
        print "Error parsing your column mappings"
        print e

    print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)

Load settings from file, fix logic

Load settings from file, fix logic

Response:
<INSERT> __author__ = 'perks'

from xlutils.copy <INSERT_END> <REPLACE_OLD> argparse
__author__ = 'perks'

if <REPLACE_NEW> copy
from xlrd import open_workbook
import xlsxwriter

def compose(input, output, mappings):
    START_ROW = 501
    END_ROW = 1000

    rb = open_workbook(input)
    r_sheet = rb.sheet_by_name("CLEAN")

    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet("Clients")

    dic = {}
    print "gothere"

    for col_index, mapping in enumerate(mappings):
        target_header = mapping[0]
        orig_header = mapping[1]

        for i in range(1, r_sheet.ncols):
            col_values = filter(None, r_sheet.col(i))
            col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values)
            col_head = col_values[0]

            if orig_header == col_head:
                migrate_col = [target_header] + col_values[START_ROW:END_ROW]
                dic.update({target_header: migrate_col})
                break

        if dic.has_key(target_header):
            for row_index, cell in enumerate(dic[target_header]):
                cell_write(worksheet, row_index, col_index, cell)

    workbook.close()

def cell_write(sheet,row_index, col_index, value):
        sheet.write(row_index, col_index, value)

if <REPLACE_END> <INSERT>    import argparse

 <INSERT_END> <REPLACE_OLD> 'mapping', <REPLACE_NEW> '-m',
            '--mappings', <REPLACE_END> <REPLACE_OLD> nargs='+',
            help='Comma separated <REPLACE_NEW> help='File with map configurations inform of TargetCol=OriginalCol',
            required=True
        )
    args = parser.parse_args()

    try:
        lines = [line.strip() for line in open(args.mappings)]
        mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]]
        compose(args.input, args.output, mappings)
    except Exception,e:
        print "Error parsing your <REPLACE_END> <REPLACE_OLD> relations in the form of OriginalCol=TargetCol'
        )
    args = parser.parse_args()

 <REPLACE_NEW> mappings"
     <REPLACE_END> <REPLACE_OLD> args

 <REPLACE_NEW> e

    print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)

 <REPLACE_END> <|endoftext|> __author__ = 'perks'

from xlutils.copy import copy
from xlrd import open_workbook
import xlsxwriter

def compose(input, output, mappings):
    START_ROW = 501
    END_ROW = 1000

    rb = open_workbook(input)
    r_sheet = rb.sheet_by_name("CLEAN")

    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet("Clients")

    dic = {}
    print "gothere"

    for col_index, mapping in enumerate(mappings):
        target_header = mapping[0]
        orig_header = mapping[1]

        for i in range(1, r_sheet.ncols):
            col_values = filter(None, r_sheet.col(i))
            col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values)
            col_head = col_values[0]

            if orig_header == col_head:
                migrate_col = [target_header] + col_values[START_ROW:END_ROW]
                dic.update({target_header: migrate_col})
                break

        if dic.has_key(target_header):
            for row_index, cell in enumerate(dic[target_header]):
                cell_write(worksheet, row_index, col_index, cell)

    workbook.close()

def cell_write(sheet,row_index, col_index, value):
        sheet.write(row_index, col_index, value)

if __name__ == '__main__':

    import argparse

    parser = argparse.ArgumentParser(
            description='Migrate columns from one spreadsheet to columns in a new spreadsheet.'
        )
    parser.add_argument(
            '-i',
            '--input',
            help='Input .xlsx file',
            required=True
        )
    parser.add_argument(
            '-o',
            '--output',
            help='Output .xlsx file name',
            default='xlsxcompose.xlsx'
        )
    parser.add_argument(
            '-m',
            '--mappings',
            help='File with map configurations inform of TargetCol=OriginalCol',
            required=True
        )
    args = parser.parse_args()

    try:
        lines = [line.strip() for line in open(args.mappings)]
        mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]]
        compose(args.input, args.output, mappings)
    except Exception,e:
        print "Error parsing your column mappings"
        print e

    print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)

Prompt:
Load settings from file, fix logic

import argparse
__author__ = 'perks'

if __name__ == '__main__':

    parser = argparse.ArgumentParser(
            description='Migrate columns from one spreadsheet to columns in a new spreadsheet.'
        )
    parser.add_argument(
            '-i',
            '--input',
            help='Input .xlsx file',
            required=True
        )
    parser.add_argument(
            '-o',
            '--output',
            help='Output .xlsx file name',
            default='xlsxcompose.xlsx'
        )
    parser.add_argument(
            'mapping',
            nargs='+',
            help='Comma separated column relations in the form of OriginalCol=TargetCol'
        )
    args = parser.parse_args()

    print args


"""
Echidna demo server.
"""

import os

from cyclone.web import RequestHandler

from echidna.server import EchidnaServer

class DemoServer(EchidnaServer):
    """
    A server to demo Echidna.
    """

    def __init__(self, **settings):
        defaults = {
            "template_path": (
                os.path.join(os.path.dirname(__file__), "templates")),
            "static_path": (
                os.path.join(os.path.dirname(__file__), "static")),
            "static_url_prefix": "/static/",
            "autoescape": None,
        }
        defaults.update(settings)
        EchidnaServer.__init__(self, DemoPageHandler, **defaults)

class DemoPageHandler(RequestHandler):
    """
    Render the demo page.
    """

    def get(self):
        self.render("demo.html",
                    api_server="localhost:8888",
                    channels=[
                        ("radio_ga_ga", "Radio Ga Ga"),
                        ("channel_x", "Channel X"),
                        ("major_tom", "Major Tom"),
                    ])

Response:
<REPLACE_OLD> self.render("demo.html", api_server="localhost:8888")
 <REPLACE_NEW> self.render("demo.html",
                    api_server="localhost:8888",
                    channels=[
                        ("radio_ga_ga", "Radio Ga Ga"),
                        ("channel_x", "Channel X"),
                        ("major_tom", "Major Tom"),
                    ])
 <REPLACE_END> <|endoftext|> """
Echidna demo server.
"""

import os

from cyclone.web import RequestHandler

from echidna.server import EchidnaServer

class DemoServer(EchidnaServer):
    """
    A server to demo Echidna.
    """

    def __init__(self, **settings):
        defaults = {
            "template_path": (
                os.path.join(os.path.dirname(__file__), "templates")),
            "static_path": (
                os.path.join(os.path.dirname(__file__), "static")),
            "static_url_prefix": "/static/",
            "autoescape": None,
        }
        defaults.update(settings)
        EchidnaServer.__init__(self, DemoPageHandler, **defaults)

class DemoPageHandler(RequestHandler):
    """
    Render the demo page.
    """

    def get(self):
        self.render("demo.html",
                    api_server="localhost:8888",
                    channels=[
                        ("radio_ga_ga", "Radio Ga Ga"),
                        ("channel_x", "Channel X"),
                        ("major_tom", "Major Tom"),
                    ])

Prompt:
Add list of channels to demo.html template context.

"""
Echidna demo server.
"""

import os

from cyclone.web import RequestHandler

from echidna.server import EchidnaServer

class DemoServer(EchidnaServer):
    """
    A server to demo Echidna.
    """

    def __init__(self, **settings):
        defaults = {
            "template_path": (
                os.path.join(os.path.dirname(__file__), "templates")),
            "static_path": (
                os.path.join(os.path.dirname(__file__), "static")),
            "static_url_prefix": "/static/",
            "autoescape": None,
        }
        defaults.update(settings)
        EchidnaServer.__init__(self, DemoPageHandler, **defaults)

class DemoPageHandler(RequestHandler):
    """
    Render the demo page.
    """

    def get(self):
        self.render("demo.html", api_server="localhost:8888")


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

from django.db import migrations, models

class Migration(migrations.Migration):

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

    operations = [
        migrations.AlterField(
            model_name='mailnotifier',
            name='event',
            field=models.CharField(max_length=128, choices=[(b'account_created_from_request', b'account_created_from_request'), (b'account_request_received', b'account_request_received'), (b'allocation_created_from_request', b'allocation_created_from_request'), (b'allocation_expired', b'allocation_expired'), (b'allocation_expiring', b'allocation_expiring'), (b'allocation_request_created_by_user', b'allocation_request_created_by_user'), (b'project_created_by_user', b'project_created_by_user')]),
        ),
    ]

Add db migration: expiration/expiring choices for mailer

Response:
<INSERT> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('mailer', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='mailnotifier',
            name='event',
            field=models.CharField(max_length=128, choices=[(b'account_created_from_request', b'account_created_from_request'), (b'account_request_received', b'account_request_received'), (b'allocation_created_from_request', b'allocation_created_from_request'), (b'allocation_expired', b'allocation_expired'), (b'allocation_expiring', b'allocation_expiring'), (b'allocation_request_created_by_user', b'allocation_request_created_by_user'), (b'project_created_by_user', b'project_created_by_user')]),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

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

    operations = [
        migrations.AlterField(
            model_name='mailnotifier',
            name='event',
            field=models.CharField(max_length=128, choices=[(b'account_created_from_request', b'account_created_from_request'), (b'account_request_received', b'account_request_received'), (b'allocation_created_from_request', b'allocation_created_from_request'), (b'allocation_expired', b'allocation_expired'), (b'allocation_expiring', b'allocation_expiring'), (b'allocation_request_created_by_user', b'allocation_request_created_by_user'), (b'project_created_by_user', b'project_created_by_user')]),
        ),
    ]

Prompt: Add db migration: expiration/expiring choices for mailer


#! usr/bin/env python3

import unittest
from sqlviz import Schema

# Tests will go here...eventually

class InventorySchemaSpec (unittest.TestCase):

    def setUp (self):
        self.schema = Schema(
            """DROP TABLE Inventory;

            CREATE TABLE Inventory
            (
            id INT PRIMARY KEY,
            product VARCHAR(50) UNIQUE,
            quantity INT,
            price DECIMAL(18,2)
            );""")

    def test_n_tables(self):
        self.assertEqual(self.schema.n_tables(),  1,
                        "The Inventory schema should contain 1 table.")

    def test_n_keys(self):
        self.assertEqual(self.schema.n_keys(),  {"PRIMARY KEY": 1, "FOREIGN KEY": 0},
                        "The Inventory schema should contain 1 primary key and 0 foreign keys.")

    def test_n_datatypes(self):
        self.assertEqual(self.schema.n_datatypes(), {"INT": 2, "VARCHAR": 1, "DECIMAL": 1},
                        "The Inventory schema should contain two INTs, one VARCHAR, and one DECIMAL")

    def lengths(self):
        self.assertEqual(self.schema.lengths(), {"VARCHAR": [50], "DECIMAL": [(18,2)]},
                        "The Inventory schema should contain one VARCHAR(50) and one DECIMAL(18,2)")

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

Fix misplaced colon in test suite

Fix misplaced colon in test suite

Response:
<REPLACE_OLD> KEY:" <REPLACE_NEW> KEY": <REPLACE_END> <|endoftext|> #! usr/bin/env python3

import unittest
from sqlviz import Schema

# Tests will go here...eventually

class InventorySchemaSpec (unittest.TestCase):

    def setUp (self):
        self.schema = Schema(
            """DROP TABLE Inventory;

            CREATE TABLE Inventory
            (
            id INT PRIMARY KEY,
            product VARCHAR(50) UNIQUE,
            quantity INT,
            price DECIMAL(18,2)
            );""")

    def test_n_tables(self):
        self.assertEqual(self.schema.n_tables(),  1,
                        "The Inventory schema should contain 1 table.")

    def test_n_keys(self):
        self.assertEqual(self.schema.n_keys(),  {"PRIMARY KEY": 1, "FOREIGN KEY": 0},
                        "The Inventory schema should contain 1 primary key and 0 foreign keys.")

    def test_n_datatypes(self):
        self.assertEqual(self.schema.n_datatypes(), {"INT": 2, "VARCHAR": 1, "DECIMAL": 1},
                        "The Inventory schema should contain two INTs, one VARCHAR, and one DECIMAL")

    def lengths(self):
        self.assertEqual(self.schema.lengths(), {"VARCHAR": [50], "DECIMAL": [(18,2)]},
                        "The Inventory schema should contain one VARCHAR(50) and one DECIMAL(18,2)")

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

Prompt:
Fix misplaced colon in test suite
#! usr/bin/env python3

import unittest
from sqlviz import Schema

# Tests will go here...eventually

class InventorySchemaSpec (unittest.TestCase):

    def setUp (self):
        self.schema = Schema(
            """DROP TABLE Inventory;

            CREATE TABLE Inventory
            (
            id INT PRIMARY KEY,
            product VARCHAR(50) UNIQUE,
            quantity INT,
            price DECIMAL(18,2)
            );""")

    def test_n_tables(self):
        self.assertEqual(self.schema.n_tables(),  1,
                        "The Inventory schema should contain 1 table.")

    def test_n_keys(self):
        self.assertEqual(self.schema.n_keys(),  {"PRIMARY KEY": 1, "FOREIGN KEY:" 0},
                        "The Inventory schema should contain 1 primary key and 0 foreign keys.")

    def test_n_datatypes(self):
        self.assertEqual(self.schema.n_datatypes(), {"INT": 2, "VARCHAR": 1, "DECIMAL": 1},
                        "The Inventory schema should contain two INTs, one VARCHAR, and one DECIMAL")

    def lengths(self):
        self.assertEqual(self.schema.lengths(), {"VARCHAR": [50], "DECIMAL": [(18,2)]},
                        "The Inventory schema should contain one VARCHAR(50) and one DECIMAL(18,2)")

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


import os.path
import json

PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f:
    SMARTPHONE_DEV_IDS = json.load(f)
with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f:
    TABLET_DEV_IDS = json.load(f)

Fix uses of file objects

Fix uses of file objects

Response:
<REPLACE_OLD> json.load(open(f))
with <REPLACE_NEW> json.load(f)
with <REPLACE_END> <REPLACE_OLD> json.load(open())
 <REPLACE_NEW> json.load(f)
 <REPLACE_END> <|endoftext|> import os.path
import json

PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f:
    SMARTPHONE_DEV_IDS = json.load(f)
with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f:
    TABLET_DEV_IDS = json.load(f)

Prompt:
Fix uses of file objects
import os.path
import json

PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f:
    SMARTPHONE_DEV_IDS = json.load(open(f))
with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f:
    TABLET_DEV_IDS = json.load(open())


# -*- coding: utf-8 -*-
from django.db import models, migrations
from django.core.management import call_command

app_name = 'api'
fixture = model_name = 'PartOfSpeech'

def load_fixture(apps, schema_editor):
    call_command('loaddata', fixture, app_label=app_name)

def unload_fixture(apps, schema_editor):
    "Deleting all entries for this model"

    PartOfSpeech = apps.get_model(app_name, model_name)
    PartOfSpeech.objects.all().delete()

class Migration(migrations.Migration):
    dependencies = [
        (app_name, '0008_posmention'),
     ]

    operations = [
        migrations.RunPython(load_fixture, reverse_code=unload_fixture),
    ]

Fix bug in unload_fixture method

Fix bug in unload_fixture method

Response:
<REPLACE_OLD> apps.get_model(api, <REPLACE_NEW> apps.get_model(app_name, <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.core.management import call_command

app_name = 'api'
fixture = model_name = 'PartOfSpeech'

def load_fixture(apps, schema_editor):
    call_command('loaddata', fixture, app_label=app_name)

def unload_fixture(apps, schema_editor):
    "Deleting all entries for this model"

    PartOfSpeech = apps.get_model(app_name, model_name)
    PartOfSpeech.objects.all().delete()

class Migration(migrations.Migration):
    dependencies = [
        (app_name, '0008_posmention'),
     ]

    operations = [
        migrations.RunPython(load_fixture, reverse_code=unload_fixture),
    ]

Prompt:
Fix bug in unload_fixture method
# -*- coding: utf-8 -*-
from django.db import models, migrations
from django.core.management import call_command

app_name = 'api'
fixture = model_name = 'PartOfSpeech'

def load_fixture(apps, schema_editor):
    call_command('loaddata', fixture, app_label=app_name)

def unload_fixture(apps, schema_editor):
    "Deleting all entries for this model"

    PartOfSpeech = apps.get_model(api, model_name)
    PartOfSpeech.objects.all().delete()

class Migration(migrations.Migration):
    dependencies = [
        (app_name, '0008_posmention'),
     ]

    operations = [
        migrations.RunPython(load_fixture, reverse_code=unload_fixture),
    ]


from flexget.manager import Session

def with_session(func):
    """"Creates a session if one was not passed via keyword argument to the function"""

    def wrapper(*args, **kwargs):
        if not kwargs.get('session'):
            kwargs['session'] = Session(autoflush=True)
            try:
                return func(*args, **kwargs)
            finally:
                kwargs['session'].close()
        else:
            return func(*args, **kwargs)
    return wrapper

Response:
<DELETE> passed_session = kwargs.get('session')
        <DELETE_END> <REPLACE_OLD> passed_session:
 <REPLACE_NEW> kwargs.get('session'):
 <REPLACE_END> <REPLACE_OLD> session <REPLACE_NEW> kwargs['session'] <REPLACE_END> <DELETE> session=session, <DELETE_END> <REPLACE_OLD> session.close()
 <REPLACE_NEW> kwargs['session'].close()
 <REPLACE_END> <|endoftext|> from flexget.manager import Session

def with_session(func):
    """"Creates a session if one was not passed via keyword argument to the function"""

    def wrapper(*args, **kwargs):
        if not kwargs.get('session'):
            kwargs['session'] = Session(autoflush=True)
            try:
                return func(*args, **kwargs)
            finally:
                kwargs['session'].close()
        else:
            return func(*args, **kwargs)
    return wrapper

Prompt:
Fix with_session decorator for python 2.5

git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1957 3942dd89-8c5d-46d7-aeed-044bccf3e60c

from flexget.manager import Session

def with_session(func):
    """"Creates a session if one was not passed via keyword argument to the function"""

    def wrapper(*args, **kwargs):
        passed_session = kwargs.get('session')
        if not passed_session:
            session = Session(autoflush=True)
            try:
                return func(*args, session=session, **kwargs)
            finally:
                session.close()
        else:
            return func(*args, **kwargs)
    return wrapper


import json
from django.http import HttpResponse
from maps.models import QuestionSet

def list_question_sets(request):
    objects = QuestionSet.objects.all()
    items = []
    for obj in objects:
        items.append({
            'title': obj.title,
            'max_duration': obj.max_duration.seconds,
            'creator': {
                'full_name': obj.creator.get_full_name()
            }
        })
    return HttpResponse(json.dumps(items))

Add API method for question sets list

Add API method for question sets list

Response:
<REPLACE_OLD> from <REPLACE_NEW> import json
from <REPLACE_END> <REPLACE_OLD> HttpResponse

def <REPLACE_NEW> HttpResponse
from maps.models import QuestionSet

def <REPLACE_END> <INSERT> objects = QuestionSet.objects.all()
    items = []
    for obj in objects:
        items.append({
            'title': obj.title,
            'max_duration': obj.max_duration.seconds,
            'creator': {
                'full_name': obj.creator.get_full_name()
            }
        })
    <INSERT_END> <REPLACE_OLD> HttpResponse('Lol, udachi')
 <REPLACE_NEW> HttpResponse(json.dumps(items))
 <REPLACE_END> <|endoftext|> import json
from django.http import HttpResponse
from maps.models import QuestionSet

def list_question_sets(request):
    objects = QuestionSet.objects.all()
    items = []
    for obj in objects:
        items.append({
            'title': obj.title,
            'max_duration': obj.max_duration.seconds,
            'creator': {
                'full_name': obj.creator.get_full_name()
            }
        })
    return HttpResponse(json.dumps(items))

Prompt:
Add API method for question sets list

from django.http import HttpResponse

def list_question_sets(request):
    return HttpResponse('Lol, udachi')


'''
Module for running arbitrairy tests
'''

import time

def echo(text):
    '''
    Return a string - used for testing the connection

    CLI Example:
    salt '*' test.echo 'foo bar baz quo qux'
    '''
    print 'Echo got called!'
    return text

def ping():
    '''
    Just used to make sure the minion is up and responding
    Return True

    CLI Example:
    salt '*' test.ping
    '''
    return True

def fib(num):
    '''
    Return a fibonachi sequence up to the passed number, and the time it took
    to compute in seconds. Used for performance tests

    CLI Example:
    salt '*' test.fib 3
    '''
    start = time.time()
    a, b = 0, 1
    ret = [0]
    while b < num:
        ret.append(b)
        a, b = b, a + b
    return ret, time.time() - start

def collatz(start):
    '''
    Execute the collatz conjecture from the passed starting number, returns
    the sequence and the time it took to compute. Used for performance tests.

    CLI Example:
    salt '*' test.collatz 3
    '''
    begin = time.time()
    steps = []
    while start != 1:
        steps.append(start)
        if start > 1:
            if start % 2 == 0:
                start = start / 2
            else:
                start = start * 3 + 1
    return steps, time.time() - begin

Fix assignment issue in coallatz

Fix assignment issue in coallatz

Response:
<REPLACE_OLD> start <REPLACE_NEW> begin <REPLACE_END> <REPLACE_OLD> start

 <REPLACE_NEW> begin

 <REPLACE_END> <|endoftext|> '''
Module for running arbitrairy tests
'''

import time

def echo(text):
    '''
    Return a string - used for testing the connection

    CLI Example:
    salt '*' test.echo 'foo bar baz quo qux'
    '''
    print 'Echo got called!'
    return text

def ping():
    '''
    Just used to make sure the minion is up and responding
    Return True

    CLI Example:
    salt '*' test.ping
    '''
    return True

def fib(num):
    '''
    Return a fibonachi sequence up to the passed number, and the time it took
    to compute in seconds. Used for performance tests

    CLI Example:
    salt '*' test.fib 3
    '''
    start = time.time()
    a, b = 0, 1
    ret = [0]
    while b < num:
        ret.append(b)
        a, b = b, a + b
    return ret, time.time() - start

def collatz(start):
    '''
    Execute the collatz conjecture from the passed starting number, returns
    the sequence and the time it took to compute. Used for performance tests.

    CLI Example:
    salt '*' test.collatz 3
    '''
    begin = time.time()
    steps = []
    while start != 1:
        steps.append(start)
        if start > 1:
            if start % 2 == 0:
                start = start / 2
            else:
                start = start * 3 + 1
    return steps, time.time() - begin

Prompt:
Fix assignment issue in coallatz

'''
Module for running arbitrairy tests
'''

import time

def echo(text):
    '''
    Return a string - used for testing the connection

    CLI Example:
    salt '*' test.echo 'foo bar baz quo qux'
    '''
    print 'Echo got called!'
    return text

def ping():
    '''
    Just used to make sure the minion is up and responding
    Return True

    CLI Example:
    salt '*' test.ping
    '''
    return True

def fib(num):
    '''
    Return a fibonachi sequence up to the passed number, and the time it took
    to compute in seconds. Used for performance tests

    CLI Example:
    salt '*' test.fib 3
    '''
    start = time.time()
    a, b = 0, 1
    ret = [0]
    while b < num:
        ret.append(b)
        a, b = b, a + b
    return ret, time.time() - start

def collatz(start):
    '''
    Execute the collatz conjecture from the passed starting number, returns
    the sequence and the time it took to compute. Used for performance tests.

    CLI Example:
    salt '*' test.collatz 3
    '''
    start = time.time()
    steps = []
    while start != 1:
        steps.append(start)
        if start > 1:
            if start % 2 == 0:
                start = start / 2
            else:
                start = start * 3 + 1
    return steps, time.time() - start


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

import sys
import os
import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src/epicslide"))

import rst

class TestRst(object):
    def test_pygments(self):
        p = rst.Pygments('')
        print p.__dict__
        print p.run()
        assert False

    def html_parts(self):
        assert False

    def html_body(self):
        assert False

Structure for the Rst test

Structure for the Rst test

Response:
<INSERT> # -*- coding: utf-8 -*-

import sys
import os
import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src/epicslide"))

import rst

class TestRst(object):
 <INSERT_END> <INSERT>   def test_pygments(self):
        p = rst.Pygments('')
        print p.__dict__
        print p.run()
        assert False

    def html_parts(self):
        assert False

    def html_body(self):
        assert False
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

import sys
import os
import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src/epicslide"))

import rst

class TestRst(object):
    def test_pygments(self):
        p = rst.Pygments('')
        print p.__dict__
        print p.run()
        assert False

    def html_parts(self):
        assert False

    def html_body(self):
        assert False

Prompt: Structure for the Rst test


from twisted.trial import unittest

from ooni.plugoo import work, tests

class WorkerTestCase(unittest.TestCase):
    def testWorkGenerator(self):
        class DummyTest:
            assets = {}
        dummytest = DummyTest()
        asset = []
        for i in range(10):
            asset.append(i)
        dummytest.assets['asset'] = asset
        wgen = work.WorkGenerator(dummytest)
        for j, x in enumerate(wgen):
            pass
        self.assertEqual(i, j)

Write test case for worker

Write test case for worker

Response:
<INSERT> from twisted.trial import unittest

from ooni.plugoo import work, tests

class WorkerTestCase(unittest.TestCase):
 <INSERT_END> <INSERT>   def testWorkGenerator(self):
        class DummyTest:
            assets = {}
        dummytest = DummyTest()
        asset = []
        for i in range(10):
            asset.append(i)
        dummytest.assets['asset'] = asset
        wgen = work.WorkGenerator(dummytest)
        for j, x in enumerate(wgen):
            pass
        self.assertEqual(i, j)

 <INSERT_END> <|endoftext|> from twisted.trial import unittest

from ooni.plugoo import work, tests

class WorkerTestCase(unittest.TestCase):
    def testWorkGenerator(self):
        class DummyTest:
            assets = {}
        dummytest = DummyTest()
        asset = []
        for i in range(10):
            asset.append(i)
        dummytest.assets['asset'] = asset
        wgen = work.WorkGenerator(dummytest)
        for j, x in enumerate(wgen):
            pass
        self.assertEqual(i, j)

Prompt: Write test case for worker


# -*- coding: utf-8 -*-
'''
tests.unit.returners.pgjsonb_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unit tests for the PGJsonb returner (pgjsonb).
'''

# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging

# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
    MagicMock,
    NO_MOCK,
    NO_MOCK_REASON,
    patch
)

# Import Salt libs
import salt.returners.pgjsonb as pgjsonb

log = logging.getLogger(__name__)

@skipIf(NO_MOCK, NO_MOCK_REASON)
class PGJsonbCleanOldJobsTestCase(TestCase, LoaderModuleMockMixin):
    '''
    Tests for the local_cache.clean_old_jobs function.
    '''
    def setup_loader_modules(self):
        return {pgjsonb: {'__opts__': {'keep_jobs': 1, 'archive_jobs': 0}}}

    def test_clean_old_jobs_purge(self):
        '''
        Tests that the function returns None when no jid_root is found.
        '''
        connect_mock = MagicMock()
        with patch.object(pgjsonb, '_get_serv', connect_mock):
            with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}):
                self.assertEqual(pgjsonb.clean_old_jobs(), None)

    def test_clean_old_jobs_archive(self):
        '''
        Tests that the function returns None when no jid_root is found.
        '''
        connect_mock = MagicMock()
        with patch.object(pgjsonb, '_get_serv', connect_mock):
            with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}):
                with patch.dict(pgjsonb.__opts__, {'archive_jobs': 1}):
                    self.assertEqual(pgjsonb.clean_old_jobs(), None)

Revert "Remove pgjsonb returner unit tests"

This reverts commit ab4a670ff22878d5115f408baf0304a0ba3ec994.

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
'''
tests.unit.returners.pgjsonb_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unit tests for the PGJsonb returner (pgjsonb).
'''

# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging

# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
    MagicMock,
    NO_MOCK,
    NO_MOCK_REASON,
    patch
)

# Import Salt libs
import salt.returners.pgjsonb as pgjsonb

log = logging.getLogger(__name__)

@skipIf(NO_MOCK, NO_MOCK_REASON)
class PGJsonbCleanOldJobsTestCase(TestCase, LoaderModuleMockMixin):
    '''
    Tests for the local_cache.clean_old_jobs function.
    '''
    def setup_loader_modules(self):
        return {pgjsonb: {'__opts__': {'keep_jobs': 1, 'archive_jobs': 0}}}

    def test_clean_old_jobs_purge(self):
        '''
        Tests that the function returns None when no jid_root is found.
        '''
        connect_mock = MagicMock()
        with patch.object(pgjsonb, '_get_serv', connect_mock):
            with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}):
                self.assertEqual(pgjsonb.clean_old_jobs(), None)

    def test_clean_old_jobs_archive(self):
        '''
        Tests that the function returns None when no jid_root is found.
        '''
        connect_mock = MagicMock()
        with patch.object(pgjsonb, '_get_serv', connect_mock):
            with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}):
                with patch.dict(pgjsonb.__opts__, {'archive_jobs': 1}):
                    self.assertEqual(pgjsonb.clean_old_jobs(), None)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
'''
tests.unit.returners.pgjsonb_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unit tests for the PGJsonb returner (pgjsonb).
'''

# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging

# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
    MagicMock,
    NO_MOCK,
    NO_MOCK_REASON,
    patch
)

# Import Salt libs
import salt.returners.pgjsonb as pgjsonb

log = logging.getLogger(__name__)

@skipIf(NO_MOCK, NO_MOCK_REASON)
class PGJsonbCleanOldJobsTestCase(TestCase, LoaderModuleMockMixin):
    '''
    Tests for the local_cache.clean_old_jobs function.
    '''
    def setup_loader_modules(self):
        return {pgjsonb: {'__opts__': {'keep_jobs': 1, 'archive_jobs': 0}}}

    def test_clean_old_jobs_purge(self):
        '''
        Tests that the function returns None when no jid_root is found.
        '''
        connect_mock = MagicMock()
        with patch.object(pgjsonb, '_get_serv', connect_mock):
            with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}):
                self.assertEqual(pgjsonb.clean_old_jobs(), None)

    def test_clean_old_jobs_archive(self):
        '''
        Tests that the function returns None when no jid_root is found.
        '''
        connect_mock = MagicMock()
        with patch.object(pgjsonb, '_get_serv', connect_mock):
            with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}):
                with patch.dict(pgjsonb.__opts__, {'archive_jobs': 1}):
                    self.assertEqual(pgjsonb.clean_old_jobs(), None)

Prompt:
Revert "Remove pgjsonb returner unit tests"

This reverts commit ab4a670ff22878d5115f408baf0304a0ba3ec994.


import argparse
import numpy as np

from PIL import Image

lookup = " .,:-!?X#"

def image_to_ascii(image, width=128):
    """
    PIL image object -> 2d array of values

    """
    def scale_height(h, w, new_width):
        print "original height: {}".format(h)
        print "original width: {}".format(w)
        print "new width: {}".format(new_width)
        conversion_factor = float(1.0 * new_width / w)
        print "conversion factor {}".format(conversion_factor)
        new_height = (h * conversion_factor) / 2.0
        print "new height: {}".format(new_height)
        return int(new_height)

    quantised = image.quantize(len(lookup))

    #quantised.show()
    array = np.asarray(quantised.resize((width, scale_height(image.height, image.width, width))))

    return [[lookup[k] for k in i] for i in array]

def convert_file(fn):
    converted = ""
    try:
        image = Image.open(fn)
        converted = image_to_ascii(image)
    except Exception as e:
        print e.message

    return converted

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--filename",
                        help="Convert this file to ASCII art",
                        required=True)
    args = parser.parse_args()
    print args
    filename = args.filename
    converted = convert_file(filename)
    print '\n'.join(''.join(i) for i in converted)

Response:
<REPLACE_OLD> .,:-?X#"

def image_to_ascii(image):
 <REPLACE_NEW> .,:-!?X#"

def image_to_ascii(image, width=128):
 <REPLACE_END> <INSERT> def scale_height(h, w, new_width):
        print "original height: {}".format(h)
        print "original width: {}".format(w)
        print "new width: {}".format(new_width)
        conversion_factor = float(1.0 * new_width / w)
        print "conversion factor {}".format(conversion_factor)
        new_height = (h * conversion_factor) / 2.0
        print "new height: {}".format(new_height)
        return int(new_height)

    <INSERT_END> <REPLACE_OLD> quantised.show()
 <REPLACE_NEW> #quantised.show()
 <REPLACE_END> <REPLACE_OLD> np.asarray(quantised.resize((128,64)))

 <REPLACE_NEW> np.asarray(quantised.resize((width, scale_height(image.height, image.width, width))))

 <REPLACE_END> <|endoftext|> import argparse
import numpy as np

from PIL import Image

lookup = " .,:-!?X#"

def image_to_ascii(image, width=128):
    """
    PIL image object -> 2d array of values

    """
    def scale_height(h, w, new_width):
        print "original height: {}".format(h)
        print "original width: {}".format(w)
        print "new width: {}".format(new_width)
        conversion_factor = float(1.0 * new_width / w)
        print "conversion factor {}".format(conversion_factor)
        new_height = (h * conversion_factor) / 2.0
        print "new height: {}".format(new_height)
        return int(new_height)

    quantised = image.quantize(len(lookup))

    #quantised.show()
    array = np.asarray(quantised.resize((width, scale_height(image.height, image.width, width))))

    return [[lookup[k] for k in i] for i in array]

def convert_file(fn):
    converted = ""
    try:
        image = Image.open(fn)
        converted = image_to_ascii(image)
    except Exception as e:
        print e.message

    return converted

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--filename",
                        help="Convert this file to ASCII art",
                        required=True)
    args = parser.parse_args()
    print args
    filename = args.filename
    converted = convert_file(filename)
    print '\n'.join(''.join(i) for i in converted)

Prompt:
CORRECT height/width conversion this time around

import argparse
import numpy as np

from PIL import Image

lookup = " .,:-?X#"

def image_to_ascii(image):
    """
    PIL image object -> 2d array of values

    """
    quantised = image.quantize(len(lookup))

    quantised.show()
    array = np.asarray(quantised.resize((128,64)))

    return [[lookup[k] for k in i] for i in array]

def convert_file(fn):
    converted = ""
    try:
        image = Image.open(fn)
        converted = image_to_ascii(image)
    except Exception as e:
        print e.message

    return converted

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--filename",
                        help="Convert this file to ASCII art",
                        required=True)
    args = parser.parse_args()
    print args
    filename = args.filename
    converted = convert_file(filename)
    print '\n'.join(''.join(i) for i in converted)


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

from django.apps import apps as global_apps
from django.contrib.contenttypes.management import update_contenttypes
from django.db import models, migrations
from django.utils.timezone import now

MARKER = '.. Migrated from django_comments_xtd.Comment model.\n\n'

comments_app_name = 'django_comments_xtd'
content_type = 'job'

def migrate_old_content(apps, schema_editor):
    try:
        Comment = apps.get_model(comments_app_name, 'XtdComment')
    except LookupError:
        # django_comments_xtd isn't installed.
        return
    update_contenttypes(apps.app_configs['contenttypes'])
    JobReviewComment = apps.get_model('jobs', 'JobReviewComment')
    Job = apps.get_model('jobs', 'Job')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    db_alias = schema_editor.connection.alias
    try:
        job_contenttype = ContentType.objects.using(db_alias).get(name=content_type)
    except ContentType.DoesNotExist:
        return
    old_comments = Comment.objects.using(db_alias).filter(
        content_type=job_contenttype.pk, is_public=True, is_removed=False,
    )
    found_jobs = {}
    comments = []
    for comment in old_comments:
        try:
            job = found_jobs[comment.object_pk]
        except KeyError:
            try:
                job = Job.objects.using(db_alias).get(pk=comment.object_pk)
                found_jobs[comment.object_pk] = job
            except Job.DoesNotExist:
                continue
        review_comment = JobReviewComment(
            job=job,
            comment=MARKER + comment.comment,
            creator=comment.user,
            created=comment.submit_date,
            updated=now(),
        )
        comments.append(review_comment)
    JobReviewComment.objects.using(db_alias).bulk_create(comments)

def delete_migrated_content(apps, schema_editor):
    JobReviewComment = apps.get_model('jobs', 'JobReviewComment')
    db_alias = schema_editor.connection.alias
    JobReviewComment.objects.using(db_alias).filter(comment__startswith=MARKER).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0001_initial'),
        ('jobs', '0011_jobreviewcomment'),
    ]
    if global_apps.is_installed(comments_app_name):
        dependencies.append((comments_app_name, '0001_initial'))

    operations = [
        migrations.RunPython(migrate_old_content, delete_migrated_content),
    ]

Migrate old comments over jobs.JobReviewComment

Fixes #591

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

from django.apps import apps as global_apps
from django.contrib.contenttypes.management import update_contenttypes
from django.db import models, migrations
from django.utils.timezone import now

MARKER = '.. Migrated from django_comments_xtd.Comment model.\n\n'

comments_app_name = 'django_comments_xtd'
content_type = 'job'

def migrate_old_content(apps, schema_editor):
    try:
        Comment = apps.get_model(comments_app_name, 'XtdComment')
    except LookupError:
        # django_comments_xtd isn't installed.
        return
    update_contenttypes(apps.app_configs['contenttypes'])
    JobReviewComment = apps.get_model('jobs', 'JobReviewComment')
    Job = apps.get_model('jobs', 'Job')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    db_alias = schema_editor.connection.alias
    try:
        job_contenttype = ContentType.objects.using(db_alias).get(name=content_type)
    except ContentType.DoesNotExist:
        return
    old_comments = Comment.objects.using(db_alias).filter(
        content_type=job_contenttype.pk, is_public=True, is_removed=False,
    )
    found_jobs = {}
    comments = []
    for comment in old_comments:
        try:
            job = found_jobs[comment.object_pk]
        except KeyError:
            try:
                job = Job.objects.using(db_alias).get(pk=comment.object_pk)
                found_jobs[comment.object_pk] = job
            except Job.DoesNotExist:
                continue
        review_comment = JobReviewComment(
            job=job,
            comment=MARKER + comment.comment,
            creator=comment.user,
            created=comment.submit_date,
            updated=now(),
        )
        comments.append(review_comment)
    JobReviewComment.objects.using(db_alias).bulk_create(comments)

def delete_migrated_content(apps, schema_editor):
    JobReviewComment = apps.get_model('jobs', 'JobReviewComment')
    db_alias = schema_editor.connection.alias
    JobReviewComment.objects.using(db_alias).filter(comment__startswith=MARKER).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0001_initial'),
        ('jobs', '0011_jobreviewcomment'),
    ]
    if global_apps.is_installed(comments_app_name):
        dependencies.append((comments_app_name, '0001_initial'))

    operations = [
        migrations.RunPython(migrate_old_content, delete_migrated_content),
    ]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.apps import apps as global_apps
from django.contrib.contenttypes.management import update_contenttypes
from django.db import models, migrations
from django.utils.timezone import now

MARKER = '.. Migrated from django_comments_xtd.Comment model.\n\n'

comments_app_name = 'django_comments_xtd'
content_type = 'job'

def migrate_old_content(apps, schema_editor):
    try:
        Comment = apps.get_model(comments_app_name, 'XtdComment')
    except LookupError:
        # django_comments_xtd isn't installed.
        return
    update_contenttypes(apps.app_configs['contenttypes'])
    JobReviewComment = apps.get_model('jobs', 'JobReviewComment')
    Job = apps.get_model('jobs', 'Job')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    db_alias = schema_editor.connection.alias
    try:
        job_contenttype = ContentType.objects.using(db_alias).get(name=content_type)
    except ContentType.DoesNotExist:
        return
    old_comments = Comment.objects.using(db_alias).filter(
        content_type=job_contenttype.pk, is_public=True, is_removed=False,
    )
    found_jobs = {}
    comments = []
    for comment in old_comments:
        try:
            job = found_jobs[comment.object_pk]
        except KeyError:
            try:
                job = Job.objects.using(db_alias).get(pk=comment.object_pk)
                found_jobs[comment.object_pk] = job
            except Job.DoesNotExist:
                continue
        review_comment = JobReviewComment(
            job=job,
            comment=MARKER + comment.comment,
            creator=comment.user,
            created=comment.submit_date,
            updated=now(),
        )
        comments.append(review_comment)
    JobReviewComment.objects.using(db_alias).bulk_create(comments)

def delete_migrated_content(apps, schema_editor):
    JobReviewComment = apps.get_model('jobs', 'JobReviewComment')
    db_alias = schema_editor.connection.alias
    JobReviewComment.objects.using(db_alias).filter(comment__startswith=MARKER).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0001_initial'),
        ('jobs', '0011_jobreviewcomment'),
    ]
    if global_apps.is_installed(comments_app_name):
        dependencies.append((comments_app_name, '0001_initial'))

    operations = [
        migrations.RunPython(migrate_old_content, delete_migrated_content),
    ]

Prompt:
Migrate old comments over jobs.JobReviewComment

Fixes #591


from .exposure import histogram, equalize, equalize_hist, \
                      rescale_intensity, cumulative_distribution, \
                      adjust_gamma, adjust_sigmoid, adjust_log

from ._adapthist import equalize_adapthist
from .unwrap import unwrap

__all__ = ['histogram',
           'equalize',
           'equalize_hist',
           'equalize_adapthist',
           'rescale_intensity',
           'cumulative_distribution',
           'adjust_gamma',
           'adjust_sigmoid',
           'adjust_log',
           'unwrap']

Response:
<REPLACE_OLD> equalize_adapthist

__all__ <REPLACE_NEW> equalize_adapthist
from .unwrap import unwrap

__all__ <REPLACE_END> <REPLACE_OLD> 'adjust_log']
 <REPLACE_NEW> 'adjust_log',
           'unwrap']
 <REPLACE_END> <|endoftext|> from .exposure import histogram, equalize, equalize_hist, \
                      rescale_intensity, cumulative_distribution, \
                      adjust_gamma, adjust_sigmoid, adjust_log

from ._adapthist import equalize_adapthist
from .unwrap import unwrap

__all__ = ['histogram',
           'equalize',
           'equalize_hist',
           'equalize_adapthist',
           'rescale_intensity',
           'cumulative_distribution',
           'adjust_gamma',
           'adjust_sigmoid',
           'adjust_log',
           'unwrap']

Prompt:
Make unwrap visible in the exposure package.

from .exposure import histogram, equalize, equalize_hist, \
                      rescale_intensity, cumulative_distribution, \
                      adjust_gamma, adjust_sigmoid, adjust_log

from ._adapthist import equalize_adapthist

__all__ = ['histogram',
           'equalize',
           'equalize_hist',
           'equalize_adapthist',
           'rescale_intensity',
           'cumulative_distribution',
           'adjust_gamma',
           'adjust_sigmoid',
           'adjust_log']


import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Text Playing Game")
        self.set_border_width(10)
        self.set_size_request(500, 400)

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Set GUI title and size

Set GUI title
and size

Response:
<REPLACE_OLD> title="")

win <REPLACE_NEW> title="Text Playing Game")
        self.set_border_width(10)
        self.set_size_request(500, 400)

win <REPLACE_END> <|endoftext|> import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Text Playing Game")
        self.set_border_width(10)
        self.set_size_request(500, 400)

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Prompt:
Set GUI title
and size

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="")

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()


#!/usr/bin/env python
#
# Setup script for Django Evolution

from ez_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages
from setuptools.command.test import test

from django_evolution import get_package_version, VERSION

def run_tests(*args):
    import os
    os.system('tests/runtests.py')

test.run_tests = run_tests

PACKAGE_NAME = 'django_evolution'

download_url = (
    'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' %
    (VERSION[0], VERSION[1]))

# Build the package
setup(
    name=PACKAGE_NAME,
    version=get_package_version(),
    description='A database schema evolution tool for the Django web framework.',
    url='http://code.google.com/p/django-evolution/',
    author='Ben Khoo',
    author_email='khoobks@westnet.com.au',
    maintainer='Christian Hammond',
    maintainer_email='christian@beanbaginc.com',
    download_url=download_url,
    packages=find_packages(exclude=['tests']),
    install_requires=[
        'Django>=1.4.10,<1.7.0',
    ],
    include_package_data=True,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)

Response:
<REPLACE_OLD> 'Django>=1.4.10',
 <REPLACE_NEW> 'Django>=1.4.10,<1.7.0',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# Setup script for Django Evolution

from ez_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages
from setuptools.command.test import test

from django_evolution import get_package_version, VERSION

def run_tests(*args):
    import os
    os.system('tests/runtests.py')

test.run_tests = run_tests

PACKAGE_NAME = 'django_evolution'

download_url = (
    'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' %
    (VERSION[0], VERSION[1]))

# Build the package
setup(
    name=PACKAGE_NAME,
    version=get_package_version(),
    description='A database schema evolution tool for the Django web framework.',
    url='http://code.google.com/p/django-evolution/',
    author='Ben Khoo',
    author_email='khoobks@westnet.com.au',
    maintainer='Christian Hammond',
    maintainer_email='christian@beanbaginc.com',
    download_url=download_url,
    packages=find_packages(exclude=['tests']),
    install_requires=[
        'Django>=1.4.10,<1.7.0',
    ],
    include_package_data=True,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)

Prompt:
Revert "Allow Django Evolution to install along with Django >= 1.7."

This reverts commit 28b280bb04f806f614f6f2cd25ce779b551fef9e.

This was committed to the wrong branch.

#!/usr/bin/env python
#
# Setup script for Django Evolution

from ez_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages
from setuptools.command.test import test

from django_evolution import get_package_version, VERSION

def run_tests(*args):
    import os
    os.system('tests/runtests.py')

test.run_tests = run_tests

PACKAGE_NAME = 'django_evolution'

download_url = (
    'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' %
    (VERSION[0], VERSION[1]))

# Build the package
setup(
    name=PACKAGE_NAME,
    version=get_package_version(),
    description='A database schema evolution tool for the Django web framework.',
    url='http://code.google.com/p/django-evolution/',
    author='Ben Khoo',
    author_email='khoobks@westnet.com.au',
    maintainer='Christian Hammond',
    maintainer_email='christian@beanbaginc.com',
    download_url=download_url,
    packages=find_packages(exclude=['tests']),
    install_requires=[
        'Django>=1.4.10',
    ],
    include_package_data=True,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Process all tasks synchronously.
# Helpful for local development and running tests
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
CELERY_ALWAYS_EAGER = True

try:
    from .local import *
except ImportError:
    pass

Response:
<REPLACE_OLD> True
TEMPLATE_DEBUG <REPLACE_NEW> True
TEMPLATES[0]['OPTIONS']['debug'] <REPLACE_END> <|endoftext|> from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Process all tasks synchronously.
# Helpful for local development and running tests
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
CELERY_ALWAYS_EAGER = True

try:
    from .local import *
except ImportError:
    pass

Prompt:
Update TEMPLATE_DEBUG to Django 1.8 version
from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Process all tasks synchronously.
# Helpful for local development and running tests
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
CELERY_ALWAYS_EAGER = True

try:
    from .local import *
except ImportError:
    pass


from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import angle_isclose, units, vectors

reflect_data = (
    (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
    (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
    (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)),
    (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)),
    (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1))
)

@pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data)
def test_reflect(initial_vector, surface_normal, expected_vector):
    assert initial_vector.reflect(surface_normal).isclose(expected_vector)

@given(initial=vectors(), normal=units())
def test_reflect_prop(initial: Vector2, normal: Vector2):
    assume(initial ^ normal != 0)
    reflected = initial.reflect(normal)
    returned = reflected.reflect(normal)
    note(f"Reflected: {reflected}")
    assert not any(map(isinf, reflected))
    assert initial.isclose(returned)
    assert isclose((initial * normal), -(reflected * normal))
    assert angle_isclose(normal.angle(initial),
                         180 - normal.angle(reflected)
    )

Response:
<INSERT> angle_isclose, <INSERT_END> <INSERT>    assert angle_isclose(normal.angle(initial),
                         180 - normal.angle(reflected)
    )
 <INSERT_END> <|endoftext|> from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import angle_isclose, units, vectors

reflect_data = (
    (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
    (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
    (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)),
    (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)),
    (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1))
)

@pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data)
def test_reflect(initial_vector, surface_normal, expected_vector):
    assert initial_vector.reflect(surface_normal).isclose(expected_vector)

@given(initial=vectors(), normal=units())
def test_reflect_prop(initial: Vector2, normal: Vector2):
    assume(initial ^ normal != 0)
    reflected = initial.reflect(normal)
    returned = reflected.reflect(normal)
    note(f"Reflected: {reflected}")
    assert not any(map(isinf, reflected))
    assert initial.isclose(returned)
    assert isclose((initial * normal), -(reflected * normal))
    assert angle_isclose(normal.angle(initial),
                         180 - normal.angle(reflected)
    )

Prompt:
test_reflect_prop: Add a property tying reflect() and angle()

from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import units, vectors

reflect_data = (
    (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
    (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
    (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)),
    (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)),
    (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1))
)

@pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data)
def test_reflect(initial_vector, surface_normal, expected_vector):
    assert initial_vector.reflect(surface_normal).isclose(expected_vector)

@given(initial=vectors(), normal=units())
def test_reflect_prop(initial: Vector2, normal: Vector2):
    assume(initial ^ normal != 0)
    reflected = initial.reflect(normal)
    returned = reflected.reflect(normal)
    note(f"Reflected: {reflected}")
    assert not any(map(isinf, reflected))
    assert initial.isclose(returned)
    assert isclose((initial * normal), -(reflected * normal))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from sys import version_info
from os import name as OS_NAME

__all__= ['unittest', 'skipIfNtMove']

if version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

skipIfNtMove = unittest.skipIf(OS_NAME == 'nt', "windows can not detect moves")

Response:
<REPLACE_OLD> License.
 <REPLACE_NEW> License.

from sys import version_info
from os import name as OS_NAME

__all__= ['unittest', 'skipIfNtMove']

if version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

skipIfNtMove = unittest.skipIf(OS_NAME == 'nt', "windows can not detect moves")
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from sys import version_info
from os import name as OS_NAME

__all__= ['unittest', 'skipIfNtMove']

if version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

skipIfNtMove = unittest.skipIf(OS_NAME == 'nt', "windows can not detect moves")

Prompt:
Declare unittest lib used within python version

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import requests

def test_rest_api_responsive():
    stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "BE": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "BE": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}'
    url = 'http://ec2-34-226-201-156.compute-1.amazonaws.com:8080/' + \
        'assemblers/cyjs'
    res = requests.post(url, stmt_str)
    assert res.status_code == 200

Add smoke test for REST API on Travis

Add smoke test for REST API on Travis

Response:
<INSERT> import requests

def test_rest_api_responsive():
 <INSERT_END> <INSERT>   stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "BE": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "BE": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}'
    url = 'http://ec2-34-226-201-156.compute-1.amazonaws.com:8080/' + \
        'assemblers/cyjs'
    res = requests.post(url, stmt_str)
    assert res.status_code == 200
 <INSERT_END> <|endoftext|> import requests

def test_rest_api_responsive():
    stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "BE": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "BE": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}'
    url = 'http://ec2-34-226-201-156.compute-1.amazonaws.com:8080/' + \
        'assemblers/cyjs'
    res = requests.post(url, stmt_str)
    assert res.status_code == 200

Prompt: Add smoke test for REST API on Travis


#! python3

''' rename files in local directory with random integer names.

windows screen saver isn't very good at randomizing fotos shown.
Change file names regularly to provide more variety
'''

import os
import re
import random
import time

random.seed()
new_names = set()
original_files = []

for entry in os.listdir():
    if os.path.isfile(entry):
        if re.match(".*jpg", entry):
            original_files.append(entry)

for counter in range(0, len(original_files)):
    new_value = random.randint(0,1000000000)
    # Make sure the new names are unique
    # -- note this is only the new set, the new name
    #    may still duplicate an old name. The set is
    #    to minimize this chance
    while new_value in new_names:
        new_value = random.randint(0,1000000000)
    new_names.add(new_value)

for of in original_files:
    nf = str(new_names.pop()).zfill(10) + ".jpg"

    try:
        os.rename(of, nf)
    except Exception as e:
        print("{}: {}".format(of, e))

time.sleep(5)

Response:
<REPLACE_OLD> ''' <REPLACE_NEW> #! python3

''' <REPLACE_END> <REPLACE_OLD> random

random.seed()
new_names <REPLACE_NEW> random
import time

random.seed()
new_names <REPLACE_END> <REPLACE_OLD> random.randint(0,100000)
 <REPLACE_NEW> random.randint(0,1000000000)
    # Make sure the new names are unique
    # -- note this is only the new set, the new name
    #    may still duplicate an old name. The set is
    #    to minimize this chance
 <REPLACE_END> <REPLACE_OLD> random.randint(0,100000)
 <REPLACE_NEW> random.randint(0,1000000000)
 <REPLACE_END> <REPLACE_OLD> str(new_names.pop()).zfill(6) <REPLACE_NEW> str(new_names.pop()).zfill(10) <REPLACE_END> <INSERT>
time.sleep(5)
 <INSERT_END> <|endoftext|> #! python3

''' rename files in local directory with random integer names.

windows screen saver isn't very good at randomizing fotos shown.
Change file names regularly to provide more variety
'''

import os
import re
import random
import time

random.seed()
new_names = set()
original_files = []

for entry in os.listdir():
    if os.path.isfile(entry):
        if re.match(".*jpg", entry):
            original_files.append(entry)

for counter in range(0, len(original_files)):
    new_value = random.randint(0,1000000000)
    # Make sure the new names are unique
    # -- note this is only the new set, the new name
    #    may still duplicate an old name. The set is
    #    to minimize this chance
    while new_value in new_names:
        new_value = random.randint(0,1000000000)
    new_names.add(new_value)

for of in original_files:
    nf = str(new_names.pop()).zfill(10) + ".jpg"

    try:
        os.rename(of, nf)
    except Exception as e:
        print("{}: {}".format(of, e))

time.sleep(5)

Prompt:
Increase namespace, sleep before cmd window closes
''' rename files in local directory with random integer names.

windows screen saver isn't very good at randomizing fotos shown.
Change file names regularly to provide more variety
'''

import os
import re
import random

random.seed()
new_names = set()
original_files = []

for entry in os.listdir():
    if os.path.isfile(entry):
        if re.match(".*jpg", entry):
            original_files.append(entry)

for counter in range(0, len(original_files)):
    new_value = random.randint(0,100000)
    while new_value in new_names:
        new_value = random.randint(0,100000)
    new_names.add(new_value)

for of in original_files:
    nf = str(new_names.pop()).zfill(6) + ".jpg"

    try:
        os.rename(of, nf)
    except Exception as e:
        print("{}: {}".format(of, e))


from __future__ import absolute_import

from etcd3.client import Etcd3Client
from etcd3.client import client
from etcd3.client import Transactions
from etcd3.members import Member

__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'

__all__ = ['Etcd3Client', 'client', 'etcdrpc', 'utils', 'Transactions',
           'Member']

Make Member part of the public api

Make Member part of the public api

Response:
<REPLACE_OLD> Transactions

__author__ <REPLACE_NEW> Transactions
from etcd3.members import Member

__author__ <REPLACE_END> <REPLACE_OLD> 'Transactions']
 <REPLACE_NEW> 'Transactions',
           'Member']
 <REPLACE_END> <|endoftext|> from __future__ import absolute_import

from etcd3.client import Etcd3Client
from etcd3.client import client
from etcd3.client import Transactions
from etcd3.members import Member

__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'

__all__ = ['Etcd3Client', 'client', 'etcdrpc', 'utils', 'Transactions',
           'Member']

Prompt:
Make Member part of the public api

from __future__ import absolute_import

from etcd3.client import Etcd3Client
from etcd3.client import client
from etcd3.client import Transactions

__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'

__all__ = ['Etcd3Client', 'client', 'etcdrpc', 'utils', 'Transactions']


from st2common.transport import actionexecution, publishers

# TODO(manas) : Exchanges, Queues and RoutingKey design discussion pending.

__all__ = ['actionexecution', 'publishers']

Response:
<REPLACE_OLD> publishers

__all__ <REPLACE_NEW> publishers

# TODO(manas) : Exchanges, Queues and RoutingKey design discussion pending.

__all__ <REPLACE_END> <|endoftext|> from st2common.transport import actionexecution, publishers

# TODO(manas) : Exchanges, Queues and RoutingKey design discussion pending.

__all__ = ['actionexecution', 'publishers']

Prompt:
Add TODO to capture the fact that design discussion is pending.

from st2common.transport import actionexecution, publishers

__all__ = ['actionexecution', 'publishers']


import inspect
import sys
import types

from rmake.lib.apiutils import thaw, freeze

_nodeTypes = {}
class _NodeTypeRegistrar(type):
    def __init__(self, name, bases, dict):
        type.__init__(self, name, bases, dict)
        _nodeTypes[self.nodeType] = self

class NodeType(object):
    __metaclass__ = _NodeTypeRegistrar
    nodeType = 'UNKNOWN'
    def __init__(self):
        pass

    def freeze(self):
        return (self.nodeType, self.__dict__)

    @classmethod
    def thaw(class_, d):
        return class_(**d)

class Client(NodeType):
    nodeType = 'CLIENT'

def thawNodeType(info):
    nodeType = info[0]
    return _nodeTypes[nodeType].thaw(info[1])

Use metaclasses to register node types.

Use metaclasses to register node types.

Response:
<REPLACE_OLD> freeze

class <REPLACE_NEW> freeze

_nodeTypes = {}
class _NodeTypeRegistrar(type):
    def __init__(self, name, bases, dict):
        type.__init__(self, name, bases, dict)
        _nodeTypes[self.nodeType] = self

class <REPLACE_END> <INSERT>    __metaclass__ = _NodeTypeRegistrar
 <INSERT_END> <REPLACE_OLD> 'CLIENT'

_nodeTypes = {}
def registerNodeTypes(moduleName):
    global _nodeTypes
    for item in sys.modules[moduleName].__dict__.values():
        if inspect.isclass(item) and issubclass(item, NodeType):
            _nodeTypes[item.nodeType] = item
registerNodeTypes(__name__)

def registerNodeType(class_):
    _nodeTypes[class_.nodeType] = class_

def <REPLACE_NEW> 'CLIENT'

def <REPLACE_END> <|endoftext|> import inspect
import sys
import types

from rmake.lib.apiutils import thaw, freeze

_nodeTypes = {}
class _NodeTypeRegistrar(type):
    def __init__(self, name, bases, dict):
        type.__init__(self, name, bases, dict)
        _nodeTypes[self.nodeType] = self

class NodeType(object):
    __metaclass__ = _NodeTypeRegistrar
    nodeType = 'UNKNOWN'
    def __init__(self):
        pass

    def freeze(self):
        return (self.nodeType, self.__dict__)

    @classmethod
    def thaw(class_, d):
        return class_(**d)

class Client(NodeType):
    nodeType = 'CLIENT'

def thawNodeType(info):
    nodeType = info[0]
    return _nodeTypes[nodeType].thaw(info[1])

Prompt:
Use metaclasses to register node types.

import inspect
import sys
import types

from rmake.lib.apiutils import thaw, freeze

class NodeType(object):
    nodeType = 'UNKNOWN'
    def __init__(self):
        pass

    def freeze(self):
        return (self.nodeType, self.__dict__)

    @classmethod
    def thaw(class_, d):
        return class_(**d)

class Client(NodeType):
    nodeType = 'CLIENT'

_nodeTypes = {}
def registerNodeTypes(moduleName):
    global _nodeTypes
    for item in sys.modules[moduleName].__dict__.values():
        if inspect.isclass(item) and issubclass(item, NodeType):
            _nodeTypes[item.nodeType] = item
registerNodeTypes(__name__)

def registerNodeType(class_):
    _nodeTypes[class_.nodeType] = class_

def thawNodeType(info):
    nodeType = info[0]
    return _nodeTypes[nodeType].thaw(info[1])