from django.db import models

# Create your models here.

class Join(models.Model):
	email = models.EmailField()
	ip_address = models.CharField(max_length=120, default='ABC')
	timestamp = models.DateTimeField(auto_now_add = True, auto_now=False)
	updated = models.DateTimeField(auto_now_add = False, auto_now=True)

	def __unicode__(self):
		return "%s" %(self.email)

#To see the guide on using south, go here:
#https://github.com/codingforentrepreneurs/Guides/blob/master/using_south_in_django.md

Add South Guide, made message for it

Add South Guide, made message for it

Response:
from django.db import models

# Create your models here.

class Join(models.Model):
	email = models.EmailField()
	ip_address = models.CharField(max_length=120, default='ABC')
	timestamp = models.DateTimeField(auto_now_add = True, auto_now=False)
	updated = models.DateTimeField(auto_now_add = False, auto_now=True)

	def __unicode__(self):
		return "%s" %(self.email)

#To see the guide on using south, go here:
#https://github.com/codingforentrepreneurs/Guides/blob/master/using_south_in_django.md

Prompt:
Add South Guide, made message for it

from django.db import models

# Create your models here.

class Join(models.Model):
	email = models.EmailField()
	ip_address = models.CharField(max_length=120, default='ABC')
	timestamp = models.DateTimeField(auto_now_add = True, auto_now=False)
	updated = models.DateTimeField(auto_now_add = False, auto_now=True)

	def __unicode__(self):
		return "%s" %(self.email)


# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from os.path import join

import six

from asv import machine

def test_machine(tmpdir):
    tmpdir = six.text_type(tmpdir)

    m = machine.Machine.load(
        interactive=False,
        machine="orangutan",
        os="BeOS",
        arch="MIPS",
        cpu="10 MHz",
        ram="640k",
        _path=join(tmpdir, 'asv-machine.json'))

    m = machine.Machine.load(
        _path=join(tmpdir, 'asv-machine.json'), interactive=False)

    assert m.machine == 'orangutan'
    assert m.os == 'BeOS'
    assert m.arch == 'MIPS'
    assert m.cpu == '10 MHz'
    assert m.ram == '640k'

def test_machine_defaults(tmpdir):
    tmpdir = six.text_type(tmpdir)

    m = machine.Machine.load(
        interactive=True,
        use_defaults=True,
        _path=join(tmpdir, 'asv-machine.json'))

    assert m.__dict__ == m.get_defaults()

Response:
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from os.path import join

import six

from asv import machine

def test_machine(tmpdir):
    tmpdir = six.text_type(tmpdir)

    m = machine.Machine.load(
        interactive=False,
        machine="orangutan",
        os="BeOS",
        arch="MIPS",
        cpu="10 MHz",
        ram="640k",
        _path=join(tmpdir, 'asv-machine.json'))

    m = machine.Machine.load(
        _path=join(tmpdir, 'asv-machine.json'), interactive=False)

    assert m.machine == 'orangutan'
    assert m.os == 'BeOS'
    assert m.arch == 'MIPS'
    assert m.cpu == '10 MHz'
    assert m.ram == '640k'

def test_machine_defaults(tmpdir):
    tmpdir = six.text_type(tmpdir)

    m = machine.Machine.load(
        interactive=True,
        use_defaults=True,
        _path=join(tmpdir, 'asv-machine.json'))

    assert m.__dict__ == m.get_defaults()

Prompt:
Add a test for asv machine --yes using defaults values

# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from os.path import join

import six

from asv import machine

def test_machine(tmpdir):
    tmpdir = six.text_type(tmpdir)

    m = machine.Machine.load(
        interactive=False,
        machine="orangutan",
        os="BeOS",
        arch="MIPS",
        cpu="10 MHz",
        ram="640k",
        _path=join(tmpdir, 'asv-machine.json'))

    m = machine.Machine.load(
        _path=join(tmpdir, 'asv-machine.json'), interactive=False)

    assert m.machine == 'orangutan'
    assert m.os == 'BeOS'
    assert m.arch == 'MIPS'
    assert m.cpu == '10 MHz'
    assert m.ram == '640k'


from enum import Enum

class Constants:
    app_title = "RTGraph"
    app_version = '0.2.0'
    app_export_path = "data"
    app_sources = ["Serial", "Simulator"]
    app_encoding = "utf-8"

    plot_update_ms = 16
    plot_xlabel_title = "Time"
    plot_xlabel_unit = "s"
    plot_colors = ['#0072bd', '#d95319', '#edb120', '#7e2f8e', '#77ac30', '#4dbeee', '#a2142f']

    process_join_timeout_ms = 1000

    argument_default_samples = 500

    serial_default_speed = 115200
    serial_timeout_ms = 0.5

    simulator_default_speed = 0.002

    csv_default_filename = "%Y-%m-%d_%H-%M-%S"
    csv_delimiter = ","
    csv_extension = "csv"

    parser_timeout_ms = 0.05

    log_filename = "{}.log".format(app_title)
    log_max_bytes = 5120
    log_default_level = 1
    log_default_console_log = False

class MinimalPython:
    major = 3
    minor = 2
    release = 0

class SourceType(Enum):
    simulator = 1
    serial = 0

Update export path to new structure

Update export path to new structure

Response:
from enum import Enum

class Constants:
    app_title = "RTGraph"
    app_version = '0.2.0'
    app_export_path = "data"
    app_sources = ["Serial", "Simulator"]
    app_encoding = "utf-8"

    plot_update_ms = 16
    plot_xlabel_title = "Time"
    plot_xlabel_unit = "s"
    plot_colors = ['#0072bd', '#d95319', '#edb120', '#7e2f8e', '#77ac30', '#4dbeee', '#a2142f']

    process_join_timeout_ms = 1000

    argument_default_samples = 500

    serial_default_speed = 115200
    serial_timeout_ms = 0.5

    simulator_default_speed = 0.002

    csv_default_filename = "%Y-%m-%d_%H-%M-%S"
    csv_delimiter = ","
    csv_extension = "csv"

    parser_timeout_ms = 0.05

    log_filename = "{}.log".format(app_title)
    log_max_bytes = 5120
    log_default_level = 1
    log_default_console_log = False

class MinimalPython:
    major = 3
    minor = 2
    release = 0

class SourceType(Enum):
    simulator = 1
    serial = 0

Prompt:
Update export path to new structure

from enum import Enum

class Constants:
    app_title = "RTGraph"
    app_version = '0.2.0'
    app_export_path = "../data"
    app_sources = ["Serial", "Simulator"]
    app_encoding = "utf-8"

    plot_update_ms = 16
    plot_xlabel_title = "Time"
    plot_xlabel_unit = "s"
    plot_colors = ['#0072bd', '#d95319', '#edb120', '#7e2f8e', '#77ac30', '#4dbeee', '#a2142f']

    process_join_timeout_ms = 1000

    argument_default_samples = 500

    serial_default_speed = 115200
    serial_timeout_ms = 0.5

    simulator_default_speed = 0.002

    csv_default_filename = "%Y-%m-%d_%H-%M-%S"
    csv_delimiter = ","
    csv_extension = "csv"

    parser_timeout_ms = 0.05

    log_filename = "{}.log".format(app_title)
    log_max_bytes = 5120
    log_default_level = 1
    log_default_console_log = False

class MinimalPython:
    major = 3
    minor = 2
    release = 0

class SourceType(Enum):
    simulator = 1
    serial = 0


'''
Utilities to search files and retain meta data about files.
'''
import logging
import os
import mmap

def map_file(path=None):
    logging.debug("map_file: " + path)

    file_map = ""

    if path is None or path is os.path.isfile(path):
        logging.error('generate string is None')
        logging.error('path is not a path.')
    else:
        with open(path) as infile:
            file_map = mmap.mmap(infile, 0, access=mmap.ACCESS_READ)

    return file_map

def mask_mmap(file_map=None, mask_model=None):
    logging.debug("file_map: " + file_map)

    masked_line = ""

    if file_map is None:
        logging.error("file_map is None")
    else:
        for line in iter(file_map.readline, ""):
            masked_line = mask_line(line, mask_model)

def mask_line(line=None, mask_model=None):
    logging.debug("mask_line processing.")

    new_line = ""

    if line is None or line is mask_model:
        logging.error("line and or mask_model is None")
    else:
        for mask in mask_model:
            print(mask)

    return new_line

Write three functions to begin the feature to mask values of some keyvalue pairs. Publish to begin writing the tests and making these work and process better. Write it through.

Response:
'''
Utilities to search files and retain meta data about files.
'''
import logging
import os
import mmap

def map_file(path=None):
    logging.debug("map_file: " + path)

    file_map = ""

    if path is None or path is os.path.isfile(path):
        logging.error('generate string is None')
        logging.error('path is not a path.')
    else:
        with open(path) as infile:
            file_map = mmap.mmap(infile, 0, access=mmap.ACCESS_READ)

    return file_map

def mask_mmap(file_map=None, mask_model=None):
    logging.debug("file_map: " + file_map)

    masked_line = ""

    if file_map is None:
        logging.error("file_map is None")
    else:
        for line in iter(file_map.readline, ""):
            masked_line = mask_line(line, mask_model)

