import os
from webassets.filter import ExternalTool, option

__all__ = ('Stylus',)

class Stylus(ExternalTool):
    """Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.

    Requires the Stylus executable to be available externally. You can install
    it using the `Node Package Manager <http://npmjs.org/>`_::

        $ npm install stylus

    Supported configuration options:

    STYLUS_BIN
        The path to the Stylus binary. If not set, assumes ``stylus`` is in the
        system path.

    STYLUS_PLUGINS
        A Python list of Stylus plugins to use. Each plugin will be included
        via Stylus's command-line ``--use`` argument.

    STYLUS_EXTRA_ARGS
        A Python list of any additional command-line arguments.

    STYLUS_EXTRA_PATHS
        A Python list of any additional import paths.
    """

    name = 'stylus'
    options = {
        'stylus': 'STYLUS_BIN',
        'plugins': option('STYLUS_PLUGINS', type=list),
        'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
        'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
    }
    max_debug_level = None

    def input(self, _in, out, **kwargs):
        args = [self.stylus or 'stylus']
        source_dir = os.path.dirname(kwargs['source_path'])
        paths = [source_dir] + (self.extra_paths or [])
        for path in paths:
            args.extend(('--include', path))
        for plugin in self.plugins or []:
            args.extend(('--use', plugin))
        if self.extra_args:
            args.extend(self.extra_args)
        self.subprocess(args, out, _in)

Update Stylus filter with include paths

Response:
<REPLACE_OLD> from <REPLACE_NEW> import os
from <REPLACE_END> <INSERT>
    STYLUS_EXTRA_PATHS
        A Python list of any additional import paths.
    <INSERT_END> <INSERT> type=list),
        'extra_paths': option('STYLUS_EXTRA_PATHS', <INSERT_END> <INSERT>        source_dir = os.path.dirname(kwargs['source_path'])
        paths = [source_dir] + (self.extra_paths or [])
        for path in paths:
            args.extend(('--include', path))
 <INSERT_END> <|endoftext|> import os
from webassets.filter import ExternalTool, option

__all__ = ('Stylus',)

class Stylus(ExternalTool):
    """Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.

    Requires the Stylus executable to be available externally. You can install
    it using the `Node Package Manager <http://npmjs.org/>`_::

        $ npm install stylus

    Supported configuration options:

    STYLUS_BIN
        The path to the Stylus binary. If not set, assumes ``stylus`` is in the
        system path.

    STYLUS_PLUGINS
        A Python list of Stylus plugins to use. Each plugin will be included
        via Stylus's command-line ``--use`` argument.

    STYLUS_EXTRA_ARGS
        A Python list of any additional command-line arguments.

    STYLUS_EXTRA_PATHS
        A Python list of any additional import paths.
    """

    name = 'stylus'
    options = {
        'stylus': 'STYLUS_BIN',
        'plugins': option('STYLUS_PLUGINS', type=list),
        'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
        'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
    }
    max_debug_level = None

    def input(self, _in, out, **kwargs):
        args = [self.stylus or 'stylus']
        source_dir = os.path.dirname(kwargs['source_path'])
        paths = [source_dir] + (self.extra_paths or [])
        for path in paths:
            args.extend(('--include', path))
        for plugin in self.plugins or []:
            args.extend(('--use', plugin))
        if self.extra_args:
            args.extend(self.extra_args)
        self.subprocess(args, out, _in)

Prompt:
Update Stylus filter with include paths

Since the Stylus filter works with stdin, the compiler doesn't know the
source directory, and thus can't resolve any imports. This adds the
source directory to the include path using the `--include` option, and
also adds the `STYLUS_EXTRA_PATHS` option to configure any extra
include paths.
from webassets.filter import ExternalTool, option

__all__ = ('Stylus',)

class Stylus(ExternalTool):
    """Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.

    Requires the Stylus executable to be available externally. You can install
    it using the `Node Package Manager <http://npmjs.org/>`_::

        $ npm install stylus

    Supported configuration options:

    STYLUS_BIN
        The path to the Stylus binary. If not set, assumes ``stylus`` is in the
        system path.

    STYLUS_PLUGINS
        A Python list of Stylus plugins to use. Each plugin will be included
        via Stylus's command-line ``--use`` argument.

    STYLUS_EXTRA_ARGS
        A Python list of any additional command-line arguments.
    """

    name = 'stylus'
    options = {
        'stylus': 'STYLUS_BIN',
        'plugins': option('STYLUS_PLUGINS', type=list),
        'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
    }
    max_debug_level = None

    def input(self, _in, out, **kwargs):
        args = [self.stylus or 'stylus']
        for plugin in self.plugins or []:
            args.extend(('--use', plugin))
        if self.extra_args:
            args.extend(self.extra_args)
        self.subprocess(args, out, _in)


#! /usr/bin/env python

import config
import os

NAME="init"
HELP="give git issues"

def execute(args):
	# Check to see if the .ghi directories have already been created
	# If it doesn't exist, create it.
	if os.path.isdir(config.GHI_DIR) == False:
		os.makedirs(config.GHI_DIR)
		os.makedirs(config.ISSUES_DIR)
	elif os.path.isdir(config.ISSUES_DIR) == False:
		os.makedirs(config.ISSUES_DIR)
	else:
		print "This git already has issues."

Remove no longer needed import

Remove no longer needed import

Response:
<REPLACE_OLD> os
import subprocess
import config

NAME="init"
HELP="give <REPLACE_NEW> config
import os

NAME="init"
HELP="give <REPLACE_END> <|endoftext|> #! /usr/bin/env python

import config
import os

NAME="init"
HELP="give git issues"

def execute(args):
	# Check to see if the .ghi directories have already been created
	# If it doesn't exist, create it.
	if os.path.isdir(config.GHI_DIR) == False:
		os.makedirs(config.GHI_DIR)
		os.makedirs(config.ISSUES_DIR)
	elif os.path.isdir(config.ISSUES_DIR) == False:
		os.makedirs(config.ISSUES_DIR)
	else:
		print "This git already has issues."

Prompt:
Remove no longer needed import

#! /usr/bin/env python

import os
import subprocess
import config

NAME="init"
HELP="give git issues"

def execute(args):
	# Check to see if the .ghi directories have already been created
	# If it doesn't exist, create it.
	if os.path.isdir(config.GHI_DIR) == False:
		os.makedirs(config.GHI_DIR)
		os.makedirs(config.ISSUES_DIR)
	elif os.path.isdir(config.ISSUES_DIR) == False:
		os.makedirs(config.ISSUES_DIR)
	else:
		print "This git already has issues."


import sys
import mailbox
import mail_parser
import nltk
import itertools
try:
    import cPickle as pickle
except ImportError:
    import pickle

def main():
    """Extract the texts of emails from a specified mailbox and
    from a specified set of senders and write corpus.txt.

    Usage: python mail_corpus.py mboxfile email1@example.com email2@example.com
    """
    mbox = mailbox.mbox(sys.argv[1])
    addresses = set(sys.argv[2:])
    f = open("corpus.txt", "w")
    for text in mail_parser.mail_texts(mbox, addresses):
        print >> f, text
    f.close()

if __name__ == '__main__':
    main()

Switch back to always write corpus.txt

Switch back to always write corpus.txt

Response:
<DELETE> output <DELETE_END> <REPLACE_OLD> mailbox.mbox(sys.argv[2])
 <REPLACE_NEW> mailbox.mbox(sys.argv[1])
 <REPLACE_END> <REPLACE_OLD> set(sys.argv[3:])
 <REPLACE_NEW> set(sys.argv[2:])
 <REPLACE_END> <REPLACE_OLD> open(sys.argv[1], <REPLACE_NEW> open("corpus.txt", <REPLACE_END> <|endoftext|> import sys
import mailbox
import mail_parser
import nltk
import itertools
try:
    import cPickle as pickle
except ImportError:
    import pickle

def main():
    """Extract the texts of emails from a specified mailbox and
    from a specified set of senders and write corpus.txt.

    Usage: python mail_corpus.py mboxfile email1@example.com email2@example.com
    """
    mbox = mailbox.mbox(sys.argv[1])
    addresses = set(sys.argv[2:])
    f = open("corpus.txt", "w")
    for text in mail_parser.mail_texts(mbox, addresses):
        print >> f, text
    f.close()

if __name__ == '__main__':
    main()

Prompt:
Switch back to always write corpus.txt

import sys
import mailbox
import mail_parser
import nltk
import itertools
try:
    import cPickle as pickle
except ImportError:
    import pickle

def main():
    """Extract the texts of emails from a specified mailbox and
    from a specified set of senders and write corpus.txt.

    Usage: python mail_corpus.py output mboxfile email1@example.com email2@example.com
    """
    mbox = mailbox.mbox(sys.argv[2])
    addresses = set(sys.argv[3:])
    f = open(sys.argv[1], "w")
    for text in mail_parser.mail_texts(mbox, addresses):
        print >> f, text
    f.close()

if __name__ == '__main__':
    main()


import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("package_list", help="List of packages for which" +
                    " recipies will be created")
args = parser.parse_args()

package_names = [package.strip() for package in
                 open(args.package_list, 'r').readlines()]

log_dir = "./logs/"
recipes_dir = "./recipes/"

build_log_file = open(log_dir + 'build_log', 'w')

successes = []
failures = []

for package in package_names:
    msg = "Creating Conda recipe for %s\n" % (package)
    print(msg)
    err = subprocess.call(['conda', 'build', recipes_dir + package],
                          stdout=build_log_file, stderr=build_log_file)
    if err is 0:
        msg = "Succesfully build conda package for %s\n" % (package)
        successes.append(package)
    else:
        msg = "Failed to conda package for %s\n" % (package)
        failures.append(package)
    print(msg)

build_log_file.close()

successful_recipes_file = open(log_dir + 'successful_builds', 'w')
failed_recipes_file = open(log_dir + 'failed_builds', 'w')

successful_recipes_file.write('\n'.join(successes))
failed_recipes_file.write('\n'.join(failures))

successful_recipes_file.close()
failed_recipes_file.close()

Add script to build conda recipes

Add script to build conda recipes

Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>

Response:
<REPLACE_OLD>  <REPLACE_NEW> import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("package_list", help="List of packages for which" +
                    " recipies will be created")
args = parser.parse_args()

package_names = [package.strip() for package in
                 open(args.package_list, 'r').readlines()]

log_dir = "./logs/"
recipes_dir = "./recipes/"

build_log_file = open(log_dir + 'build_log', 'w')

successes = []
failures = []

for package in package_names:
    msg = "Creating Conda recipe for %s\n" % (package)
    print(msg)
    err = subprocess.call(['conda', 'build', recipes_dir + package],
                          stdout=build_log_file, stderr=build_log_file)
    if err is 0:
        msg = "Succesfully build conda package for %s\n" % (package)
        successes.append(package)
    else:
        msg = "Failed to conda package for %s\n" % (package)
        failures.append(package)
    print(msg)

build_log_file.close()

successful_recipes_file = open(log_dir + 'successful_builds', 'w')
failed_recipes_file = open(log_dir + 'failed_builds', 'w')

successful_recipes_file.write('\n'.join(successes))
failed_recipes_file.write('\n'.join(failures))

successful_recipes_file.close()
failed_recipes_file.close()
 <REPLACE_END> <|endoftext|> import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("package_list", help="List of packages for which" +
                    " recipies will be created")
args = parser.parse_args()

package_names = [package.strip() for package in
                 open(args.package_list, 'r').readlines()]

log_dir = "./logs/"
recipes_dir = "./recipes/"

build_log_file = open(log_dir + 'build_log', 'w')

successes = []
failures = []

for package in package_names:
    msg = "Creating Conda recipe for %s\n" % (package)
    print(msg)
    err = subprocess.call(['conda', 'build', recipes_dir + package],
                          stdout=build_log_file, stderr=build_log_file)
    if err is 0:
        msg = "Succesfully build conda package for %s\n" % (package)
        successes.append(package)
    else:
        msg = "Failed to conda package for %s\n" % (package)
        failures.append(package)
    print(msg)

build_log_file.close()

successful_recipes_file = open(log_dir + 'successful_builds', 'w')
failed_recipes_file = open(log_dir + 'failed_builds', 'w')

successful_recipes_file.write('\n'.join(successes))
failed_recipes_file.write('\n'.join(failures))

successful_recipes_file.close()
failed_recipes_file.close()

Prompt:
Add script to build conda recipes

Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>


import RPi.GPIO as GPIO
import time

# This test is made for a quick check of the gpios

# List of the in channels to test. When pressed they output a message.
in_chanels = []

# A list of output channels to test. These whill be switched on and off in a pattern.
out_chanels = []

def switch_called(channel):
	print 'Edge detected on channel %s'%channel

for in_channel in in_chanels:
    GPIO.setup(in_channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN )
    GPIO.add_event_detect(in_channel, GPIO.RISING, callback=switch_called, bouncetime=300)

for out_channel in out_chanels:
    GPIO.setup(out_channel, GPIO.OUT)
    GPIO.output(out_channel, GPIO.LOW)

print 'Start output test'
while True:
    for out_channel in out_chanels:
    	time.sleep(1)
    	GPIO.output(out_channel, not GPIO.input(out_channel))

Test for rudimentary io tests added

Test for rudimentary io tests added

Response:
<INSERT> import RPi.GPIO as GPIO
import time

# This test is made for a quick check of the gpios

# List of the in channels to test. When pressed they output a message.
in_chanels = []

# A list of output channels to test. These whill be switched on and off in a pattern.
out_chanels = []

def switch_called(channel):
	print 'Edge detected on channel %s'%channel

for in_channel in in_chanels:
 <INSERT_END> <INSERT>   GPIO.setup(in_channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN )
    GPIO.add_event_detect(in_channel, GPIO.RISING, callback=switch_called, bouncetime=300)

for out_channel in out_chanels:
    GPIO.setup(out_channel, GPIO.OUT)
    GPIO.output(out_channel, GPIO.LOW)

print 'Start output test'
while True:
    for out_channel in out_chanels:
    	time.sleep(1)
    	GPIO.output(out_channel, not GPIO.input(out_channel))

     <INSERT_END> <|endoftext|> import RPi.GPIO as GPIO
import time

# This test is made for a quick check of the gpios

# List of the in channels to test. When pressed they output a message.
in_chanels = []

# A list of output channels to test. These whill be switched on and off in a pattern.
out_chanels = []

def switch_called(channel):
	print 'Edge detected on channel %s'%channel

for in_channel in in_chanels:
    GPIO.setup(in_channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN )
    GPIO.add_event_detect(in_channel, GPIO.RISING, callback=switch_called, bouncetime=300)

for out_channel in out_chanels:
    GPIO.setup(out_channel, GPIO.OUT)
    GPIO.output(out_channel, GPIO.LOW)

print 'Start output test'
while True:
    for out_channel in out_chanels:
    	time.sleep(1)
    	GPIO.output(out_channel, not GPIO.input(out_channel))

Prompt: Test for rudimentary io tests added


#!/usr/bin/python
"""
This script touches all files known to the database, creating a skeletal
mirror for local development.
"""

import sys, os
import store

def get_paths(cursor, prefix=None):
    store.safe_execute(cursor, "SELECT python_version, name, filename FROM release_files")

    for type, name, filename in cursor.fetchall():
        yield os.path.join(prefix, type, name[0], name, filename)

if __name__ == '__main__':
    import config
    try:
        config = config.Config(sys.argv[1])
    except IndexError:
        print "Usage: touch_all_files.py config.ini"
        raise SystemExit

    datastore = store.Store(config)
    datastore.open()
    cursor = datastore.get_cursor()
    prefix = config.database_files_dir

    for path in get_paths(cursor, prefix):
        dir = os.path.dirname(path)
        if not os.path.exists(dir):
            print "Creating directory %s" % dir
            os.makedirs(dir)
        if not os.path.exists(path):
            print "Creating file %s" % path
            open(path, "a")

Add script to synthesize all uploaded files. Patch by Dan Callahan.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/python
"""
This script touches all files known to the database, creating a skeletal
mirror for local development.
"""

import sys, os
import store

def get_paths(cursor, prefix=None):
    store.safe_execute(cursor, "SELECT python_version, name, filename FROM release_files")

    for type, name, filename in cursor.fetchall():
        yield os.path.join(prefix, type, name[0], name, filename)

if __name__ == '__main__':
    import config
    try:
        config = config.Config(sys.argv[1])
    except IndexError:
        print "Usage: touch_all_files.py config.ini"
        raise SystemExit

    datastore = store.Store(config)
    datastore.open()
    cursor = datastore.get_cursor()
    prefix = config.database_files_dir

    for path in get_paths(cursor, prefix):
        dir = os.path.dirname(path)
        if not os.path.exists(dir):
            print "Creating directory %s" % dir
            os.makedirs(dir)
        if not os.path.exists(path):
            print "Creating file %s" % path
            open(path, "a")
 <REPLACE_END> <|endoftext|> #!/usr/bin/python
"""
This script touches all files known to the database, creating a skeletal
mirror for local development.
"""

import sys, os
import store

def get_paths(cursor, prefix=None):
    store.safe_execute(cursor, "SELECT python_version, name, filename FROM release_files")

    for type, name, filename in cursor.fetchall():
        yield os.path.join(prefix, type, name[0], name, filename)

if __name__ == '__main__':
    import config
    try:
        config = config.Config(sys.argv[1])
    except IndexError:
        print "Usage: touch_all_files.py config.ini"
        raise SystemExit

    datastore = store.Store(config)
    datastore.open()
    cursor = datastore.get_cursor()
    prefix = config.database_files_dir

    for path in get_paths(cursor, prefix):
        dir = os.path.dirname(path)
        if not os.path.exists(dir):
            print "Creating directory %s" % dir
            os.makedirs(dir)
        if not os.path.exists(path):
            print "Creating file %s" % path
            open(path, "a")

Prompt:
Add script to synthesize all uploaded files.
Patch by Dan Callahan.


import pubrunner
import os
import shlex
import subprocess

def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
	globalSettings = pubrunner.getGlobalSettings()

	clusterFlags = ""
	if useCluster and "cluster" in globalSettings:
		clusterSettings = globalSettings["cluster"]
		jobs = 1
		if "jobs" in globalSettings["cluster"]:
			jobs = int(globalSettings["cluster"]["jobs"])
		clusterFlags = "--jobs %d --latency-wait 60" % jobs

		if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
			clusterFlags += ' --drmaa'
		elif "options" in clusterSettings:
			clusterFlags += " --cluster '%s'" % clusterSettings["options"]
		else:
			raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")

	makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)

	env = os.environ.copy()
	env.update(parameters)

	retval = subprocess.call(shlex.split(makecommand),env=env)
	if retval != 0:
		raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)

Fix for non-DRMAA cluster run

Fix for non-DRMAA cluster run

Response:
<REPLACE_OLD> = "--cluster <REPLACE_NEW> += " --cluster <REPLACE_END> <|endoftext|>
import pubrunner
import os
import shlex
import subprocess

def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
	globalSettings = pubrunner.getGlobalSettings()

	clusterFlags = ""
	if useCluster and "cluster" in globalSettings:
		clusterSettings = globalSettings["cluster"]
		jobs = 1
		if "jobs" in globalSettings["cluster"]:
			jobs = int(globalSettings["cluster"]["jobs"])
		clusterFlags = "--jobs %d --latency-wait 60" % jobs

		if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
			clusterFlags += ' --drmaa'
		elif "options" in clusterSettings:
			clusterFlags += " --cluster '%s'" % clusterSettings["options"]
		else:
			raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")

	makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)

	env = os.environ.copy()
	env.update(parameters)

	retval = subprocess.call(shlex.split(makecommand),env=env)
	if retval != 0:
		raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)

Prompt:
Fix for non-DRMAA cluster run

import pubrunner
import os
import shlex
import subprocess

def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
	globalSettings = pubrunner.getGlobalSettings()

	clusterFlags = ""
	if useCluster and "cluster" in globalSettings:
		clusterSettings = globalSettings["cluster"]
		jobs = 1
		if "jobs" in globalSettings["cluster"]:
			jobs = int(globalSettings["cluster"]["jobs"])
		clusterFlags = "--jobs %d --latency-wait 60" % jobs

		if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
			clusterFlags += ' --drmaa'
		elif "options" in clusterSettings:
			clusterFlags = "--cluster '%s'" % clusterSettings["options"]
		else:
			raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")

	makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)

	env = os.environ.copy()
	env.update(parameters)

	retval = subprocess.call(shlex.split(makecommand),env=env)
	if retval != 0:
		raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)