def mask_line(line=None, mask_model=None):
    logging.debug("mask_line processing.")

    new_line = ""

    if line is None or line is mask_model:
        logging.error("line and or mask_model is None")
    else:
        for mask in mask_model:
            print(mask)

    return new_line

Prompt: Write three functions to begin the feature to mask values of some keyvalue pairs. Publish to begin writing the tests and making these work and process better. Write it through.


def filterDictToStr(filterDict):
    return ', '.join(['%s=%s' %(key, repr(value)) for key, value in filterDict.items()])

class DataObject(object):

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        return 'DataObject( %s )' %(', '.join(['%s=%s' %(key, repr(value)) for key, value in self.__dict__.items()]))

    __repr__ = __str__

class hashableDict(dict):
    '''
        A dict that is hashable.
    '''

    def __hash__(self):
        KEYVAL_SEP = '~~..~~'
        NONEVAL='~~__NONE$$zz'

        PAIRS_SEP='88ascvjikZZ'

        hashableStr = []

        keys = list(self.keys())
        keys.sort()

        for key in keys:
            value = self[key]

            if value is None:
                value = NONEVAL
            else:
                value = str(value)

            hashableStr.append(key + KEYVAL_SEP + value)

        hashableStr = PAIRS_SEP.join(hashableStr)

        ret = hash(hashableStr)
        return ret

Add a hashable-dict type for testing

Add a hashable-dict type for testing

Response:
def filterDictToStr(filterDict):
    return ', '.join(['%s=%s' %(key, repr(value)) for key, value in filterDict.items()])

class DataObject(object):

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        return 'DataObject( %s )' %(', '.join(['%s=%s' %(key, repr(value)) for key, value in self.__dict__.items()]))

    __repr__ = __str__

class hashableDict(dict):
    '''
        A dict that is hashable.
    '''

    def __hash__(self):
        KEYVAL_SEP = '~~..~~'
        NONEVAL='~~__NONE$$zz'

        PAIRS_SEP='88ascvjikZZ'

        hashableStr = []

        keys = list(self.keys())
        keys.sort()

        for key in keys:
            value = self[key]

            if value is None:
                value = NONEVAL
            else:
                value = str(value)

            hashableStr.append(key + KEYVAL_SEP + value)

        hashableStr = PAIRS_SEP.join(hashableStr)

        ret = hash(hashableStr)
        return ret

Prompt:
Add a hashable-dict type for testing

def filterDictToStr(filterDict):
    return ', '.join(['%s=%s' %(key, repr(value)) for key, value in filterDict.items()])

class DataObject(object):

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        return 'DataObject( %s )' %(', '.join(['%s=%s' %(key, repr(value)) for key, value in self.__dict__.items()]))

    __repr__ = __str__


import os
import unittest
import tempfile
from io import StringIO

from pysd.py_backend.xmile.xmile2py import translate_xmile

class TestEquationStringParsing(unittest.TestCase):

    def test_multiline_equation():
        with open('tests/test-models/tests/game/test_game.stmx', 'r') as stmx:
            contents = stmx.read()

        # Insert line break in equation definition
        contents = contents.replace('<eqn>(Stock+Constant)</eqn>', '<eqn>(Stock+\nConstant)</eqn>')

        # Write out contents to temporary file
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
            temp_file.write(contents)

        # Convert file (should not raise error)
        generated_file = translate_xmile(temp_file.name)

        with open(generated_file, 'r') as fp:
            contents = fp.read()

        idx = contents.find('stock() + constant()')

        assert idx > 0, 'Correct, generated, equation not found'

        os.remove(temp_file.name)
        os.remove(generated_file+'.py')

Test to ensure equations with line breaks are parsed correctly

Response:
import os
import unittest
import tempfile
from io import StringIO

from pysd.py_backend.xmile.xmile2py import translate_xmile

class TestEquationStringParsing(unittest.TestCase):

    def test_multiline_equation():
        with open('tests/test-models/tests/game/test_game.stmx', 'r') as stmx:
            contents = stmx.read()

        # Insert line break in equation definition
        contents = contents.replace('<eqn>(Stock+Constant)</eqn>', '<eqn>(Stock+\nConstant)</eqn>')

        # Write out contents to temporary file
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
            temp_file.write(contents)

        # Convert file (should not raise error)
        generated_file = translate_xmile(temp_file.name)

        with open(generated_file, 'r') as fp:
            contents = fp.read()

        idx = contents.find('stock() + constant()')

        assert idx > 0, 'Correct, generated, equation not found'

        os.remove(temp_file.name)
        os.remove(generated_file+'.py')

Prompt: Test to ensure equations with line breaks are parsed correctly


import os

from distutils.core import setup

VERSION = '0.2.0-dev'

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

required = [
    'Django >= 1.5.0',
]