"""Vumi monitoring and control framework."""

from vumi.blinkenlights.metrics_workers import (MetricTimeBucket,
                                                MetricAggregator,
                                                GraphiteMetricsCollector)

__all__ = ["MetricTimeBucket", "MetricAggregator", "GraphiteMetricsCollector"]

Add blinkenlights metrics workers to vumi.blinkenlights package namespace (for convenience).

Response:
<INSERT> """Vumi monitoring and control framework."""

from vumi.blinkenlights.metrics_workers import (MetricTimeBucket,
 <INSERT_END> <INSERT>                                               MetricAggregator,
                                                GraphiteMetricsCollector)

__all__ = ["MetricTimeBucket", "MetricAggregator", "GraphiteMetricsCollector"]
 <INSERT_END> <|endoftext|> """Vumi monitoring and control framework."""

from vumi.blinkenlights.metrics_workers import (MetricTimeBucket,
                                                MetricAggregator,
                                                GraphiteMetricsCollector)

__all__ = ["MetricTimeBucket", "MetricAggregator", "GraphiteMetricsCollector"]

Prompt: Add blinkenlights metrics workers to vumi.blinkenlights package namespace (for convenience).


import sublime_plugin

from .sublime_lib.path import root_at_packages, get_package_name

PLUGIN_NAME = get_package_name()

SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax"
                   % PLUGIN_NAME)
TPL = '''\
{
    "$1": $0
}'''.replace(" " * 4, "\t")

class NewSettingsCommand(sublime_plugin.WindowCommand):
    def run(self):
        v = self.window.new_file()
        v.settings().set('default_dir', root_at_packages('User'))
        v.set_syntax_file(SETTINGS_SYNTAX)
        v.run_command('insert_snippet', {'contents': TPL})

Response:
<REPLACE_OLD> Settings.tmLanguage"
 <REPLACE_NEW> Text Settings.sublime-syntax"
 <REPLACE_END> <REPLACE_OLD> "{\n\t$0\n}"

class <REPLACE_NEW> '''\
{
    "$1": $0
}'''.replace(" " * 4, "\t")

class <REPLACE_END> <|endoftext|> import sublime_plugin

from .sublime_lib.path import root_at_packages, get_package_name

PLUGIN_NAME = get_package_name()

SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax"
                   % PLUGIN_NAME)
TPL = '''\
{
    "$1": $0
}'''.replace(" " * 4, "\t")

class NewSettingsCommand(sublime_plugin.WindowCommand):
    def run(self):
        v = self.window.new_file()
        v.settings().set('default_dir', root_at_packages('User'))
        v.set_syntax_file(SETTINGS_SYNTAX)
        v.run_command('insert_snippet', {'contents': TPL})

Prompt:
Update syntax path for new settings file command

import sublime_plugin

from .sublime_lib.path import root_at_packages, get_package_name

PLUGIN_NAME = get_package_name()

SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Settings.tmLanguage"
                   % PLUGIN_NAME)
TPL = "{\n\t$0\n}"

class NewSettingsCommand(sublime_plugin.WindowCommand):
    def run(self):
        v = self.window.new_file()
        v.settings().set('default_dir', root_at_packages('User'))
        v.set_syntax_file(SETTINGS_SYNTAX)
        v.run_command('insert_snippet', {'contents': TPL})


from datastreams import DataStream, DataSet

class DictStream(DataStream):

    @staticmethod
    def Stream(iterable,
               transform=lambda row: row,
               predicate=lambda row: True):
        return DictStream(iterable, transform=transform, predicate=predicate)

    @staticmethod
    def Set(iterable):
        return DictSet(iterable)

    @staticmethod
    def getattr(row, name):
        return row.get(name)

    @staticmethod
    def hasattr(row, name):
        return name in row

    @staticmethod
    def setattr(row, name, value):
        row[name] = value

    def delete(self, key):
        transform = lambda row: dict((k, v) for k, v in row.items() if k != key)
        return self.Stream(self, transform=transform)

    @staticmethod
    def join_objects(left, right):
        joined = {}
        joined.update(right.items())
        joined.update(left.items())
        joined['left'] = left
        joined['right'] = right
        return joined

class DictSet(DictStream, DataSet):
    pass  # TODO implement dict inner/outer joins

Response:
<INSERT> joined.update(right.items())
        <INSERT_END> <DELETE>        joined.update(right.items())
 <DELETE_END> <|endoftext|> from datastreams import DataStream, DataSet

class DictStream(DataStream):

    @staticmethod
    def Stream(iterable,
               transform=lambda row: row,
               predicate=lambda row: True):
        return DictStream(iterable, transform=transform, predicate=predicate)

    @staticmethod
    def Set(iterable):
        return DictSet(iterable)

    @staticmethod
    def getattr(row, name):
        return row.get(name)

    @staticmethod
    def hasattr(row, name):
        return name in row

    @staticmethod
    def setattr(row, name, value):
        row[name] = value

    def delete(self, key):
        transform = lambda row: dict((k, v) for k, v in row.items() if k != key)
        return self.Stream(self, transform=transform)

    @staticmethod
    def join_objects(left, right):
        joined = {}
        joined.update(right.items())
        joined.update(left.items())
        joined['left'] = left
        joined['right'] = right
        return joined

class DictSet(DictStream, DataSet):
    pass  # TODO implement dict inner/outer joins

Prompt:
Fix DictStream join precedence (right was overriding left improperly)

from datastreams import DataStream, DataSet

class DictStream(DataStream):

    @staticmethod
    def Stream(iterable,
               transform=lambda row: row,
               predicate=lambda row: True):
        return DictStream(iterable, transform=transform, predicate=predicate)

    @staticmethod
    def Set(iterable):
        return DictSet(iterable)

    @staticmethod
    def getattr(row, name):
        return row.get(name)

    @staticmethod
    def hasattr(row, name):
        return name in row

    @staticmethod
    def setattr(row, name, value):
        row[name] = value

    def delete(self, key):
        transform = lambda row: dict((k, v) for k, v in row.items() if k != key)
        return self.Stream(self, transform=transform)

    @staticmethod
    def join_objects(left, right):
        joined = {}
        joined.update(left.items())
        joined.update(right.items())
        joined['left'] = left
        joined['right'] = right
        return joined

class DictSet(DictStream, DataSet):
    pass  # TODO implement dict inner/outer joins


from django.conf import settings
from importlib import import_module

class InvalidTemplateFixture(Exception):
    pass

# holds all the fixtures
template_fixtures = {}

def get_template_fixtures():
    """
    Return the list of all available template fixtures.

    Caches the result for faster access.

    Code modified from django/template/base.py/get_templatetags_modules()
    """
    global template_fixtures
    if not template_fixtures:
        _template_fixtures = {}
        # Populate list once per process. Mutate the local list first, and
        # then assign it to the global name to ensure there are no cases where
        # two threads try to populate it simultaneously.
        for app_module in list(settings.INSTALLED_APPS):
            try:
                templatefixture_module = '%s.templatefixtures' % app_module
                mod = import_module(templatefixture_module)
                try:
                    fixtures = mod.fixtures
                    # TODO: validate fixtures structure
                    _template_fixtures.update(fixtures)
                except AttributeError:
                    raise InvalidTemplateFixture('Template fixture module %s '
                                                 'does not have a variable'
                                                 'named "fixtures"' %
                                                 templatefixture_module)
                except ValueError:
                    raise InvalidTemplateFixture('%s.fixture should be a '
                                                 'dictionary' %
                                                 templatefixture_module)
            except ImportError as e:
                #print app_module, e
                continue
        template_fixtures = _template_fixtures
    return template_fixtures

Response:
<REPLACE_OLD> django.utils.importlib <REPLACE_NEW> importlib <REPLACE_END> <|endoftext|> from django.conf import settings
from importlib import import_module

class InvalidTemplateFixture(Exception):
    pass

# holds all the fixtures
template_fixtures = {}

def get_template_fixtures():
    """
    Return the list of all available template fixtures.

    Caches the result for faster access.

    Code modified from django/template/base.py/get_templatetags_modules()
    """
    global template_fixtures
    if not template_fixtures:
        _template_fixtures = {}
        # Populate list once per process. Mutate the local list first, and
        # then assign it to the global name to ensure there are no cases where
        # two threads try to populate it simultaneously.
        for app_module in list(settings.INSTALLED_APPS):
            try:
                templatefixture_module = '%s.templatefixtures' % app_module
                mod = import_module(templatefixture_module)
                try:
                    fixtures = mod.fixtures
                    # TODO: validate fixtures structure
                    _template_fixtures.update(fixtures)
                except AttributeError:
                    raise InvalidTemplateFixture('Template fixture module %s '
                                                 'does not have a variable'
                                                 'named "fixtures"' %
                                                 templatefixture_module)
                except ValueError:
                    raise InvalidTemplateFixture('%s.fixture should be a '
                                                 'dictionary' %
                                                 templatefixture_module)
            except ImportError as e:
                #print app_module, e
                continue
        template_fixtures = _template_fixtures
    return template_fixtures

Prompt:
Use Python importlib instead of sjango.utils.importlib

from django.conf import settings
from django.utils.importlib import import_module

class InvalidTemplateFixture(Exception):
    pass

# holds all the fixtures
template_fixtures = {}

def get_template_fixtures():
    """
    Return the list of all available template fixtures.

    Caches the result for faster access.

    Code modified from django/template/base.py/get_templatetags_modules()
    """
    global template_fixtures
    if not template_fixtures:
        _template_fixtures = {}
        # Populate list once per process. Mutate the local list first, and
        # then assign it to the global name to ensure there are no cases where
        # two threads try to populate it simultaneously.
        for app_module in list(settings.INSTALLED_APPS):
            try:
                templatefixture_module = '%s.templatefixtures' % app_module
                mod = import_module(templatefixture_module)
                try:
                    fixtures = mod.fixtures
                    # TODO: validate fixtures structure
                    _template_fixtures.update(fixtures)
                except AttributeError:
                    raise InvalidTemplateFixture('Template fixture module %s '
                                                 'does not have a variable'
                                                 'named "fixtures"' %
                                                 templatefixture_module)
                except ValueError:
                    raise InvalidTemplateFixture('%s.fixture should be a '
                                                 'dictionary' %
                                                 templatefixture_module)
            except ImportError as e:
                #print app_module, e
                continue
        template_fixtures = _template_fixtures
    return template_fixtures


# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger

class GrpcExceptionWrapper(object):
    def __init__(self, response_type, state_code=StatusCode.UNKNOWN):
        self.response_type = response_type
        self.state_code = state_code

    def _set_context(self, context, exception):
        if context is not None:
            context.set_code(self.state_code)
            context.set_details(str(exception))

    def __call__(self, f):
        def wrap_f(caller_self, request, context):
            try:
                return f(caller_self, request, context)
            except ValueError as e:
                context.set_code(StatusCode.INVALID_ARGUMENT)
                self._set_context(context, e)
                logger.info(str(e))
                return self.response_type()
            except Exception as e:
                self._set_context(context, e)
                logger.exception(e)
                return self.response_type()

        return wrap_f

Response:
<INSERT> context.set_code(StatusCode.INVALID_ARGUMENT)
                <INSERT_END> <|endoftext|> # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger

class GrpcExceptionWrapper(object):
    def __init__(self, response_type, state_code=StatusCode.UNKNOWN):
        self.response_type = response_type
        self.state_code = state_code

    def _set_context(self, context, exception):
        if context is not None:
            context.set_code(self.state_code)
            context.set_details(str(exception))

    def __call__(self, f):
        def wrap_f(caller_self, request, context):
            try:
                return f(caller_self, request, context)
            except ValueError as e:
                context.set_code(StatusCode.INVALID_ARGUMENT)
                self._set_context(context, e)
                logger.info(str(e))
                return self.response_type()
            except Exception as e:
                self._set_context(context, e)
                logger.exception(e)
                return self.response_type()

        return wrap_f

Prompt:
Set code to Invalid argument for ValueErrors

# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger

class GrpcExceptionWrapper(object):
    def __init__(self, response_type, state_code=StatusCode.UNKNOWN):
        self.response_type = response_type
        self.state_code = state_code

    def _set_context(self, context, exception):
        if context is not None:
            context.set_code(self.state_code)
            context.set_details(str(exception))

    def __call__(self, f):
        def wrap_f(caller_self, request, context):
            try:
                return f(caller_self, request, context)
            except ValueError as e:
                self._set_context(context, e)
                logger.info(str(e))
                return self.response_type()
            except Exception as e:
                self._set_context(context, e)
                logger.exception(e)
                return self.response_type()

        return wrap_f


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

from setuptools import setup

try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    name="pybossa-pbs",
    version="1.0",
    author="Daniel Lombraña González",
    author_email="info@pybossa.com",
    description="PyBossa command line client",
    long_description=read_md('README.md'),
    license="AGPLv3",
    url="https://github.com/PyBossa/pbs",
    classifiers = ['Development Status :: 4 - Beta',
                   'Environment :: Console',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
                   'Operating System :: OS Independent',
                   'Programming Language :: Python',],
    py_modules=['pbs'],
    install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage',
                      'rednose', 'pypandoc'],
    entry_points='''
        [console_scripts]
        pbs=pbs:cli
    '''
)

Response:
<REPLACE_OLD> setup

setup(
    name="pbs",
 <REPLACE_NEW> setup

try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    name="pybossa-pbs",
 <REPLACE_END> <INSERT> long_description=read_md('README.md'),
    <INSERT_END> <REPLACE_OLD> 0 <REPLACE_NEW> 4 <REPLACE_END> <REPLACE_OLD> Production',
 <REPLACE_NEW> Beta',
 <REPLACE_END> <REPLACE_OLD> Consle',
 <REPLACE_NEW> Console',
 <REPLACE_END> <REPLACE_OLD> Affer v3',
 <REPLACE_NEW> Affero General Public License v3 or later (AGPLv3+)',
 <REPLACE_END> <REPLACE_OLD> 'rednose'],
 <REPLACE_NEW> 'rednose', 'pypandoc'],
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    name="pybossa-pbs",
    version="1.0",
    author="Daniel Lombraña González",
    author_email="info@pybossa.com",
    description="PyBossa command line client",
    long_description=read_md('README.md'),
    license="AGPLv3",
    url="https://github.com/PyBossa/pbs",
    classifiers = ['Development Status :: 4 - Beta',
                   'Environment :: Console',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
                   'Operating System :: OS Independent',
                   'Programming Language :: Python',],
    py_modules=['pbs'],
    install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage',
                      'rednose', 'pypandoc'],
    entry_points='''
        [console_scripts]
        pbs=pbs:cli
    '''
)

Prompt:
Use pandoc to convert from Markdown to RST for pypi

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

from setuptools import setup

setup(
    name="pbs",
    version="1.0",
    author="Daniel Lombraña González",
    author_email="info@pybossa.com",
    description="PyBossa command line client",
    license="AGPLv3",
    url="https://github.com/PyBossa/pbs",
    classifiers = ['Development Status :: 0 - Production',
                   'Environment :: Consle',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: GNU Affer v3',
                   'Operating System :: OS Independent',
                   'Programming Language :: Python',],
    py_modules=['pbs'],
    install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage',
                      'rednose'],
    entry_points='''
        [console_scripts]
        pbs=pbs:cli
    '''
)


from mock import patch
from unittest import TestCase

from crossbuild import (
    main,
)

class CrossBuildTestCase(TestCase):

    def test_main_setup(self):
        with patch('crossbuild.setup_cross_building') as mock:
            main(['-d', '-v', 'setup', '--build-dir', './foo'])
        args, kwargs = mock.call_args
        self.assertEqual(('./foo', ), args)
        self.assertEqual({'dry_run': True, 'verbose': True}, kwargs)

    def test_main_osx_clientt(self):
        with patch('crossbuild.build_osx_client') as mock:
            main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

    def test_main_win_client(self):
        with patch('crossbuild.build_win_client') as mock:
            main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

    def test_main_win_agent(self):
        with patch('crossbuild.build_win_agent') as mock:
            main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

Add main osx-client command test.

Add main osx-client command test.

Response:
<REPLACE_OLD> test_main_win_client(self):
        with patch('crossbuild.build_win_client') as mock:
            main(['win-client', <REPLACE_NEW> test_main_osx_clientt(self):
        with patch('crossbuild.build_osx_client') as mock:
            main(['osx-client', <REPLACE_END> <INSERT> kwargs)

    def test_main_win_client(self):
        with patch('crossbuild.build_win_client') as mock:
            main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

    def test_main_win_agent(self):
        with patch('crossbuild.build_win_agent') as mock:
            main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, <INSERT_END> <|endoftext|> from mock import patch
from unittest import TestCase

from crossbuild import (
    main,
)

class CrossBuildTestCase(TestCase):

    def test_main_setup(self):
        with patch('crossbuild.setup_cross_building') as mock:
            main(['-d', '-v', 'setup', '--build-dir', './foo'])
        args, kwargs = mock.call_args
        self.assertEqual(('./foo', ), args)
        self.assertEqual({'dry_run': True, 'verbose': True}, kwargs)

    def test_main_osx_clientt(self):
        with patch('crossbuild.build_osx_client') as mock:
            main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

    def test_main_win_client(self):
        with patch('crossbuild.build_win_client') as mock:
            main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

    def test_main_win_agent(self):
        with patch('crossbuild.build_win_agent') as mock:
            main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)

Prompt:
Add main osx-client command test.
from mock import patch
from unittest import TestCase

from crossbuild import (
    main,
)

class CrossBuildTestCase(TestCase):

    def test_main_setup(self):
        with patch('crossbuild.setup_cross_building') as mock:
            main(['-d', '-v', 'setup', '--build-dir', './foo'])
        args, kwargs = mock.call_args
        self.assertEqual(('./foo', ), args)
        self.assertEqual({'dry_run': True, 'verbose': True}, kwargs)

    def test_main_win_client(self):
        with patch('crossbuild.build_win_client') as mock:
            main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz'])
        args, kwargs = mock.call_args
        self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args)
        self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)


from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase

#todo: merge into test_series

def age_series(**kwargs):
    from flexget.plugins.filter.series import Release
    from flexget.manager import Session
    import datetime
    session = Session()
    session.query(Release).update({'first_seen': datetime.datetime.now() - datetime.timedelta(**kwargs)})
    session.commit()

class TestImportSeries(FlexGetBase):

    __yaml__ = """
        tasks:
          test_import_altnames:
            configure_series:
              from:
                mock:
                  - {title: 'the show', alternate_name: 'le show'}
            mock:
              - title: le show s03e03
    """

    def test_timeframe_max(self):
        """Tests configure_series as well as timeframe with max_quality."""
        self.execute_task('test_import_altnames')
        entry = self.task.find_entry(title='le show s03e03')
        assert entry.accepted, 'entry matching series alternate name should have been accepted.'
        assert entry['series_name'] == 'the show', 'entry series should be set to the main name'

Test for series configure loading alternate name

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase

#todo: merge into test_series

def age_series(**kwargs):
    from flexget.plugins.filter.series import Release
    from flexget.manager import Session
    import datetime
    session = Session()
    session.query(Release).update({'first_seen': datetime.datetime.now() - datetime.timedelta(**kwargs)})
    session.commit()

class TestImportSeries(FlexGetBase):

    __yaml__ = """
        tasks:
          test_import_altnames:
            configure_series:
              from:
                mock:
                  - {title: 'the show', alternate_name: 'le show'}
            mock:
              - title: le show s03e03
    """

    def test_timeframe_max(self):
        """Tests configure_series as well as timeframe with max_quality."""
        self.execute_task('test_import_altnames')
        entry = self.task.find_entry(title='le show s03e03')
        assert entry.accepted, 'entry matching series alternate name should have been accepted.'
        assert entry['series_name'] == 'the show', 'entry series should be set to the main name'
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase

#todo: merge into test_series

def age_series(**kwargs):
    from flexget.plugins.filter.series import Release
    from flexget.manager import Session
    import datetime
    session = Session()
    session.query(Release).update({'first_seen': datetime.datetime.now() - datetime.timedelta(**kwargs)})
    session.commit()

class TestImportSeries(FlexGetBase):

    __yaml__ = """
        tasks:
          test_import_altnames:
            configure_series:
              from:
                mock:
                  - {title: 'the show', alternate_name: 'le show'}
            mock:
              - title: le show s03e03
    """

    def test_timeframe_max(self):
        """Tests configure_series as well as timeframe with max_quality."""
        self.execute_task('test_import_altnames')
        entry = self.task.find_entry(title='le show s03e03')
        assert entry.accepted, 'entry matching series alternate name should have been accepted.'
        assert entry['series_name'] == 'the show', 'entry series should be set to the main name'

Prompt: Test for series configure loading alternate name


#!/usr/bin/env python

from bioc import BioCReader
from bioc import BioCWriter

test_file = '../test_input/bcIVLearningCorpus.xml'
dtd_file = '../test_input/BioC.dtd'

def main():
    bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file)
    bioc_reader.read()
    '''
    sentences = bioc_reader.collection.documents[0].passages[0].sentences
    for sentence in sentences:
        print sentence.offset
    '''

    bioc_writer = BioCWriter('output_bioc.xml')
    bioc_writer.collection = bioc_reader.collection
    bioc_writer.write()
    print(bioc_writer)

if  __name__ == '__main__':
    main()

Add BioC.dtd one level up

Add BioC.dtd one level up

Response:
<REPLACE_OLD> '../test_input/PMID-8557975-simplified-sentences.xml'
dtd_file <REPLACE_NEW> '../test_input/bcIVLearningCorpus.xml'
dtd_file <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from bioc import BioCReader
from bioc import BioCWriter

test_file = '../test_input/bcIVLearningCorpus.xml'
dtd_file = '../test_input/BioC.dtd'

def main():
    bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file)
    bioc_reader.read()
    '''
    sentences = bioc_reader.collection.documents[0].passages[0].sentences
    for sentence in sentences:
        print sentence.offset
    '''

    bioc_writer = BioCWriter('output_bioc.xml')
    bioc_writer.collection = bioc_reader.collection
    bioc_writer.write()
    print(bioc_writer)

if  __name__ == '__main__':
    main()

Prompt:
Add BioC.dtd one level up

#!/usr/bin/env python

from bioc import BioCReader
from bioc import BioCWriter

test_file = '../test_input/PMID-8557975-simplified-sentences.xml'
dtd_file = '../test_input/BioC.dtd'

def main():
    bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file)
    bioc_reader.read()
    '''
    sentences = bioc_reader.collection.documents[0].passages[0].sentences
    for sentence in sentences:
        print sentence.offset
    '''

    bioc_writer = BioCWriter('output_bioc.xml')
    bioc_writer.collection = bioc_reader.collection
    bioc_writer.write()
    print(bioc_writer)

if  __name__ == '__main__':
    main()


#!/usr/bin/env python
from setuptools import setup, find_packages

__version__ = '0.50.1'

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(name='lcapy',
      version=__version__,
      author='Michael Hayes',
      author_email='michael.hayes@canterbury.ac.nz',
      description='Symbolic linear circuit analysis',
      long_description = long_description,
      long_description_content_type="text/markdown",
      url='https://github.com/mph-/lcapy',
      download_url='https://github.com/mph-/lcapy',
      install_requires=['matplotlib',
                        'scipy',
                        'numpy',
                        'sympy',
                        'networkx',
                        'setuptools',
                        'wheel'
      ],
      packages=find_packages(exclude=['demo']),
      entry_points={
          'console_scripts': [
              'schtex=lcapy.scripts.schtex:main',
          ],
      },
      classifiers=[
          "Programming Language :: Python :: 3",
          "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)",
          "Operating System :: OS Independent",
      ],
)

Add wheel as a requirement

Add wheel as a requirement

Response:
<REPLACE_OLD> 'setuptools'
 <REPLACE_NEW> 'setuptools',
                        'wheel'
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from setuptools import setup, find_packages

__version__ = '0.50.1'

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(name='lcapy',
      version=__version__,
      author='Michael Hayes',
      author_email='michael.hayes@canterbury.ac.nz',
      description='Symbolic linear circuit analysis',
      long_description = long_description,
      long_description_content_type="text/markdown",
      url='https://github.com/mph-/lcapy',
      download_url='https://github.com/mph-/lcapy',
      install_requires=['matplotlib',
                        'scipy',
                        'numpy',
                        'sympy',
                        'networkx',
                        'setuptools',
                        'wheel'
      ],
      packages=find_packages(exclude=['demo']),
      entry_points={
          'console_scripts': [
              'schtex=lcapy.scripts.schtex:main',
          ],
      },
      classifiers=[
          "Programming Language :: Python :: 3",
          "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)",
          "Operating System :: OS Independent",
      ],
)

Prompt:
Add wheel as a requirement

#!/usr/bin/env python
from setuptools import setup, find_packages

__version__ = '0.50.1'

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(name='lcapy',
      version=__version__,
      author='Michael Hayes',
      author_email='michael.hayes@canterbury.ac.nz',
      description='Symbolic linear circuit analysis',
      long_description = long_description,
      long_description_content_type="text/markdown",
      url='https://github.com/mph-/lcapy',
      download_url='https://github.com/mph-/lcapy',
      install_requires=['matplotlib',
                        'scipy',
                        'numpy',
                        'sympy',
                        'networkx',
                        'setuptools'
      ],
      packages=find_packages(exclude=['demo']),
      entry_points={
          'console_scripts': [
              'schtex=lcapy.scripts.schtex:main',
          ],
      },
      classifiers=[
          "Programming Language :: Python :: 3",
          "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)",
          "Operating System :: OS Independent",
      ],
)


# coding: utf-8
import random
import gym
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns  # noqa
env = gym.make('FrozenLake-v0')

class Agent(object):

    def __init__(self, action_space, eps=0.01, alpha=0.1, gamma=0.9):
        self.action_space = action_space
        self.eps = eps
        self.alpha = alpha
        self.gamma = gamma
        self.q_table = {}

    def q_function(self, obs, act):
        key = (obs, act)
        if key not in self.q_table:
            self.q_table[key] = 100
        return self.q_table[key]

    def get_action_list(self):
        return range(self.action_space.n)

    def _get_best_action(self, obs):
        best = (-1e9, None)
        for act in self.get_action_list():
            score = self.q_function(obs, act)
            if best[0] < score:
                best = (score, act)
        return best[1]

    def action(self, obs):
        if random.random() < self.eps:
            return self.action_space.sample()
        return self._get_best_action(obs)

    def update(self, obs, act, reward, next_obs):
        next_act = self._get_best_action(next_obs)
        q = 0
        q += (1.0 - self.alpha) * self.q_function(obs, act)
        q += self.alpha * (
            reward + self.gamma * self.q_function(next_obs, next_act))
        self.q_table[(obs, act)] = q

def run_episode(agent):
    obs = env.reset()
    cnt = 0
    while True:
        cnt += 1
        action = agent.action(obs)
        next_obs, reward, done, info = env.step(action)
        if done:
            break
        agent.update(obs, action, reward, next_obs)
        obs = next_obs
    return cnt

trial = 50
n_episode = 2000
result = []
for i in range(trial):
    print('trial %i start.' % (i))
    agent = Agent(env.action_space)
    for j in range(n_episode):
        cnt = run_episode(agent)
        result.append([j, cnt])

df = pd.DataFrame(result, columns=['episode', 'n_move'])
df.plot.scatter(x='episode', y='n_move')
plt.savefig('result.png')

Add an agent of q-learning

Add an agent of q-learning

Response:
<REPLACE_OLD>  <REPLACE_NEW> # coding: utf-8
import random
import gym
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns  # noqa
env = gym.make('FrozenLake-v0')

class Agent(object):

    def __init__(self, action_space, eps=0.01, alpha=0.1, gamma=0.9):
        self.action_space = action_space
        self.eps = eps
        self.alpha = alpha
        self.gamma = gamma
        self.q_table = {}

    def q_function(self, obs, act):
        key = (obs, act)
        if key not in self.q_table:
            self.q_table[key] = 100
        return self.q_table[key]

    def get_action_list(self):
        return range(self.action_space.n)

    def _get_best_action(self, obs):
        best = (-1e9, None)
        for act in self.get_action_list():
            score = self.q_function(obs, act)
            if best[0] < score:
                best = (score, act)
        return best[1]

    def action(self, obs):
        if random.random() < self.eps:
            return self.action_space.sample()
        return self._get_best_action(obs)

    def update(self, obs, act, reward, next_obs):
        next_act = self._get_best_action(next_obs)
        q = 0
        q += (1.0 - self.alpha) * self.q_function(obs, act)
        q += self.alpha * (
            reward + self.gamma * self.q_function(next_obs, next_act))
        self.q_table[(obs, act)] = q

def run_episode(agent):
    obs = env.reset()
    cnt = 0
    while True:
        cnt += 1
        action = agent.action(obs)
        next_obs, reward, done, info = env.step(action)
        if done:
            break
        agent.update(obs, action, reward, next_obs)
        obs = next_obs
    return cnt

trial = 50
n_episode = 2000
result = []
for i in range(trial):
    print('trial %i start.' % (i))
    agent = Agent(env.action_space)
    for j in range(n_episode):
        cnt = run_episode(agent)
        result.append([j, cnt])

df = pd.DataFrame(result, columns=['episode', 'n_move'])
df.plot.scatter(x='episode', y='n_move')
plt.savefig('result.png')
 <REPLACE_END> <|endoftext|> # coding: utf-8
import random
import gym
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns  # noqa
env = gym.make('FrozenLake-v0')

class Agent(object):

    def __init__(self, action_space, eps=0.01, alpha=0.1, gamma=0.9):
        self.action_space = action_space
        self.eps = eps
        self.alpha = alpha
        self.gamma = gamma
        self.q_table = {}

    def q_function(self, obs, act):
        key = (obs, act)
        if key not in self.q_table:
            self.q_table[key] = 100
        return self.q_table[key]

    def get_action_list(self):
        return range(self.action_space.n)

    def _get_best_action(self, obs):
        best = (-1e9, None)
        for act in self.get_action_list():
            score = self.q_function(obs, act)
            if best[0] < score:
                best = (score, act)
        return best[1]

    def action(self, obs):
        if random.random() < self.eps:
            return self.action_space.sample()
        return self._get_best_action(obs)

    def update(self, obs, act, reward, next_obs):
        next_act = self._get_best_action(next_obs)
        q = 0
        q += (1.0 - self.alpha) * self.q_function(obs, act)
        q += self.alpha * (
            reward + self.gamma * self.q_function(next_obs, next_act))
        self.q_table[(obs, act)] = q