setup(
    name='madmin',
    version=VERSION,
    description="Virtual mail administration django app",
    author="Lewis Gunsch",
    author_email="lewis@gunsch.ca",
    url="https://github.com/lgunsch/madmin",
    license='MIT',
    long_description=README,
    packages=[
        'madmin',
        'madmin.management',
        'madmin.management.commands',
        'madmin.migrations',
        'madmin.tests',
    ],
    scripts=[],
    install_requires=required,
    include_package_data=True,
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Communications :: Email',
        'Topic :: Communications :: Email :: Mail Transport Agents',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Bump the version number - 0.2.0-dev.

Response:
import os

from distutils.core import setup

VERSION = '0.2.0-dev'

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

required = [
    'Django >= 1.5.0',
]

setup(
    name='madmin',
    version=VERSION,
    description="Virtual mail administration django app",
    author="Lewis Gunsch",
    author_email="lewis@gunsch.ca",
    url="https://github.com/lgunsch/madmin",
    license='MIT',
    long_description=README,
    packages=[
        'madmin',
        'madmin.management',
        'madmin.management.commands',
        'madmin.migrations',
        'madmin.tests',
    ],
    scripts=[],
    install_requires=required,
    include_package_data=True,
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Communications :: Email',
        'Topic :: Communications :: Email :: Mail Transport Agents',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Prompt:
Bump the version number - 0.2.0-dev.

Signed-off-by: Lewis Gunsch <748e1641a368164906d4a0c0e3965345453dcc93@gunsch.ca>

import os

from distutils.core import setup

VERSION = '0.1.0'

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

required = [
    'Django >= 1.5.0',
]

setup(
    name='madmin',
    version=VERSION,
    description="Virtual mail administration django app",
    author="Lewis Gunsch",
    author_email="lewis@gunsch.ca",
    url="https://github.com/lgunsch/madmin",
    license='MIT',
    long_description=README,
    packages=[
        'madmin',
        'madmin.management',
        'madmin.management.commands',
        'madmin.migrations',
        'madmin.tests',
    ],
    scripts=[],
    install_requires=required,
    include_package_data=True,
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Communications :: Email',
        'Topic :: Communications :: Email :: Mail Transport Agents',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


# -*- coding: utf-8 -*-
"""
	sphinxcontrib.openstreetmap
	===========================

	Embed OpenStreetMap on your documentation.

	:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
	:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive

class openstreetmap(nodes.General, nodes.Element):
    pass

class OpenStreetMapDirective(Directive):
    """Directive for embedding OpenStreetMap"""
    has_content = False
    option_spec = {
        'id': directives.unchanged,
        'label': directives.unchanged,
        'marker': directives.unchanged,
    }

    def run(self):
        node = openstreetmap()
        return [node]

def visit_openstreetmap_node(self, node):
    self.body.append("
OpenStreetMap directive
")

def depart_openstreetmap_node(self, node):
    pass

def setup(app):
    app.add_node(openstreetmap,
                 html=(visit_openstreetmap_node, depart_openstreetmap_node))
    app.add_directive('openstreetmap', OpenStreetMapDirective)

Add marker as required parameter

Add marker as required parameter

Response:
# -*- coding: utf-8 -*-
"""
	sphinxcontrib.openstreetmap
	===========================

	Embed OpenStreetMap on your documentation.

	:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
	:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive

class openstreetmap(nodes.General, nodes.Element):
    pass

class OpenStreetMapDirective(Directive):
    """Directive for embedding OpenStreetMap"""
    has_content = False
    option_spec = {
        'id': directives.unchanged,
        'label': directives.unchanged,
        'marker': directives.unchanged,
    }

    def run(self):
        node = openstreetmap()
        return [node]

def visit_openstreetmap_node(self, node):
    self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")

def depart_openstreetmap_node(self, node):
    pass

def setup(app):
    app.add_node(openstreetmap,
                 html=(visit_openstreetmap_node, depart_openstreetmap_node))
    app.add_directive('openstreetmap', OpenStreetMapDirective)

Prompt:
Add marker as required parameter

# -*- coding: utf-8 -*-
"""
	sphinxcontrib.openstreetmap
	===========================

	Embed OpenStreetMap on your documentation.

	:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
	:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive

class openstreetmap(nodes.General, nodes.Element):
    pass

class OpenStreetMapDirective(Directive):
    """Directive for embedding OpenStreetMap"""
    has_content = False
    option_spec = {
        'id': directives.unchanged,
        'label': directives.unchanged
    }

    def run(self):
        node = openstreetmap()
        return [node]

def visit_openstreetmap_node(self, node):
    self.body.append("
OpenStreetMap directive
")

def depart_openstreetmap_node(self, node):
    pass

def setup(app):
    app.add_node(openstreetmap,
                 html=(visit_openstreetmap_node, depart_openstreetmap_node))
    app.add_directive('openstreetmap', OpenStreetMapDirective)


import os
import pickle
from collections import defaultdict
from indra.sources import tas
from indra.databases import drugbank_client

def normalize_drug(drug):
    flags = score_drug(drug)
    if 'long_name' in flags:
        if 'DRUGBANK' in drug.db_refs:
            db_name = \
                drugbank_client.get_drugbank_name(drug.db_refs['DRUGBANK'])
            if db_name:
                drug.name = db_name

def score_drug(drug):
    flags = set()
    if any(char in drug.name for char in {'(', '[', '{', ','}):
        flags.add('has_special_char')
    if 'CHEBI' not in drug.db_refs and 'CHEMBL' in drug.db_refs:
        flags.add('chembl_not_chebi')
    if len(drug.name) > 20:
        flags.add('long_name')
    if ' ' in drug.name:
        flags.add('has_space')
    return flags

def choose_best_stmt(stmt_group):
    for stmt in stmt_group:
        normalize_drug(stmt.subj)
    stmts = sorted(stmt_group,
                   key=lambda x:
                    (len(score_drug(x.subj)),
                     len(x.subj.name)))
    if len(stmt_group) > 1:
        print('Choosing: %s (%s) from' %
              (stmts[0].subj, score_drug(stmts[0].subj)))
        for stmt in stmts:
            print(stmt.subj, score_drug(stmt.subj))
        print()
    return stmts[0]

if __name__ == '__main__':
    tp = tas.process_from_web(affinity_class_limit=2, named_only=True,
                              standardized_only=False)
    grouped = defaultdict(list)
    for stmt in tp.statements:
        grouped[(stmt.subj.db_refs['LSPCI'], stmt.obj.name)].append(stmt)

    opt_stmts = []
    for (lspci, obj_name), stmts in grouped.items():
        opt_stmt = choose_best_stmt(stmts)
        opt_stmts.append(opt_stmt)

    fname = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         os.pardir, 'resources', 'tas_stmts_filtered.pkl')
    with open(fname, 'wb') as fh:
        pickle.dump(opt_stmts, fh)

Add script to reproduce custom TAS dump

Add script to reproduce custom TAS dump

Response:
import os
import pickle
from collections import defaultdict
from indra.sources import tas
from indra.databases import drugbank_client

def normalize_drug(drug):
    flags = score_drug(drug)
    if 'long_name' in flags:
        if 'DRUGBANK' in drug.db_refs:
            db_name = \
                drugbank_client.get_drugbank_name(drug.db_refs['DRUGBANK'])
            if db_name:
                drug.name = db_name

def score_drug(drug):
    flags = set()
    if any(char in drug.name for char in {'(', '[', '{', ','}):
        flags.add('has_special_char')
    if 'CHEBI' not in drug.db_refs and 'CHEMBL' in drug.db_refs:
        flags.add('chembl_not_chebi')
    if len(drug.name) > 20:
        flags.add('long_name')
    if ' ' in drug.name:
        flags.add('has_space')
    return flags

def choose_best_stmt(stmt_group):
    for stmt in stmt_group:
        normalize_drug(stmt.subj)
    stmts = sorted(stmt_group,
                   key=lambda x:
                    (len(score_drug(x.subj)),
                     len(x.subj.name)))
    if len(stmt_group) > 1:
        print('Choosing: %s (%s) from' %
              (stmts[0].subj, score_drug(stmts[0].subj)))
        for stmt in stmts:
            print(stmt.subj, score_drug(stmt.subj))
        print()
    return stmts[0]

if __name__ == '__main__':
    tp = tas.process_from_web(affinity_class_limit=2, named_only=True,
                              standardized_only=False)
    grouped = defaultdict(list)
    for stmt in tp.statements:
        grouped[(stmt.subj.db_refs['LSPCI'], stmt.obj.name)].append(stmt)

    opt_stmts = []
    for (lspci, obj_name), stmts in grouped.items():
        opt_stmt = choose_best_stmt(stmts)
        opt_stmts.append(opt_stmt)

    fname = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         os.pardir, 'resources', 'tas_stmts_filtered.pkl')
    with open(fname, 'wb') as fh:
        pickle.dump(opt_stmts, fh)

Prompt: Add script to reproduce custom TAS dump


from flask_table import Table, Col

class RawCol(Col):
    """Class that will just output whatever it is given and will not
    escape it.
    """

    def td_format(self, content):
        return content

class ItemTable(Table):
    name = Col('Name')
    raw = RawCol('Raw')

def main():
    items = [{'name': 'A', 'raw': 'a'},
             {'name': 'B', 'raw': 'b'}]

    tab = ItemTable(items)

    # or {{ tab }} in jinja
    print(tab.__html__())

if __name__ == '__main__':
    main()

Add subclassing example for RawCol

Add subclassing example for RawCol

Response:
from flask_table import Table, Col

class RawCol(Col):
    """Class that will just output whatever it is given and will not
    escape it.
    """

    def td_format(self, content):
        return content

class ItemTable(Table):
    name = Col('Name')
    raw = RawCol('Raw')

def main():
    items = [{'name': 'A', 'raw': 'a'},
             {'name': 'B', 'raw': 'b'}]

    tab = ItemTable(items)

    # or {{ tab }} in jinja
    print(tab.__html__())

if __name__ == '__main__':
    main()

Prompt: Add subclassing example for RawCol


import os
from setuptools import setup

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

setup(
    name='rs_limits',
    version='0.5.1',
    author='Kevin L. Mitchell',
    author_email='kevin.mitchell@rackspace.com',
    description="Rackspace-specific rate-limit preprocessor for turnstile",
    license='Apache License (2.0)',
    py_modules=['rs_limits'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Paste',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
        ],
    url='https://github.com/klmitch/rs_limits',
    long_description=read('README.rst'),
    entry_points={
        'console_scripts': [
            'group_class = rs_limits:group_class',
            ],
        },
    install_requires=[
        'argparse',
        'nova_limits',
        'turnstile',
        ],
    tests_require=[
        'mox',
        'nose',
        'unittest2>=0.5.1',
        ],
    )

Add nose to dependencies list.

Add nose to dependencies list.

Response:
import os
from setuptools import setup

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

setup(
    name='rs_limits',
    version='0.5.1',
    author='Kevin L. Mitchell',
    author_email='kevin.mitchell@rackspace.com',
    description="Rackspace-specific rate-limit preprocessor for turnstile",
    license='Apache License (2.0)',
    py_modules=['rs_limits'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Paste',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
        ],
    url='https://github.com/klmitch/rs_limits',
    long_description=read('README.rst'),
    entry_points={
        'console_scripts': [
            'group_class = rs_limits:group_class',
            ],
        },
    install_requires=[
        'argparse',
        'nova_limits',
        'turnstile',
        ],
    tests_require=[
        'mox',
        'nose',
        'unittest2>=0.5.1',
        ],
    )

Prompt:
Add nose to dependencies list.

import os
from setuptools import setup

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

setup(
    name='rs_limits',
    version='0.5.1',
    author='Kevin L. Mitchell',
    author_email='kevin.mitchell@rackspace.com',
    description="Rackspace-specific rate-limit preprocessor for turnstile",
    license='Apache License (2.0)',
    py_modules=['rs_limits'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Paste',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
        ],
    url='https://github.com/klmitch/rs_limits',
    long_description=read('README.rst'),
    entry_points={
        'console_scripts': [
            'group_class = rs_limits:group_class',
            ],
        },
    install_requires=[
        'argparse',
        'nova_limits',
        'turnstile',
        ],
    tests_require=[
        'mox',
        'unittest2>=0.5.1',
        ],
    )


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

from django.db import models, migrations

class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='wine',
            name='description',
            field=models.TextField(blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='winery',
            name='description',
            field=models.TextField(blank=True),
            preserve_default=True,
        ),
    ]

Migrate database for model changes.

Migrate database for model changes.

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

from django.db import models, migrations

class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='wine',
            name='description',
            field=models.TextField(blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='winery',
            name='description',
            field=models.TextField(blank=True),
            preserve_default=True,
        ),
    ]

Prompt: Migrate database for model changes.


'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe

Libraries used:
import tkinter
import tkinter.filedialog
import csv
import os
import re
from time import sleep
import zipfile
'''
from distutils.core import setup
import py2exe

setup(
      console=[{'author': 'Shun Sakurai',
                       'dest_base': 'Check Forbidden',
                       'script': 'check_forbidden.py',
                       'version': '1.4.0',
                       }],
      options={'py2exe': {
                     'bundle_files': 2,
                     'compressed': True,
                     'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'],
                     }}
     )

Response:
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe

Libraries used:
import tkinter
import tkinter.filedialog
import csv
import os
import re
from time import sleep
import zipfile
'''
from distutils.core import setup
import py2exe

setup(
      console=[{'author': 'Shun Sakurai',
                       'dest_base': 'Check Forbidden',
                       'script': 'check_forbidden.py',
                       'version': '1.4.0',
                       }],
      options={'py2exe': {
                     'bundle_files': 2,
                     'compressed': True,
                     'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'],
                     }}
     )

Prompt:
Change the application name to 'Check Forbidden'

'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe

Libraries used:
import tkinter
import tkinter.filedialog
import csv
import os
import re
from time import sleep
import zipfile
'''
from distutils.core import setup
import py2exe

setup(
      console=[{'author': 'Shun Sakurai',
                       'script': 'check_forbidden.py',
                       'version': '1.4.0',
                       }],
      options={'py2exe': {
                     'bundle_files': 2,
                     'compressed': True,
                     'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'],
                     }}
     )


"""
Celery tasks for the User Profiles portion of RAPID.
"""

import datetime

import logging

from celery.schedules import crontab
from celery.task import PeriodicTask
from profiles.models import Profile

LOGGER = logging.getLogger(None)
"""The logger for this module"""
# Note: Logging doesn't appear to work properly unless we get the root logger

class Update_Users(PeriodicTask):
    """
    Periodic task to update users as inactive who have not logged in for more than 90 days

    This class runs every day at midnight
    """
    run_every = crontab(minute=0, hour=0)

    def run(self, **kwargs):
       LOGGER.debug("Running Update_Users task...")
       print("Updating users alert flag...")
       current_time = datetime.datetime.utcnow()
       #print("current_time",current_time)
       expired_date = current_time - datetime.timedelta(days=90)
       print("expired_date:",expired_date)
       Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)

Response:
"""
Celery tasks for the User Profiles portion of RAPID.
"""

import datetime

import logging

from celery.schedules import crontab
from celery.task import PeriodicTask
from profiles.models import Profile

LOGGER = logging.getLogger(None)
"""The logger for this module"""
# Note: Logging doesn't appear to work properly unless we get the root logger

class Update_Users(PeriodicTask):
    """
    Periodic task to update users as inactive who have not logged in for more than 90 days

    This class runs every day at midnight
    """
    run_every = crontab(minute=0, hour=0)

    def run(self, **kwargs):
       LOGGER.debug("Running Update_Users task...")
       print("Updating users alert flag...")
       current_time = datetime.datetime.utcnow()
       #print("current_time",current_time)
       expired_date = current_time - datetime.timedelta(days=90)
       print("expired_date:",expired_date)
       Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)

Prompt:
Update the crontab schedule to run every day at midnight

"""
Celery tasks for the User Profiles portion of RAPID.
"""

import datetime

import logging

from celery.schedules import crontab
from celery.task import PeriodicTask
from profiles.models import Profile

LOGGER = logging.getLogger(None)
"""The logger for this module"""
# Note: Logging doesn't appear to work properly unless we get the root logger

class Update_Users(PeriodicTask):
    """
    Periodic task to update users as inactive who have not logged in for more than 90 days

    This class runs every day at midnight
    """
    #run_every = crontab(minute=0, hour=0)
    run_every = crontab()

    def run(self, **kwargs):
       LOGGER.debug("Running Update_Users task...")
       print("Updating users alert flag...")
       current_time = datetime.datetime.utcnow()
       #print("current_time",current_time)
       expired_date = current_time - datetime.timedelta(days=90)
       print("expired_date:",expired_date)
       Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)


import json

from django import http

class JSONResponseMixin(object):
    context_variable = 'object_list'

    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(self.convert_context_to_json(context))

    def dispatch(self, *args, **kwargs):
        return super(JSONResponseMixin, self).dispatch(*args, **kwargs)

    def post(self, *args, **kwargs):
        return self.get(self, *args, **kwargs)

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return http.HttpResponse(content,
                                 content_type='application/json',
                                 **httpresponse_kwargs)

    def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        if self.context_variable is not None:
            return json.dumps(context.get(self.context_variable, None))
        return json.dumps(context)

Use json and not simplejson

Use json and not simplejson

Response:
import json

from django import http

class JSONResponseMixin(object):
    context_variable = 'object_list'

    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(self.convert_context_to_json(context))

    def dispatch(self, *args, **kwargs):
        return super(JSONResponseMixin, self).dispatch(*args, **kwargs)

    def post(self, *args, **kwargs):
        return self.get(self, *args, **kwargs)

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return http.HttpResponse(content,
                                 content_type='application/json',
                                 **httpresponse_kwargs)

    def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        if self.context_variable is not None:
            return json.dumps(context.get(self.context_variable, None))
        return json.dumps(context)

Prompt:
Use json and not simplejson

from django import http
from django.utils import simplejson as json

class JSONResponseMixin(object):
    context_variable = 'object_list'

    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(self.convert_context_to_json(context))

    def dispatch(self, *args, **kwargs):
        return super(JSONResponseMixin, self).dispatch(*args, **kwargs)

    def post(self, *args, **kwargs):
        return self.get(self, *args, **kwargs)

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return http.HttpResponse(content,
                                 content_type='application/json',
                                 **httpresponse_kwargs)

    def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        if self.context_variable is not None:
            return json.dumps(context.get(self.context_variable, None))
        return json.dumps(context)


from ooni import nettest
from ooni.utils import log
from twisted.internet import defer, protocol, reactor
from twisted.python import usage

import os

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None

class UsageOptions(usage.Options):
    optParameters = [
        ['interpreter', 'i', '', 'The interpreter to use'],
        ['script', 's', '', 'The script to run']
    ]

class ScriptProcessProtocol(protocol.ProcessProtocol):
    def __init__(self, test_case):
        self.test_case = test_case
        self.deferred = defer.Deferred()

    def connectionMade(self):
        log.debug("connectionMade")
        self.transport.closeStdin()
        self.test_case.report['lua_output'] = ""

    def outReceived(self, data):
        log.debug('outReceived: %s' % data)
        self.test_case.report['lua_output'] += data

    def errReceived(self, data):
        log.err('Script error: %s' % data)
        self.transport.signalProcess('KILL')

    def processEnded(self, status):
        rc = status.value.exitCode
        log.debug('processEnded: %s, %s' % \
                  (rc, self.test_case.report['lua_output']))
        if rc == 0:
            self.deferred.callback(self)
        else:
            self.deferred.errback(rc)

# TODO: Maybe the script requires a back-end.
class Script(nettest.NetTestCase):
    name = "Script test"
    version = "0.1"
    authors = "Dominic Hamon"

    usageOptions = UsageOptions
    requiredOptions = ['interpreter', 'script']

    def test_run_script(self):
        """
        We run the script specified in the usage options and take whatever
        is printed to stdout as the results of the test.
        """
        processProtocol = ScriptProcessProtocol(self)

        interpreter = self.localOptions['interpreter']
        if not which(interpreter):
            log.err('Unable to find %s executable in PATH.' % interpreter)
            return

        reactor.spawnProcess(processProtocol,
                             interpreter,
                             args=[interpreter, self.localOptions['script']],
                             env={'HOME': os.environ['HOME']},
                             usePTY=True)

        if not reactor.running:
            reactor.run()
        return processProtocol.deferred

Add Dominic Hamon's nettest for running tests written with other interpreters.

 * Fixes #8011.

Response:
from ooni import nettest
from ooni.utils import log
from twisted.internet import defer, protocol, reactor
from twisted.python import usage

import os

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None

class UsageOptions(usage.Options):
    optParameters = [
        ['interpreter', 'i', '', 'The interpreter to use'],
        ['script', 's', '', 'The script to run']
    ]

class ScriptProcessProtocol(protocol.ProcessProtocol):
    def __init__(self, test_case):
        self.test_case = test_case
        self.deferred = defer.Deferred()

    def connectionMade(self):
        log.debug("connectionMade")
        self.transport.closeStdin()
        self.test_case.report['lua_output'] = ""

    def outReceived(self, data):
        log.debug('outReceived: %s' % data)
        self.test_case.report['lua_output'] += data

    def errReceived(self, data):
        log.err('Script error: %s' % data)
        self.transport.signalProcess('KILL')

    def processEnded(self, status):
        rc = status.value.exitCode
        log.debug('processEnded: %s, %s' % \
                  (rc, self.test_case.report['lua_output']))
        if rc == 0:
            self.deferred.callback(self)
        else:
            self.deferred.errback(rc)

# TODO: Maybe the script requires a back-end.
class Script(nettest.NetTestCase):
    name = "Script test"
    version = "0.1"
    authors = "Dominic Hamon"

    usageOptions = UsageOptions
    requiredOptions = ['interpreter', 'script']

    def test_run_script(self):
        """
        We run the script specified in the usage options and take whatever
        is printed to stdout as the results of the test.
        """
        processProtocol = ScriptProcessProtocol(self)

        interpreter = self.localOptions['interpreter']
        if not which(interpreter):
            log.err('Unable to find %s executable in PATH.' % interpreter)
            return

        reactor.spawnProcess(processProtocol,
                             interpreter,
                             args=[interpreter, self.localOptions['script']],
                             env={'HOME': os.environ['HOME']},
                             usePTY=True)

        if not reactor.running:
            reactor.run()
        return processProtocol.deferred

Prompt:
Add Dominic Hamon's nettest for running tests written with other interpreters.

 * Fixes #8011.


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

from setuptools import setup, find_packages

setup(name='haas',
      version='0.2rc2',
      url='https://github.com/CCI-MOC/haas',
      packages=find_packages(),
      scripts=['scripts/haas', 'scripts/create_bridges'],
      install_requires=['Flask-SQLAlchemy',
                        'Werkzeug>=0.9.4,<0.10',
                        'Flask>=0.10.1,<0.11',
                        'schema==0.3.1',
                        'importlib==1.0.3',
                        'passlib==1.6.2',
                        'pexpect==3.3',
                        'requests==2.4.1',
                        'pytest>=2.6.2,<3.0',
                        'pytest-cov==1.8.0',
                        'pytest-xdist',
                        ])

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

from setuptools import setup, find_packages

setup(name='haas',
      version='0.2rc2',
      url='https://github.com/CCI-MOC/haas',
      packages=find_packages(),
      scripts=['scripts/haas', 'scripts/create_bridges'],
      install_requires=['Flask-SQLAlchemy',
                        'Werkzeug>=0.9.4,<0.10',
                        'Flask>=0.10.1,<0.11',
                        'schema==0.3.1',
                        'importlib==1.0.3',
                        'passlib==1.6.2',
                        'pexpect==3.3',
                        'requests==2.4.1',
                        'pytest>=2.6.2,<3.0',
                        'pytest-cov==1.8.0',
                        'pytest-xdist',
                        ])

Prompt:
Replace dependency on SQLAlchemy with Flask-SQLALchemy

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

from setuptools import setup, find_packages

setup(name='haas',
      version='0.2rc2',
      url='https://github.com/CCI-MOC/haas',
      packages=find_packages(),
      scripts=['scripts/haas', 'scripts/create_bridges'],
      install_requires=['SQLAlchemy==0.9.7',
                        'Werkzeug>=0.9.4,<0.10',
                        'Flask>=0.10.1,<0.11',
                        'schema==0.3.1',
                        'importlib==1.0.3',
                        'passlib==1.6.2',
                        'pexpect==3.3',
                        'requests==2.4.1',
                        'pytest>=2.6.2,<3.0',
                        'pytest-cov==1.8.0',
                        'pytest-xdist',
                        ])


import os
import json

from dtags.utils import halt, expand_path

TAGS = os.path.expanduser('~/.dtags')

def load_tags():
    """Load the tags from disk."""
    if not os.path.exists(TAGS):
        try:
            with open(TAGS, "w") as config_file:
                json.dump({}, config_file)
        except (IOError, OSError) as e:
            halt("Failed to init {}: {}".format(TAGS, e.strerror), e.errno)
    else:
        try:
            with open(TAGS, "r") as config_file:
                json_str = config_file.read().strip()
                if not json_str:
                    return {}
                tag_data = json.loads(json_str)
                if not tag_data:
                    return {}
                return {
                    tag: {expand_path(path): path for path in paths}
                    for tag, paths in tag_data.items()
                }
        except ValueError as e:
            halt("Failed to load {}: {}".format(TAGS, e))
        except (IOError, OSError) as e:
            halt("Failed to load {}: {}".format(TAGS, e.strerror), e.errno)

def save_tags(tags):
    """Save the tags to disk.

    :param tags: tags to save
    """
    try:
        with open(TAGS, "w") as config_file:
            json.dump(
                {tag: sorted(paths.values()) for tag, paths in tags.items()},
                config_file,
                indent=4,
                sort_keys=True
            )
    except IOError as e:
        halt("Failed to save {}: {}".format(TAGS, e.strerror))

Fix a bug in load_tags function

Fix a bug in load_tags function

Response:
import os
import json

from dtags.utils import halt, expand_path

TAGS = os.path.expanduser('~/.dtags')

def load_tags():
    """Load the tags from disk."""
    if not os.path.exists(TAGS):
        try:
            with open(TAGS, "w") as config_file:
                json.dump({}, config_file)
        except (IOError, OSError) as e:
            halt("Failed to init {}: {}".format(TAGS, e.strerror), e.errno)
    else:
        try:
            with open(TAGS, "r") as config_file:
                json_str = config_file.read().strip()
                if not json_str:
                    return {}
                tag_data = json.loads(json_str)
                if not tag_data:
                    return {}
                return {
                    tag: {expand_path(path): path for path in paths}
                    for tag, paths in tag_data.items()
                }
        except ValueError as e:
            halt("Failed to load {}: {}".format(TAGS, e))
        except (IOError, OSError) as e:
            halt("Failed to load {}: {}".format(TAGS, e.strerror), e.errno)

def save_tags(tags):
    """Save the tags to disk.

    :param tags: tags to save
    """
    try:
        with open(TAGS, "w") as config_file:
            json.dump(
                {tag: sorted(paths.values()) for tag, paths in tags.items()},
                config_file,
                indent=4,
                sort_keys=True
            )
    except IOError as e:
        halt("Failed to save {}: {}".format(TAGS, e.strerror))

Prompt:
Fix a bug in load_tags function

import os
import json

from dtags.utils import halt, expand_path

TAGS = os.path.expanduser('~/.dtags')

def load_tags():
    """Load the tags from disk."""
    if not os.path.exists(TAGS):
        try:
            with open(TAGS, "w") as config_file:
                json.dump({}, config_file)
        except (IOError, OSError) as e:
            halt("Failed to init {}: {}".format(TAGS, e.strerror), e.errno)
    else:
        try:
            with open(TAGS, "r") as config_file:
                json_str = config_file.read().strip()
                tag_data = {} if not json_str else json.loads(json_str)
                return {
                    tag: {expand_path(path): path for path in paths}
                    for tag, paths in tag_data.items()
                }
        except ValueError as e:
            halt("Failed to load {}: {}".format(TAGS, e))
        except (IOError, OSError) as e:
            halt("Failed to load {}: {}".format(TAGS, e.strerror), e.errno)

def save_tags(tags):
    """Save the tags to disk.

    :param tags: tags to save
    """
    try:
        with open(TAGS, "w") as config_file:
            json.dump(
                {tag: sorted(paths.values()) for tag, paths in tags.items()},
                config_file,
                indent=4,
                sort_keys=True
            )
    except IOError as e:
        halt("Failed to save {}: {}".format(TAGS, e.strerror))


#!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse

def get_args():
    d = '(default: %(default)s)'
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('model')
    parser.add_argument('-w','--weight-file-name', default='weights.h5',
                        help=d)
    parser.add_argument('-a', '--architecture-file-name',
                        default='architecture.json', help=d)
    return parser.parse_args()

def run():
    args = get_args()
    from h5py import File
    import json
    m = File(args.model,'r')
    with File(args.weight_file_name,'w') as w:
        for name, wt in w.items():
            w.copy(wt, name)

    arch = json.loads(m.attrs['model_config'])
    with open(args.architecture_file_name,'w') as arch_file:
        arch_file.write(json.dumps(arch,indent=2))

if __name__ == '__main__':
    run()

Remove Keras from network splitter

Response:
#!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse

def get_args():
    d = '(default: %(default)s)'
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('model')
    parser.add_argument('-w','--weight-file-name', default='weights.h5',
                        help=d)
    parser.add_argument('-a', '--architecture-file-name',
                        default='architecture.json', help=d)
    return parser.parse_args()

def run():
    args = get_args()
    from h5py import File
    import json
    m = File(args.model,'r')
    with File(args.weight_file_name,'w') as w:
        for name, wt in w.items():
            w.copy(wt, name)

    arch = json.loads(m.attrs['model_config'])
    with open(args.architecture_file_name,'w') as arch_file:
        arch_file.write(json.dumps(arch,indent=2))

if __name__ == '__main__':
    run()

Prompt:
Remove Keras from network splitter

Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function.

#!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse

def get_args():
    d = '(default: %(default)s)'
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('model')
    parser.add_argument('-w','--weight-file-name', default='weights.h5',
                        help=d)
    parser.add_argument('-a', '--architecture-file-name',
                        default='architecture.json', help=d)
    return parser.parse_args()

def run():
    args = get_args()
    import keras
    m = keras.models.load_model(args.model)
    m.save_weights(args.weight_file_name)
    with open(args.architecture_file_name,'w') as arch:
        arch.write(m.to_json(indent=2))

if __name__ == '__main__':
    run()


from django.conf import settings
from django.core.management import BaseCommand, CommandError
from django.utils import timezone

from legalaid.models import Case

class Command(BaseCommand):
    help = "Recalculate case.assigned_out_of_hours since a given date"

    def handle(self, *args, **options):
        try:
            date_string = args[0]
        except IndexError:
            raise CommandError("A start date is required")

        try:
            dt = timezone.datetime.strptime(date_string, "%Y-%m-%d")
        except ValueError:
            raise CommandError("The start date should be a valid datetime in yyyy-mm-dd format")

        cases = Case.objects.filter(provider_assigned_at__gte=dt)
        count = cases.count()

        self.stdout.write("{count} cases assigned since {dt}.".format(count=count, dt=dt))
        if not count:
            return

        unchanged = []
        changed_to_true = []
        changed_to_false = []

        for case in cases:
            current_value = case.assigned_out_of_hours
            new_value = self.recalculate_field(case)
            if new_value == current_value:
                unchanged.append(case.pk)
            elif new_value:
                changed_to_true.append(case.pk)
            else:
                changed_to_false.append(case.pk)

        self.stdout.write("{count} cases already had the correct value.".format(count=len(unchanged)))
        self.stdout.write("{count} cases will be changed to `True`.".format(count=len(changed_to_true)))
        self.stdout.write("{count} cases will be changed to `False`.".format(count=len(changed_to_false)))

    def recalculate_field(self, case):
        case_category = getattr(case.eligibility_check.category, "code") if case.eligibility_check else None
        non_rota_hours = settings.NON_ROTA_OPENING_HOURS[case_category]
        return not non_rota_hours.available(case.provider_assigned_at, tz_aware=True)

Add management command to recalculate the field

Response:
from django.conf import settings
from django.core.management import BaseCommand, CommandError
from django.utils import timezone

from legalaid.models import Case

class Command(BaseCommand):
    help = "Recalculate case.assigned_out_of_hours since a given date"

    def handle(self, *args, **options):
        try:
            date_string = args[0]
        except IndexError:
            raise CommandError("A start date is required")

        try:
            dt = timezone.datetime.strptime(date_string, "%Y-%m-%d")
        except ValueError:
            raise CommandError("The start date should be a valid datetime in yyyy-mm-dd format")

        cases = Case.objects.filter(provider_assigned_at__gte=dt)
        count = cases.count()

        self.stdout.write("{count} cases assigned since {dt}.".format(count=count, dt=dt))
        if not count:
            return

        unchanged = []
        changed_to_true = []
        changed_to_false = []

        for case in cases:
            current_value = case.assigned_out_of_hours
            new_value = self.recalculate_field(case)
            if new_value == current_value:
                unchanged.append(case.pk)
            elif new_value:
                changed_to_true.append(case.pk)
            else:
                changed_to_false.append(case.pk)

        self.stdout.write("{count} cases already had the correct value.".format(count=len(unchanged)))
        self.stdout.write("{count} cases will be changed to `True`.".format(count=len(changed_to_true)))
        self.stdout.write("{count} cases will be changed to `False`.".format(count=len(changed_to_false)))

    def recalculate_field(self, case):
        case_category = getattr(case.eligibility_check.category, "code") if case.eligibility_check else None
        non_rota_hours = settings.NON_ROTA_OPENING_HOURS[case_category]
        return not non_rota_hours.available(case.provider_assigned_at, tz_aware=True)

Prompt: Add management command to recalculate the field


# coding: utf-8
from __future__ import unicode_literals

from ..util import get_doc

import pytest
import numpy
from numpy.testing import assert_array_equal

@pytest.mark.parametrize('words,heads,matrix', [
    (
        'She created a test for spacy'.split(),
        [1, 0, 1, -2, -1, -1],
        numpy.array([
            [0, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1],
            [1, 1, 2, 3, 3, 3],
            [1, 1, 3, 3, 3, 3],
            [1, 1, 3, 3, 4, 4],
            [1, 1, 3, 3, 4, 5]], dtype=numpy.int32)
    )
    ])
def test_issue2396(en_vocab, words, heads, matrix):
    doc = get_doc(en_vocab, words=words, heads=heads)

    span = doc[:]
    assert_array_equal(doc.get_lca_matrix(), matrix)
    assert_array_equal(span.get_lca_matrix(), matrix)

Update get_lca_matrix test for develop

Update get_lca_matrix test for develop

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

from ..util import get_doc

import pytest
import numpy
from numpy.testing import assert_array_equal

@pytest.mark.parametrize('words,heads,matrix', [
    (
        'She created a test for spacy'.split(),
        [1, 0, 1, -2, -1, -1],
        numpy.array([
            [0, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1],
            [1, 1, 2, 3, 3, 3],
            [1, 1, 3, 3, 3, 3],
            [1, 1, 3, 3, 4, 4],
            [1, 1, 3, 3, 4, 5]], dtype=numpy.int32)
    )
    ])
def test_issue2396(en_vocab, words, heads, matrix):
    doc = get_doc(en_vocab, words=words, heads=heads)

    span = doc[:]
    assert_array_equal(doc.get_lca_matrix(), matrix)
    assert_array_equal(span.get_lca_matrix(), matrix)

Prompt:
Update get_lca_matrix test for develop

# coding: utf-8
from __future__ import unicode_literals

from ..util import get_doc

import pytest
import numpy

@pytest.mark.parametrize('sentence,matrix', [
    (
        'She created a test for spacy',
        numpy.array([
            [0, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1],
            [1, 1, 2, 3, 3, 3],
            [1, 1, 3, 3, 3, 3],
            [1, 1, 3, 3, 4, 4],
            [1, 1, 3, 3, 4, 5]], dtype=numpy.int32)
    )
    ])
def test_issue2396(EN, sentence, matrix):
    doc = EN(sentence)
    span = doc[:]
    assert (doc.get_lca_matrix() == matrix).all()
    assert (span.get_lca_matrix() == matrix).all()


"""
Project Euler Problem 7
=======================

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.

What is the 10001st prime number?
"""
from itertools import count

def is_prime(number):
    """
    Takes a number and returns True if it's a prime number, otherwise returns False.
    """
    if number == 2 or number == 3:
        return True

    if number <= 0 or number % 2 == 0 or number % 3 == 0:
        return False

    for i in range(2, int(number ** 0.5) + 1):
        if number % i == 0:
            return False

    return True

def prime_by_position(position):
    """
    Takes an integer and returns the prime number at that position.
    """
    prime_count = 0

    for i in count(start=2):
        if is_prime(i):
            prime_count += 1

            if prime_count == position:
                return i

def test_prime_by_position():
    assert prime_by_position(6) == 13

print(prime_by_position(10001))

Add solution and unit tests for problem 7

Response:
"""
Project Euler Problem 7
=======================

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.

What is the 10001st prime number?
"""
from itertools import count

def is_prime(number):
    """
    Takes a number and returns True if it's a prime number, otherwise returns False.
    """
    if number == 2 or number == 3:
        return True

    if number <= 0 or number % 2 == 0 or number % 3 == 0:
        return False

    for i in range(2, int(number ** 0.5) + 1):
        if number % i == 0:
            return False

    return True

def prime_by_position(position):
    """
    Takes an integer and returns the prime number at that position.
    """
    prime_count = 0

    for i in count(start=2):
        if is_prime(i):
            prime_count += 1

            if prime_count == position:
                return i

def test_prime_by_position():
    assert prime_by_position(6) == 13

print(prime_by_position(10001))

Prompt: Add solution and unit tests for problem 7


class Solution(object):
    def getMaximumGold(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        self.grid = grid
        self.rows = len(grid)
        if self.rows:
            self.cols = len(grid[0])

        ans = 0
        for x in range(self.rows):
            for y in range(self.cols):
                ans = max(ans, self.dfs(x, y))

        return ans

    def dfs(self, x, y):
        if not (0 <= x < self.rows and 0 <= y < self.cols):
            return 0
        else:
            gold = self.grid[x][y]
            if gold == 0:
                return 0
            self.grid[x][y] = 0
            ans = 0
            for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                nxt = self.dfs(x + dx, y + dy)
                if nxt > ans:
                    ans = nxt
            self.grid[x][y] = gold
            return ans + gold

Add py solution for 1219. Path with Maximum Gold

1219. Path with Maximum Gold: https://leetcode.com/problems/path-with-maximum-gold/

Response:
class Solution(object):
    def getMaximumGold(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        self.grid = grid
        self.rows = len(grid)
        if self.rows:
            self.cols = len(grid[0])

        ans = 0
        for x in range(self.rows):
            for y in range(self.cols):
                ans = max(ans, self.dfs(x, y))

        return ans

    def dfs(self, x, y):
        if not (0 <= x < self.rows and 0 <= y < self.cols):
            return 0
        else:
            gold = self.grid[x][y]
            if gold == 0:
                return 0
            self.grid[x][y] = 0
            ans = 0
            for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                nxt = self.dfs(x + dx, y + dy)
                if nxt > ans:
                    ans = nxt
            self.grid[x][y] = gold
            return ans + gold

Prompt:
Add py solution for 1219. Path with Maximum Gold

1219. Path with Maximum Gold: https://leetcode.com/problems/path-with-maximum-gold/


from django.test import TestCase
from django.urls import reverse

# Create your tests here.

class HomeViewTestCase(TestCase):
    """HomeView test suite"""

    expected_url = '/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:home')
        self.assertEquals(reverse_url, self.expected_url)

class LoginViewTestCase(TestCase):
    """LoginView test suite"""

    expected_url = '/login/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:login')
        self.assertEquals(reverse_url, self.expected_url)

class LogoutViewTestCase(TestCase):
    """LogoutView test suite"""

    expected_url = '/logout/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:logout')
        self.assertEquals(reverse_url, self.expected_url)

class UserFormViewTestCase(TestCase):
    """UserFormView test suite"""

    expected_url = '/register/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:register')
        self.assertEquals(reverse_url, self.expected_url)

Add view test cases for portal

Add view test cases for portal

Response:
from django.test import TestCase
from django.urls import reverse

# Create your tests here.

class HomeViewTestCase(TestCase):
    """HomeView test suite"""

    expected_url = '/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:home')
        self.assertEquals(reverse_url, self.expected_url)

class LoginViewTestCase(TestCase):
    """LoginView test suite"""

    expected_url = '/login/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:login')
        self.assertEquals(reverse_url, self.expected_url)

class LogoutViewTestCase(TestCase):
    """LogoutView test suite"""

    expected_url = '/logout/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:logout')
        self.assertEquals(reverse_url, self.expected_url)

class UserFormViewTestCase(TestCase):
    """UserFormView test suite"""

    expected_url = '/register/'

    def test_desired_location(self):
        resp = self.client.get(self.expected_url)
        self.assertEqual(resp.status_code, 200)

    def test_desired_name(self):
        reverse_url = reverse('portal:register')
        self.assertEquals(reverse_url, self.expected_url)

Prompt: Add view test cases for portal


from django.conf.urls import patterns, url

urlpatterns = patterns('projects.views',
    url(r'^add/$', 'add_project', name='add_project'),
    url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
    url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
    url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
    url(r'^archive/$', 'projects_archive', name='projects_archive'),
    url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
)

Add url for project_status_edit option

Add url for project_status_edit option

Response:
from django.conf.urls import patterns, url

urlpatterns = patterns('projects.views',
    url(r'^add/$', 'add_project', name='add_project'),
    url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
    url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
    url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
    url(r'^archive/$', 'projects_archive', name='projects_archive'),
    url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
)

Prompt:
Add url for project_status_edit option

from django.conf.urls import patterns, url

urlpatterns = patterns('projects.views',
    url(r'^add/$', 'add_project', name='add_project'),
    url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
    url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
    url(r'^archive/$', 'projects_archive', name='projects_archive'),
    url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
)


"""
    oauthlib
    ~~~~~~~~

    A generic, spec-compliant, thorough implementation of the OAuth
    request-signing logic.

    :copyright: (c) 2011 by Idan Gazit.
    :license: BSD, see LICENSE for details.
"""

__author__ = 'Idan Gazit <idan@gazit.me>'
__version__ = '0.6.0'

Add meta info in oauthlib module

Add meta info in oauthlib module

Response:
"""
    oauthlib
    ~~~~~~~~

    A generic, spec-compliant, thorough implementation of the OAuth
    request-signing logic.

    :copyright: (c) 2011 by Idan Gazit.
    :license: BSD, see LICENSE for details.
"""

__author__ = 'Idan Gazit <idan@gazit.me>'
__version__ = '0.6.0'

Prompt: Add meta info in oauthlib module


from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

class Reporter(object):
    def __init__(self, name):
        self.styles = getSampleStyleSheet()
        self.styles.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY))
        self.story = []
        self.name = name
        return

    def make_report(self):
        doc = SimpleDocTemplate(self.name + '.pdf', pagesize=letter,
                                rightMargin=72, leftMargin=72,
                                topMargin=72, bottomMargin=18)
        doc.build(self.story)
        return doc

    def add_story_text(self, text, style='Normal', space=None, fontsize=12):
        if space is None:
            space=(1,12)
        ptext = '<fond size=%d>%s</font>' % (fontsize, text)
        self.story.append(Paragraph(ptext, self.styles[style]))
        self.story.append(Spacer(*space))
        return

    def add_story_image(self, image_path, width=None, height=None):
        if width is not None:
            width = width*inch
        if height is not None:
            height = height*inch
        im = Image(image_path, width, height)
        self.story.append(im)

Add a simple class to work with canvas tools.

Response:
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

class Reporter(object):
    def __init__(self, name):
        self.styles = getSampleStyleSheet()
        self.styles.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY))
        self.story = []
        self.name = name
        return

    def make_report(self):
        doc = SimpleDocTemplate(self.name + '.pdf', pagesize=letter,
                                rightMargin=72, leftMargin=72,
                                topMargin=72, bottomMargin=18)
        doc.build(self.story)
        return doc

    def add_story_text(self, text, style='Normal', space=None, fontsize=12):
        if space is None:
            space=(1,12)
        ptext = '<fond size=%d>%s</font>' % (fontsize, text)
        self.story.append(Paragraph(ptext, self.styles[style]))
        self.story.append(Spacer(*space))
        return

    def add_story_image(self, image_path, width=None, height=None):
        if width is not None:
            width = width*inch
        if height is not None:
            height = height*inch
        im = Image(image_path, width, height)
        self.story.append(im)

Prompt: Add a simple class to work with canvas tools.


from cffi import FFI

ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;

fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);

int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);

void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("libfluidsynth.so.1")

Change the LD search path

Change the LD search path

Response:
from cffi import FFI

ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;

fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);

int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);

void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("libfluidsynth.so.1")

Prompt:
Change the LD search path

from cffi import FFI

ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;

fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);

int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);

void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1")  # Testing


# Copyright 2015-2017 John "LuaMilkshake" Marion
#
# 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.

"""GoldDust Packages Classes/Utilities
"""

class Package:
    """A package managed by GoldDust"""
    def __init__(self):
        self.name = ""
        self.version = ""

    @property
    def tarball(self):
        """The tarball file name for this package."""
        return "{}-{}.tar.bz2".format(self.name, self.version)

    @property
    def sig_file(self):
        """The detached signature file name for this package."""
        return "{}.sig".format(self.tarball)

class InstallScript:
    """Package pre/post install action script.

    These functions are used to perform extra work beyond extracting
    files.

    Note that JAR modification should only be done using the `munge_jar`
    function. This lets GoldDust know that you're modifying the JAR so it
    can properly handle other JAR mod packages as well.
    """
    def pre_install(self):
        """Called before any files are installed.
        """
        pass

    def munge_jar(self, jar):
        """Modify the Minecraft JAR file.
        """
        pass

    def post_install(self):
        """Called after files are installed.
        """
        pass

Add munge_jar stub for InstallScript

Add munge_jar stub for InstallScript

Response:
# Copyright 2015-2017 John "LuaMilkshake" Marion
#
# 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.

"""GoldDust Packages Classes/Utilities
"""

class Package:
    """A package managed by GoldDust"""
    def __init__(self):
        self.name = ""
        self.version = ""

    @property
    def tarball(self):
        """The tarball file name for this package."""
        return "{}-{}.tar.bz2".format(self.name, self.version)

    @property
    def sig_file(self):
        """The detached signature file name for this package."""
        return "{}.sig".format(self.tarball)

class InstallScript:
    """Package pre/post install action script.

    These functions are used to perform extra work beyond extracting
    files.

    Note that JAR modification should only be done using the `munge_jar`
    function. This lets GoldDust know that you're modifying the JAR so it
    can properly handle other JAR mod packages as well.
    """
    def pre_install(self):
        """Called before any files are installed.
        """
        pass

    def munge_jar(self, jar):
        """Modify the Minecraft JAR file.
        """
        pass

    def post_install(self):
        """Called after files are installed.
        """
        pass

Prompt:
Add munge_jar stub for InstallScript

# Copyright 2015-2017 John "LuaMilkshake" Marion
#
# 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.

"""GoldDust Packages Classes/Utilities
"""

class Package:
    """A package managed by GoldDust"""
    def __init__(self):
        self.name = ""
        self.version = ""

    @property
    def tarball(self):
        """The tarball file name for this package."""
        return "{}-{}.tar.bz2".format(self.name, self.version)

    @property
    def sig_file(self):
        """The detached signature file name for this package."""
        return "{}.sig".format(self.tarball)

class InstallScript:
    """Package pre/post install action script.
    """
    def pre_install(self):
        """Called before any files are installed.
        """
        pass

    def post_install(self):
        """Called after files are installed.
        """
        pass


from .. import run_nbgrader
from .base import BaseTestApp

class TestNbGraderFormgrade(BaseTestApp):

    def test_help(self):
        """Does the help display without error?"""
        run_nbgrader(["formgrade", "--help-all"])

Add back in command line test for nbgrader formgrade

Response:
from .. import run_nbgrader
from .base import BaseTestApp

class TestNbGraderFormgrade(BaseTestApp):

    def test_help(self):
        """Does the help display without error?"""
        run_nbgrader(["formgrade", "--help-all"])

Prompt: Add back in command line test for nbgrader formgrade


### GAMECHANGER_CI_PREVENT_BUILD
import os
import sys
import imp
from setuptools import find_packages

try:
    from restricted_pkg import setup
except:
    # allow falling back to setuptools only if
    # we are not trying to upload
    if 'upload' in sys.argv:
        raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg')
    from setuptools import setup

requirements = imp.load_source('requirements', os.path.realpath('requirements.py'))

setup(
    name='dusty',
    version='0.0.1',
    description='Docker-based development environment manager',
    url='https://github.com/gamechanger/dusty',
    private_repository='gamechanger',
    author='GameChanger',
    author_email='travis@gamechanger.io',
    packages=find_packages(),
    install_requires=requirements.install_requires,
    tests_require=requirements.test_requires,
    test_suite="nose.collector",
    entry_points={'console_scripts':
                  ['dustyd = dusty.daemon:main',
                   'dusty = dusty.cli.__init__:main']},
    zip_safe=False
)

Response:
### GAMECHANGER_CI_PREVENT_BUILD
import os
import sys
import imp
from setuptools import find_packages

try:
    from restricted_pkg import setup
except:
    # allow falling back to setuptools only if
    # we are not trying to upload
    if 'upload' in sys.argv:
        raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg')
    from setuptools import setup

requirements = imp.load_source('requirements', os.path.realpath('requirements.py'))

setup(
    name='dusty',
    version='0.0.1',
    description='Docker-based development environment manager',
    url='https://github.com/gamechanger/dusty',
    private_repository='gamechanger',
    author='GameChanger',
    author_email='travis@gamechanger.io',
    packages=find_packages(),
    install_requires=requirements.install_requires,
    tests_require=requirements.test_requires,
    test_suite="nose.collector",
    entry_points={'console_scripts':
                  ['dustyd = dusty.daemon:main',
                   'dusty = dusty.cli.__init__:main']},
    zip_safe=False
)

Prompt:
Add magic comment to stop our CI from building a package

import os
import sys
import imp
from setuptools import find_packages

try:
    from restricted_pkg import setup
except:
    # allow falling back to setuptools only if
    # we are not trying to upload
    if 'upload' in sys.argv:
        raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg')
    from setuptools import setup

requirements = imp.load_source('requirements', os.path.realpath('requirements.py'))

setup(
    name='dusty',
    version='0.0.1',
    description='Docker-based development environment manager',
    url='https://github.com/gamechanger/dusty',
    private_repository='gamechanger',
    author='GameChanger',
    author_email='travis@gamechanger.io',
    packages=find_packages(),
    install_requires=requirements.install_requires,
    tests_require=requirements.test_requires,
    test_suite="nose.collector",
    entry_points={'console_scripts':
                  ['dustyd = dusty.daemon:main',
                   'dusty = dusty.cli.__init__:main']},
    zip_safe=False
)


#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...

Options:
TERM        The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE  The list of files to search through
-c COL      Only search in the column specified by COL.
-o          Only output the matched part
"""
import re

from docopt import docopt
import xlrd

__author__ = 'peter'

def main():
    args = docopt(__doc__)
    p = re.compile(args['TERM'], re.UNICODE)
    for f in args['EXCEL_FILE']:
        workbook = xlrd.open_workbook(f)
        sheet = workbook.sheet_by_index(0)
        for rownum in range(sheet.nrows):
            for idx, v in enumerate(sheet.row_values(rownum)):
                if args['-c'] and idx != int(args['-c']):
                    continue
                s = p.search(str(v))
                if s:
                    if args['-o']:
                        print(s.group(0))
                    else:
                        print(sheet.row_values(rownum))

if __name__ == '__main__':
    main()

Response:
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...

Options:
TERM        The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE  The list of files to search through
-c COL      Only search in the column specified by COL.
-o          Only output the matched part
"""
import re

from docopt import docopt
import xlrd

__author__ = 'peter'

def main():
    args = docopt(__doc__)
    p = re.compile(args['TERM'], re.UNICODE)
    for f in args['EXCEL_FILE']:
        workbook = xlrd.open_workbook(f)
        sheet = workbook.sheet_by_index(0)
        for rownum in range(sheet.nrows):
            for idx, v in enumerate(sheet.row_values(rownum)):
                if args['-c'] and idx != int(args['-c']):
                    continue
                s = p.search(str(v))
                if s:
                    if args['-o']:
                        print(s.group(0))
                    else:
                        print(sheet.row_values(rownum))

if __name__ == '__main__':
    main()

Prompt:
Add support for only searching specified column

#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...

Options:
TERM        The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE  The list of files to search through
-o          Only output the matched part
"""
import re

from docopt import docopt
import xlrd

__author__ = 'peter'

def main():
    args = docopt(__doc__)
    p = re.compile(args['TERM'], re.UNICODE)
    for f in args['EXCEL_FILE']:
        workbook = xlrd.open_workbook(f)
        sheet = workbook.sheet_by_index(0)
        for rownum in range(sheet.nrows):
            for v in sheet.row_values(rownum):
                s = p.search(str(v))
                if s:
                    if args['-o']:
                        print(s.group(0))
                    else:
                        print(sheet.row_values(rownum))

if __name__ == '__main__':
    main()


#!/usr/bin/env python
from __future__ import division, print_function, absolute_import

def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    import numpy as np

    config = Configuration('pywt', parent_package, top_path)

    config.add_data_dir('tests')

    sources = ["_pywt", "common", "convolution", "wavelets", "wt"]
    source_templates = ["convolution", "wt"]
    headers = ["templating", "wavelets_coeffs"]
    header_templates = ["convolution", "wt", "wavelets_coeffs"]

    # add main PyWavelets module
    config.add_extension(
        '_pywt',
        sources=["src/{0}.c".format(s) for s in sources],
        depends=(["src/{0}.template.c".format(s) for s in source_templates]
                 + ["src/{0}.template.h".format(s) for s in header_templates]
                 + ["src/{0}.h".format(s) for s in headers]),
        include_dirs=["src", np.get_include()],
        define_macros=[("PY_EXTENSION", None)],
    )

    config.make_config_py()
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())

Fix format string for Python-2.6

BLD: Fix format string for Python-2.6

Response:
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import

def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    import numpy as np

    config = Configuration('pywt', parent_package, top_path)

    config.add_data_dir('tests')

    sources = ["_pywt", "common", "convolution", "wavelets", "wt"]
    source_templates = ["convolution", "wt"]
    headers = ["templating", "wavelets_coeffs"]
    header_templates = ["convolution", "wt", "wavelets_coeffs"]

    # add main PyWavelets module
    config.add_extension(
        '_pywt',
        sources=["src/{0}.c".format(s) for s in sources],
        depends=(["src/{0}.template.c".format(s) for s in source_templates]
                 + ["src/{0}.template.h".format(s) for s in header_templates]
                 + ["src/{0}.h".format(s) for s in headers]),
        include_dirs=["src", np.get_include()],
        define_macros=[("PY_EXTENSION", None)],
    )

    config.make_config_py()
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())

Prompt:
BLD: Fix format string for Python-2.6

#!/usr/bin/env python
from __future__ import division, print_function, absolute_import

def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    import numpy as np

    config = Configuration('pywt', parent_package, top_path)

    config.add_data_dir('tests')

    sources = ["_pywt", "common", "convolution", "wavelets", "wt"]
    source_templates = ["convolution", "wt"]
    headers = ["templating", "wavelets_coeffs"]
    header_templates = ["convolution", "wt", "wavelets_coeffs"]

    # add main PyWavelets module
    config.add_extension(
        '_pywt',
        sources=["src/{}.c".format(s) for s in sources],
        depends=(["src/{}.template.c".format(s) for s in source_templates]
                 + ["src/{}.template.h".format(s) for s in header_templates]
                 + ["src/{}.h".format(s) for s in headers]),
        include_dirs=["src", np.get_include()],
        define_macros=[("PY_EXTENSION", None)],
    )

    config.make_config_py()
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())