def run_episode(agent):
    obs = env.reset()
    cnt = 0
    while True:
        cnt += 1
        action = agent.action(obs)
        next_obs, reward, done, info = env.step(action)
        if done:
            break
        agent.update(obs, action, reward, next_obs)
        obs = next_obs
    return cnt

trial = 50
n_episode = 2000
result = []
for i in range(trial):
    print('trial %i start.' % (i))
    agent = Agent(env.action_space)
    for j in range(n_episode):
        cnt = run_episode(agent)
        result.append([j, cnt])

df = pd.DataFrame(result, columns=['episode', 'n_move'])
df.plot.scatter(x='episode', y='n_move')
plt.savefig('result.png')

Prompt: Add an agent of q-learning


from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase

from crm.tests.model_maker import (
    make_contact,
    make_user_contact,
)
from login.tests.model_maker import make_user

class TestContactUser(TestCase):

    def test_link_user_to_contact(self):
        """Create a contact and link it to a user"""
        contact = make_contact(
            'pkimber',
            'Patrick Kimber',
        )
        make_user_contact(make_user('fred'), contact)
        user = User.objects.get(username='fred')
        user_contacts = user.usercontact_set.all()
        self.assertIn('Kimber', user_contacts[0].contact.name)

    def test_one_contact_per_user(self):
        """Make sure a user can only link to one contact"""
        fred = make_user('fred')
        jsmith = make_contact('jsmith', 'John Smith')
        pkimber = make_contact('pkimber', 'Patrick Kimber')
        make_user_contact(fred, pkimber)
        self.assertRaises(
            IntegrityError,
            make_user_contact,
            fred,
            jsmith,
        )

Response:
<INSERT> django.db import IntegrityError
from <INSERT_END> <REPLACE_OLD> user_contacts[0].contact.name)
 <REPLACE_NEW> user_contacts[0].contact.name)

    def test_one_contact_per_user(self):
        """Make sure a user can only link to one contact"""
        fred = make_user('fred')
        jsmith = make_contact('jsmith', 'John Smith')
        pkimber = make_contact('pkimber', 'Patrick Kimber')
        make_user_contact(fred, pkimber)
        self.assertRaises(
            IntegrityError,
            make_user_contact,
            fred,
            jsmith,
        )
 <REPLACE_END> <|endoftext|> from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase

from crm.tests.model_maker import (
    make_contact,
    make_user_contact,
)
from login.tests.model_maker import make_user

class TestContactUser(TestCase):

    def test_link_user_to_contact(self):
        """Create a contact and link it to a user"""
        contact = make_contact(
            'pkimber',
            'Patrick Kimber',
        )
        make_user_contact(make_user('fred'), contact)
        user = User.objects.get(username='fred')
        user_contacts = user.usercontact_set.all()
        self.assertIn('Kimber', user_contacts[0].contact.name)

    def test_one_contact_per_user(self):
        """Make sure a user can only link to one contact"""
        fred = make_user('fred')
        jsmith = make_contact('jsmith', 'John Smith')
        pkimber = make_contact('pkimber', 'Patrick Kimber')
        make_user_contact(fred, pkimber)
        self.assertRaises(
            IntegrityError,
            make_user_contact,
            fred,
            jsmith,
        )

Prompt:
Make sure a user can only link to one contact

from django.contrib.auth.models import User
from django.test import TestCase

from crm.tests.model_maker import (
    make_contact,
    make_user_contact,
)
from login.tests.model_maker import make_user

class TestContactUser(TestCase):

    def test_link_user_to_contact(self):
        """Create a contact and link it to a user"""
        contact = make_contact(
            'pkimber',
            'Patrick Kimber',
        )
        make_user_contact(make_user('fred'), contact)
        user = User.objects.get(username='fred')
        user_contacts = user.usercontact_set.all()
        self.assertIn('Kimber', user_contacts[0].contact.name)


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

from locations.items import GeojsonPointItem

class TheLearningExperienceSpider(scrapy.Spider):
    name = "learning_experience"
    allowed_domains = ["thelearningexperience.com"]
    start_urls = (
        'https://thelearningexperience.com/our-centers/directory',
    )

    def parse(self, response):
        for loc_path in response.xpath('//a[@itemprop="url"]/@href'):
            yield scrapy.Request(
                response.urljoin(loc_path.extract()),
                callback=self.parse_location,
            )

    def parse_location(self, response):
        properties = {
            'name': response.xpath('//h1[@class="lp-yellow-text"]/text()').extract_first(),
            'addr:full': response.xpath('//span[@itemprop="streetAddress"]/text()').extract_first(),
            'addr:city': response.xpath('//span[@itemprop="addressLocality"]/text()').extract_first(),
            'addr:state': response.xpath('//span[@itemprop="addressRegion"]/text()').extract_first(),
            'addr:postcode': response.xpath('//span[@itemprop="postalCode"]/text()').extract_first(),
            'phone': response.xpath('//a[@itemprop="telephone"]/text()').extract_first(),
            'opening_hours': response.xpath('//tr[@itemprop="openingHours"]/@datetime').extract_first(),
            'ref': response.request.url,
            'website': response.request.url,
        }

        lon_lat = [
            float(response.xpath('//meta[@name="place:location:longitude"]/@content').extract_first()),
            float(response.xpath('//meta[@name="place:location:latitude"]/@content').extract_first()),
        ]

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

Add The Learning Experience spider

Add The Learning Experience spider

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

from locations.items import GeojsonPointItem

class TheLearningExperienceSpider(scrapy.Spider):
    name = "learning_experience"
    allowed_domains = ["thelearningexperience.com"]
    start_urls = (
        'https://thelearningexperience.com/our-centers/directory',
    )

    def parse(self, response):
        for loc_path in response.xpath('//a[@itemprop="url"]/@href'):
            yield scrapy.Request(
                response.urljoin(loc_path.extract()),
                callback=self.parse_location,
            )

    def parse_location(self, response):
        properties = {
            'name': response.xpath('//h1[@class="lp-yellow-text"]/text()').extract_first(),
            'addr:full': response.xpath('//span[@itemprop="streetAddress"]/text()').extract_first(),
            'addr:city': response.xpath('//span[@itemprop="addressLocality"]/text()').extract_first(),
            'addr:state': response.xpath('//span[@itemprop="addressRegion"]/text()').extract_first(),
            'addr:postcode': response.xpath('//span[@itemprop="postalCode"]/text()').extract_first(),
            'phone': response.xpath('//a[@itemprop="telephone"]/text()').extract_first(),
            'opening_hours': response.xpath('//tr[@itemprop="openingHours"]/@datetime').extract_first(),
            'ref': response.request.url,
            'website': response.request.url,
        }

        lon_lat = [
            float(response.xpath('//meta[@name="place:location:longitude"]/@content').extract_first()),
            float(response.xpath('//meta[@name="place:location:latitude"]/@content').extract_first()),
        ]

        yield GeojsonPointItem(
            properties=properties,
            lon_lat=lon_lat,
        )
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import scrapy
import re

from locations.items import GeojsonPointItem

class TheLearningExperienceSpider(scrapy.Spider):
    name = "learning_experience"
    allowed_domains = ["thelearningexperience.com"]
    start_urls = (
        'https://thelearningexperience.com/our-centers/directory',
    )

    def parse(self, response):
        for loc_path in response.xpath('//a[@itemprop="url"]/@href'):
            yield scrapy.Request(
                response.urljoin(loc_path.extract()),
                callback=self.parse_location,
            )

    def parse_location(self, response):
        properties = {
            'name': response.xpath('//h1[@class="lp-yellow-text"]/text()').extract_first(),
            'addr:full': response.xpath('//span[@itemprop="streetAddress"]/text()').extract_first(),
            'addr:city': response.xpath('//span[@itemprop="addressLocality"]/text()').extract_first(),
            'addr:state': response.xpath('//span[@itemprop="addressRegion"]/text()').extract_first(),
            'addr:postcode': response.xpath('//span[@itemprop="postalCode"]/text()').extract_first(),
            'phone': response.xpath('//a[@itemprop="telephone"]/text()').extract_first(),
            'opening_hours': response.xpath('//tr[@itemprop="openingHours"]/@datetime').extract_first(),
            'ref': response.request.url,
            'website': response.request.url,
        }

        lon_lat = [
            float(response.xpath('//meta[@name="place:location:longitude"]/@content').extract_first()),
            float(response.xpath('//meta[@name="place:location:latitude"]/@content').extract_first()),
        ]

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

Prompt: Add The Learning Experience spider


#!/usr/bin/env python3
from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse

def restet_relational_db():

    print('Removing relational database...')
    db.reflect()
    db.drop_all()
    print('Removing relational database completed.')

    print('Recreating relational database...')
    db.create_all()
    print('Recreating relational database completed.')

def reset_mappings_db():
    print('Removing mappigns database...')
    bdb.reset()
    bdb_refseq.reset()
    print('Removing mapings database completed.')

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-i',
        '--import_mappings',
        action='store_true',
        help='Should mappings be (re)imported'
    )
    parser.add_argument(
        '-r',
        '--reload_relational',
        action='store_true',
        help='Should relational database be (re)imported'
    )

    args = parser.parse_args()

    if args.import_mappings:
        reset_mappings_db()

    if args.reload_relational:
        restet_relational_db()

    if args.reload_relational or args.import_mappings:
        print('Importing data')
        import_data(
            import_mappings=args.import_mappings,
            reload_relational=args.reload_relational
        )
        print('Importing completed')

    print('Done, all tasks completed.')

else:
    print('This script should be run from command line')

Use store true in db creation script

Use store true in db creation script

Response:
<REPLACE_OLD> default=False,
 <REPLACE_NEW> action='store_true',
 <REPLACE_END> <REPLACE_OLD> default=False,
 <REPLACE_NEW> action='store_true',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse

def restet_relational_db():

    print('Removing relational database...')
    db.reflect()
    db.drop_all()
    print('Removing relational database completed.')

    print('Recreating relational database...')
    db.create_all()
    print('Recreating relational database completed.')

def reset_mappings_db():
    print('Removing mappigns database...')
    bdb.reset()
    bdb_refseq.reset()
    print('Removing mapings database completed.')

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-i',
        '--import_mappings',
        action='store_true',
        help='Should mappings be (re)imported'
    )
    parser.add_argument(
        '-r',
        '--reload_relational',
        action='store_true',
        help='Should relational database be (re)imported'
    )

    args = parser.parse_args()

    if args.import_mappings:
        reset_mappings_db()

    if args.reload_relational:
        restet_relational_db()

    if args.reload_relational or args.import_mappings:
        print('Importing data')
        import_data(
            import_mappings=args.import_mappings,
            reload_relational=args.reload_relational
        )
        print('Importing completed')

    print('Done, all tasks completed.')

else:
    print('This script should be run from command line')

Prompt:
Use store true in db creation script

#!/usr/bin/env python3
from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse

def restet_relational_db():

    print('Removing relational database...')
    db.reflect()
    db.drop_all()
    print('Removing relational database completed.')

    print('Recreating relational database...')
    db.create_all()
    print('Recreating relational database completed.')

def reset_mappings_db():
    print('Removing mappigns database...')
    bdb.reset()
    bdb_refseq.reset()
    print('Removing mapings database completed.')

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-i',
        '--import_mappings',
        default=False,
        help='Should mappings be (re)imported'
    )
    parser.add_argument(
        '-r',
        '--reload_relational',
        default=False,
        help='Should relational database be (re)imported'
    )

    args = parser.parse_args()

    if args.import_mappings:
        reset_mappings_db()

    if args.reload_relational:
        restet_relational_db()

    if args.reload_relational or args.import_mappings:
        print('Importing data')
        import_data(
            import_mappings=args.import_mappings,
            reload_relational=args.reload_relational
        )
        print('Importing completed')

    print('Done, all tasks completed.')

else:
    print('This script should be run from command line')


from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    args = ''
    help = 'Write Liblouis tables from the confirmed words in the dictionary'

    def handle(self, *args, **options):
        # write new global white lists
        verbosity = int(options['verbosity'])
        if verbosity >= 2:
            self.stderr.write('Writing new global white lists...\n')
        writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
        # update local tables
        if verbosity >= 2:
            self.stderr.write('Updating local tables...\n')
        writeLocalTables(Document.objects.all())

Response:
<INSERT> verbosity = int(options['verbosity'])
        <INSERT_END> <REPLACE_OLD> options['verbosity'] <REPLACE_NEW> verbosity <REPLACE_END> <REPLACE_OLD> options['verbosity'] <REPLACE_NEW> verbosity <REPLACE_END> <|endoftext|> from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    args = ''
    help = 'Write Liblouis tables from the confirmed words in the dictionary'

    def handle(self, *args, **options):
        # write new global white lists
        verbosity = int(options['verbosity'])
        if verbosity >= 2:
            self.stderr.write('Writing new global white lists...\n')
        writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
        # update local tables
        if verbosity >= 2:
            self.stderr.write('Updating local tables...\n')
        writeLocalTables(Document.objects.all())

Prompt:
Make sure the verbosity stuff actually works

from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    args = ''
    help = 'Write Liblouis tables from the confirmed words in the dictionary'

    def handle(self, *args, **options):
        # write new global white lists
        if options['verbosity'] >= 2:
            self.stderr.write('Writing new global white lists...\n')
        writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
        # update local tables
        if options['verbosity'] >= 2:
            self.stderr.write('Updating local tables...\n')
        writeLocalTables(Document.objects.all())


# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

import pytest #This module contains automated tests.
import unittest.mock #For the mocking and monkeypatching functionality.

import cura.Settings.ExtruderStack #The module we're testing.
from cura.Settings.Exceptions import InvalidOperationError #To check whether the correct exceptions are raised.

##  An empty extruder stack to test with.
@pytest.fixture()
def extruder_stack() -> cura.Settings.ExtruderStack.ExtruderStack:
    return cura.Settings.ExtruderStack.ExtruderStack

#############################START OF TEST CASES################################

##  Tests whether adding a container is properly forbidden.
def test_addContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.addContainer(unittest.mock.MagicMock())

##  Tests whether inserting a container is properly forbidden.
def test_insertContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.insertContainer(0, unittest.mock.MagicMock())

##  Tests whether removing a container is properly forbidden.
def test_removeContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.removeContainer(unittest.mock.MagicMock())

Response:
<REPLACE_OLD> cura.Settings.ExtruderStack.ExtruderStack

## <REPLACE_NEW> cura.Settings.ExtruderStack.ExtruderStack

#############################START OF TEST CASES################################

## <REPLACE_END> <|endoftext|> # Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

import pytest #This module contains automated tests.
import unittest.mock #For the mocking and monkeypatching functionality.

import cura.Settings.ExtruderStack #The module we're testing.
from cura.Settings.Exceptions import InvalidOperationError #To check whether the correct exceptions are raised.

##  An empty extruder stack to test with.
@pytest.fixture()
def extruder_stack() -> cura.Settings.ExtruderStack.ExtruderStack:
    return cura.Settings.ExtruderStack.ExtruderStack

#############################START OF TEST CASES################################

##  Tests whether adding a container is properly forbidden.
def test_addContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.addContainer(unittest.mock.MagicMock())

##  Tests whether inserting a container is properly forbidden.
def test_insertContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.insertContainer(0, unittest.mock.MagicMock())

##  Tests whether removing a container is properly forbidden.
def test_removeContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.removeContainer(unittest.mock.MagicMock())

Prompt:
Add delimiter between global stuff and test cases

Helps provide some oversight since this module is about to explode in size.

Contributes to issue CURA-3497.

# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

import pytest #This module contains automated tests.
import unittest.mock #For the mocking and monkeypatching functionality.

import cura.Settings.ExtruderStack #The module we're testing.
from cura.Settings.Exceptions import InvalidOperationError #To check whether the correct exceptions are raised.

##  An empty extruder stack to test with.
@pytest.fixture()
def extruder_stack() -> cura.Settings.ExtruderStack.ExtruderStack:
    return cura.Settings.ExtruderStack.ExtruderStack

##  Tests whether adding a container is properly forbidden.
def test_addContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.addContainer(unittest.mock.MagicMock())

##  Tests whether inserting a container is properly forbidden.
def test_insertContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.insertContainer(0, unittest.mock.MagicMock())

##  Tests whether removing a container is properly forbidden.
def test_removeContainer(extruder_stack):
    with pytest.raises(InvalidOperationError):
        extruder_stack.removeContainer(unittest.mock.MagicMock())


#! /usr/bin/env python

import sys
from setuptools import setup

if 'upload' in sys.argv:
    if '--sign' not in sys.argv and sys.argv[1:] != ['upload', '--help']:
        raise SystemExit('Refusing to upload unsigned packages.')

PACKAGENAME = 'preconditions'

setup(
    name=PACKAGENAME,
    description='Flexible, concise preconditions.',
    url='https://github.com/nejucomo/{0}'.format(PACKAGENAME),
    license='MIT',
    version='0.1.dev0',
    author='Nathan Wilcox',
    author_email='nejucomo@gmail.com',
    py_modules=[PACKAGENAME],
    test_suite='tests',
    )

Response:
<REPLACE_OLD> python

from <REPLACE_NEW> python

import sys
from <REPLACE_END> <REPLACE_OLD> setup

PACKAGENAME <REPLACE_NEW> setup

if 'upload' in sys.argv:
    if '--sign' not in sys.argv and sys.argv[1:] != ['upload', '--help']:
        raise SystemExit('Refusing to upload unsigned packages.')

PACKAGENAME <REPLACE_END> <|endoftext|> #! /usr/bin/env python

import sys
from setuptools import setup

if 'upload' in sys.argv:
    if '--sign' not in sys.argv and sys.argv[1:] != ['upload', '--help']:
        raise SystemExit('Refusing to upload unsigned packages.')

PACKAGENAME = 'preconditions'

setup(
    name=PACKAGENAME,
    description='Flexible, concise preconditions.',
    url='https://github.com/nejucomo/{0}'.format(PACKAGENAME),
    license='MIT',
    version='0.1.dev0',
    author='Nathan Wilcox',
    author_email='nejucomo@gmail.com',
    py_modules=[PACKAGENAME],
    test_suite='tests',
    )

Prompt:
Add a "signature requirement" to the sdist upload command.

#! /usr/bin/env python

from setuptools import setup

PACKAGENAME = 'preconditions'

setup(
    name=PACKAGENAME,
    description='Flexible, concise preconditions.',
    url='https://github.com/nejucomo/{0}'.format(PACKAGENAME),
    license='MIT',
    version='0.1.dev0',
    author='Nathan Wilcox',
    author_email='nejucomo@gmail.com',
    py_modules=[PACKAGENAME],
    test_suite='tests',
    )


import npc
import pytest

@pytest.fixture(scope="module")
def character():
    char = npc.character.Character()
    char.tags('description').append('Fee fie foe fum')
    char.tags('type').append('human')
    return char

Set up defaults using tag syntax

Set up defaults using tag syntax