"""
This file defines the types for type annotations.

These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""

__all__ = [
    "Array",
    "Device",
    "Dtype",
    "SupportsDLPack",
    "SupportsBufferProtocol",
    "PyCapsule",
]

import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING

from . import Array
from numpy import (
    dtype,
    int8,
    int16,
    int32,
    int64,
    uint8,
    uint16,
    uint32,
    uint64,
    float32,
    float64,
)

# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]

Device = Literal["cpu"]
if TYPE_CHECKING or sys.version_info >= (3, 9):
    Dtype = dtype[Union[
        int8,
        int16,
        int32,
        int64,
        uint8,
        uint16,
        uint32,
        uint64,
        float32,
        float64,
    ]]
else:
    Dtype = dtype

SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any

Response:
"""
This file defines the types for type annotations.

These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""

__all__ = [
    "Array",
    "Device",
    "Dtype",
    "SupportsDLPack",
    "SupportsBufferProtocol",
    "PyCapsule",
]

import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING

from . import Array
from numpy import (
    dtype,
    int8,
    int16,
    int32,
    int64,
    uint8,
    uint16,
    uint32,
    uint64,
    float32,
    float64,
)

# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]

Device = Literal["cpu"]
if TYPE_CHECKING or sys.version_info >= (3, 9):
    Dtype = dtype[Union[
        int8,
        int16,
        int32,
        int64,
        uint8,
        uint16,
        uint32,
        uint64,
        float32,
        float64,
    ]]
else:
    Dtype = dtype

SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any

Prompt:
MAINT: Fix invalid parameter types used in `Dtype`

"""
This file defines the types for type annotations.

These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""

__all__ = [
    "Array",
    "Device",
    "Dtype",
    "SupportsDLPack",
    "SupportsBufferProtocol",
    "PyCapsule",
]

from typing import Any, Literal, Sequence, Type, Union

from . import (
    Array,
    int8,
    int16,
    int32,
    int64,
    uint8,
    uint16,
    uint32,
    uint64,
    float32,
    float64,
)

# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]

Device = Literal["cpu"]
Dtype = Type[
    Union[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]
]
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any