Response:
<REPLACE_OLD> char.append('description', 'Fee <REPLACE_NEW> char.tags('description').append('Fee <REPLACE_END> <REPLACE_OLD> char.append('type', 'human')
 <REPLACE_NEW> char.tags('type').append('human')
 <REPLACE_END> <|endoftext|> import npc
import pytest

@pytest.fixture(scope="module")
def character():
    char = npc.character.Character()
    char.tags('description').append('Fee fie foe fum')
    char.tags('type').append('human')
    return char

Prompt:
Set up defaults using tag syntax

import npc
import pytest

@pytest.fixture(scope="module")
def character():
    char = npc.character.Character()
    char.append('description', 'Fee fie foe fum')
    char.append('type', 'human')
    return char


import os, errno
# Create build folder if it doesn't exist

def get_path(relative_path):
	cur_dir = os.path.dirname(__file__)
	return os.path.join(cur_dir, relative_path)

try:
    os.makedirs(get_path('build'))
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

template = open(get_path('./5xx.template.html'), 'r')
templateString = template.read()
template.close()

# We only use 0-11 according to
# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_error
for i in range(12):
    numString = str(i) if i >= 10 else '0{}'.format(i)
    fileName = './build/5{}.html'.format(numString)
    outputFile = open(get_path(fileName), 'w')
    htmlString = templateString.replace('{ERROR_CODE_PLACEHOLDER}', '5{}'.format(numString))
    outputFile.write(htmlString)
    outputFile.close()

Response:
<REPLACE_OLD> exist
try:
 <REPLACE_NEW> exist

def get_path(relative_path):
	cur_dir = os.path.dirname(__file__)
	return os.path.join(cur_dir, relative_path)

try:
 <REPLACE_END> <REPLACE_OLD> os.makedirs('build')
except <REPLACE_NEW> os.makedirs(get_path('build'))
except <REPLACE_END> <REPLACE_OLD> open('./5xx.template.html', <REPLACE_NEW> open(get_path('./5xx.template.html'), <REPLACE_END> <REPLACE_OLD> open(fileName, <REPLACE_NEW> open(get_path(fileName), <REPLACE_END> <|endoftext|> import os, errno
# Create build folder if it doesn't exist

def get_path(relative_path):
	cur_dir = os.path.dirname(__file__)
	return os.path.join(cur_dir, relative_path)

try:
    os.makedirs(get_path('build'))
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

template = open(get_path('./5xx.template.html'), 'r')
templateString = template.read()
template.close()

# We only use 0-11 according to
# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_error
for i in range(12):
    numString = str(i) if i >= 10 else '0{}'.format(i)
    fileName = './build/5{}.html'.format(numString)
    outputFile = open(get_path(fileName), 'w')
    htmlString = templateString.replace('{ERROR_CODE_PLACEHOLDER}', '5{}'.format(numString))
    outputFile.write(htmlString)
    outputFile.close()

Prompt:
Make static http error code generator directory agnostic

import os, errno
# Create build folder if it doesn't exist
try:
    os.makedirs('build')
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

template = open('./5xx.template.html', 'r')
templateString = template.read()
template.close()

# We only use 0-11 according to
# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_error
for i in range(12):
    numString = str(i) if i >= 10 else '0{}'.format(i)
    fileName = './build/5{}.html'.format(numString)
    outputFile = open(fileName, 'w')
    htmlString = templateString.replace('{ERROR_CODE_PLACEHOLDER}', '5{}'.format(numString))
    outputFile.write(htmlString)
    outputFile.close()


# coding=utf-8
# Copyright 2018 The Gin-Config Authors.
#
# 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.

"""Init file for Gin."""

from gin.config import bind_parameter
from gin.config import clear_config
from gin.config import config_is_locked
from gin.config import config_scope
from gin.config import configurable
from gin.config import constant
from gin.config import constants_from_enum
from gin.config import current_scope
from gin.config import current_scope_str
from gin.config import enter_interactive_mode
from gin.config import exit_interactive_mode
from gin.config import external_configurable
from gin.config import finalize
from gin.config import operative_config_str
from gin.config import parse_config
from gin.config import parse_config_file
from gin.config import parse_config_files_and_bindings
from gin.config import query_parameter
from gin.config import REQUIRED
from gin.config import unlock_config

Response:
<INSERT> constants_from_enum
from gin.config import <INSERT_END> <|endoftext|> # coding=utf-8
# Copyright 2018 The Gin-Config Authors.
#
# 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.

"""Init file for Gin."""

from gin.config import bind_parameter
from gin.config import clear_config
from gin.config import config_is_locked
from gin.config import config_scope
from gin.config import configurable
from gin.config import constant
from gin.config import constants_from_enum
from gin.config import current_scope
from gin.config import current_scope_str
from gin.config import enter_interactive_mode
from gin.config import exit_interactive_mode
from gin.config import external_configurable
from gin.config import finalize
from gin.config import operative_config_str
from gin.config import parse_config
from gin.config import parse_config_file
from gin.config import parse_config_files_and_bindings
from gin.config import query_parameter
from gin.config import REQUIRED
from gin.config import unlock_config

Prompt:
Add import for constants_from_enum to be able to use @gin.constants_from_enum

PiperOrigin-RevId: 198401971

# coding=utf-8
# Copyright 2018 The Gin-Config Authors.
#
# 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.

"""Init file for Gin."""

from gin.config import bind_parameter
from gin.config import clear_config
from gin.config import config_is_locked
from gin.config import config_scope
from gin.config import configurable
from gin.config import constant
from gin.config import current_scope
from gin.config import current_scope_str
from gin.config import enter_interactive_mode
from gin.config import exit_interactive_mode
from gin.config import external_configurable
from gin.config import finalize
from gin.config import operative_config_str
from gin.config import parse_config
from gin.config import parse_config_file
from gin.config import parse_config_files_and_bindings
from gin.config import query_parameter
from gin.config import REQUIRED
from gin.config import unlock_config


import turtle as t

GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"

t.fillcolor(FARBE)
t.shape(SHAPE)

def zeichneKerze(brennt):
    t.pd()
    t.begin_fill()
    t.forward(GROESSE*100)
    t.left(90)
    t.forward(GROESSE*400)
    t.left(90)
    t.forward(GROESSE*100)
    t.right(90)
    t.forward(GROESSE*30)
    t.back(GROESSE*30)
    t.left(90)
    t.forward(GROESSE*100)
    t.left(90)
    t.forward(GROESSE*400)
    t.left(90)
    t.forward(GROESSE*100)
    t.end_fill()
    t.pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    t.left(90)
    t.fd(GROESSE*430)
    t.pd()
    t.color("yellow")
    t.dot(GROESSE*60)
    t.color("black")
    t.back(GROESSE*30)
    t.pu()
    t.home()

if __name__=="__main__":
    zeichneKerze(True)
    t.hideturtle()

Response:
<REPLACE_OLD> from <REPLACE_NEW> import <REPLACE_END> <REPLACE_OLD> import *

GROESSE <REPLACE_NEW> as t

GROESSE <REPLACE_END> <REPLACE_OLD> "turtle"

fillcolor(FARBE)
shape(SHAPE)

def <REPLACE_NEW> "turtle"

t.fillcolor(FARBE)
t.shape(SHAPE)

def <REPLACE_END> <REPLACE_OLD> pd()
 <REPLACE_NEW> t.pd()
 <REPLACE_END> <REPLACE_OLD> begin_fill()
 <REPLACE_NEW> t.begin_fill()
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*100)
 <REPLACE_NEW> t.forward(GROESSE*100)
 <REPLACE_END> <REPLACE_OLD> left(90)
 <REPLACE_NEW> t.left(90)
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*400)
 <REPLACE_NEW> t.forward(GROESSE*400)
 <REPLACE_END> <REPLACE_OLD> left(90)
 <REPLACE_NEW> t.left(90)
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*100)
 <REPLACE_NEW> t.forward(GROESSE*100)
 <REPLACE_END> <REPLACE_OLD> right(90)
 <REPLACE_NEW> t.right(90)
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*30)
 <REPLACE_NEW> t.forward(GROESSE*30)
 <REPLACE_END> <REPLACE_OLD> back(GROESSE*30)
 <REPLACE_NEW> t.back(GROESSE*30)
 <REPLACE_END> <REPLACE_OLD> left(90)
 <REPLACE_NEW> t.left(90)
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*100)
 <REPLACE_NEW> t.forward(GROESSE*100)
 <REPLACE_END> <REPLACE_OLD> left(90)
 <REPLACE_NEW> t.left(90)
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*400)
 <REPLACE_NEW> t.forward(GROESSE*400)
 <REPLACE_END> <REPLACE_OLD> left(90)
 <REPLACE_NEW> t.left(90)
 <REPLACE_END> <REPLACE_OLD> forward(GROESSE*100)
 <REPLACE_NEW> t.forward(GROESSE*100)
 <REPLACE_END> <REPLACE_OLD> end_fill()
 <REPLACE_NEW> t.end_fill()
 <REPLACE_END> <REPLACE_OLD> pu()
 <REPLACE_NEW> t.pu()
 <REPLACE_END> <REPLACE_OLD> left(90)
 <REPLACE_NEW> t.left(90)
 <REPLACE_END> <REPLACE_OLD> fd(GROESSE*430)
 <REPLACE_NEW> t.fd(GROESSE*430)
 <REPLACE_END> <REPLACE_OLD> pd()
 <REPLACE_NEW> t.pd()
 <REPLACE_END> <REPLACE_OLD> color("yellow")
 <REPLACE_NEW> t.color("yellow")
 <REPLACE_END> <REPLACE_OLD> dot(GROESSE*60)
 <REPLACE_NEW> t.dot(GROESSE*60)
 <REPLACE_END> <REPLACE_OLD> color("black")
 <REPLACE_NEW> t.color("black")
 <REPLACE_END> <REPLACE_OLD> back(GROESSE*30)
 <REPLACE_NEW> t.back(GROESSE*30)
 <REPLACE_END> <REPLACE_OLD> pu()
 <REPLACE_NEW> t.pu()
 <REPLACE_END> <REPLACE_OLD> home()

if <REPLACE_NEW> t.home()

if <REPLACE_END> <REPLACE_OLD> hideturtle()
 <REPLACE_NEW> t.hideturtle()
 <REPLACE_END> <|endoftext|> import turtle as t

GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"

t.fillcolor(FARBE)
t.shape(SHAPE)

def zeichneKerze(brennt):
    t.pd()
    t.begin_fill()
    t.forward(GROESSE*100)
    t.left(90)
    t.forward(GROESSE*400)
    t.left(90)
    t.forward(GROESSE*100)
    t.right(90)
    t.forward(GROESSE*30)
    t.back(GROESSE*30)
    t.left(90)
    t.forward(GROESSE*100)
    t.left(90)
    t.forward(GROESSE*400)
    t.left(90)
    t.forward(GROESSE*100)
    t.end_fill()
    t.pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    t.left(90)
    t.fd(GROESSE*430)
    t.pd()
    t.color("yellow")
    t.dot(GROESSE*60)
    t.color("black")
    t.back(GROESSE*30)
    t.pu()
    t.home()

if __name__=="__main__":
    zeichneKerze(True)
    t.hideturtle()

Prompt:
Make imports compliant to PEP 8 suggestion

from turtle import *

GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"

fillcolor(FARBE)
shape(SHAPE)

def zeichneKerze(brennt):
    pd()
    begin_fill()
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    right(90)
    forward(GROESSE*30)
    back(GROESSE*30)
    left(90)
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    end_fill()
    pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    left(90)
    fd(GROESSE*430)
    pd()
    color("yellow")
    dot(GROESSE*60)
    color("black")
    back(GROESSE*30)
    pu()
    home()

if __name__=="__main__":
    zeichneKerze(True)
    hideturtle()