# -*- coding: utf-8 -*-
"""Testing the environment/configuration handler.
"""
import os
from copy import copy

import pytest

from typhon import environment

class TestEnvironment:
    """Testing the environment handler."""
    def setup_method(self):
        """Run all test methods with an empty environment."""
        self.env = copy(os.environ)
        os.environ = {}

    def teardown_method(self):
        """Restore old environment."""
        os.environ = self.env

    def test_get_environment_variables(self):
        """Test if environment variables are considered."""
        os.environ['TYPHON_ENV_TEST'] = 'TEST_VALUE'

        assert environment.environ['TYPHON_ENV_TEST'] == 'TEST_VALUE'

    def test_set_environment_variables(self):
        """Test if environment variables are updated."""
        environment.environ['TYPHON_ENV_TEST'] = 'TEST_VALUE'

        assert os.environ['TYPHON_ENV_TEST'] == 'TEST_VALUE'

    def test_undefined_variable(self):
        """Test behavior for undefined variables."""
        with pytest.raises(KeyError):
            environment.environ['TYPHON_ENV_TEST']

Add unittests for environment handler.

Add unittests for environment handler.

Response:
# -*- coding: utf-8 -*-
"""Testing the environment/configuration handler.
"""
import os
from copy import copy

import pytest

from typhon import environment

class TestEnvironment:
    """Testing the environment handler."""
    def setup_method(self):
        """Run all test methods with an empty environment."""
        self.env = copy(os.environ)
        os.environ = {}

    def teardown_method(self):
        """Restore old environment."""
        os.environ = self.env

    def test_get_environment_variables(self):
        """Test if environment variables are considered."""
        os.environ['TYPHON_ENV_TEST'] = 'TEST_VALUE'

        assert environment.environ['TYPHON_ENV_TEST'] == 'TEST_VALUE'

    def test_set_environment_variables(self):
        """Test if environment variables are updated."""
        environment.environ['TYPHON_ENV_TEST'] = 'TEST_VALUE'

        assert os.environ['TYPHON_ENV_TEST'] == 'TEST_VALUE'

    def test_undefined_variable(self):
        """Test behavior for undefined variables."""
        with pytest.raises(KeyError):
            environment.environ['TYPHON_ENV_TEST']

Prompt: Add unittests for environment handler.


#!/usr/bin/env python

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

# Need to figure out why this only fails on travis
# pylint: disable=bad-continuation

"""Prepares for nested docker, and executes a command."""
# TODO(Q-Lee): check the necessity of this once MountPropagation is available in
# prow: https://github.com/kubernetes/kubernetes/pull/59252

import argparse
import os
import subprocess
import sys

def check(*cmd):
    """Log and run the command, raising on errors."""
    print >>sys.stderr, 'Run:', cmd
    subprocess.check_call(cmd)

def main(envs, cmd):
    """Make important mounts r-shared, then run script and verify it exits 0."""
    check("mount", "--make-rshared", "/lib/modules")
    check("mount", "--make-rshared", "/sys")

    for env in envs:
        key, val = env.split('=', 1)
        print >>sys.stderr, '%s=%s' % (key, val)
        os.environ[key] = val
    if not cmd:
        raise ValueError(cmd)
    check(*cmd)

if __name__ == '__main__':
    PARSER = argparse.ArgumentParser()
    PARSER.add_argument('--env', default=[], action='append')
    PARSER.add_argument('cmd', nargs=1)
    PARSER.add_argument('args', nargs='*')
    ARGS = PARSER.parse_args()
    main(ARGS.env, ARGS.cmd + ARGS.args)

Add a scenario to initiliaze nested dind

Response:
#!/usr/bin/env python

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

# Need to figure out why this only fails on travis
# pylint: disable=bad-continuation

"""Prepares for nested docker, and executes a command."""
# TODO(Q-Lee): check the necessity of this once MountPropagation is available in
# prow: https://github.com/kubernetes/kubernetes/pull/59252

import argparse
import os
import subprocess
import sys

def check(*cmd):
    """Log and run the command, raising on errors."""
    print >>sys.stderr, 'Run:', cmd
    subprocess.check_call(cmd)

def main(envs, cmd):
    """Make important mounts r-shared, then run script and verify it exits 0."""
    check("mount", "--make-rshared", "/lib/modules")
    check("mount", "--make-rshared", "/sys")

    for env in envs:
        key, val = env.split('=', 1)
        print >>sys.stderr, '%s=%s' % (key, val)
        os.environ[key] = val
    if not cmd:
        raise ValueError(cmd)
    check(*cmd)

if __name__ == '__main__':
    PARSER = argparse.ArgumentParser()
    PARSER.add_argument('--env', default=[], action='append')
    PARSER.add_argument('cmd', nargs=1)
    PARSER.add_argument('args', nargs='*')
    ARGS = PARSER.parse_args()
    main(ARGS.env, ARGS.cmd + ARGS.args)

Prompt: Add a scenario to initiliaze nested dind


import datetime
from decimal import Decimal

from django.core.serializers.json import DjangoJSONEncoder

DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)

try:
    import freezegun.api
except ImportError:
    pass
else:
    DATETIME += (freezegun.api.FakeDatetime,)
    DATE += (freezegun.api.FakeDate,)

class TZAwareJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, DATETIME):
            return obj.strftime("%Y-%m-%d %H:%M:%S%z")
        return super(TZAwareJSONEncoder, self).default(obj)

def default(o):
    if hasattr(o, 'to_json'):
        return o.to_json()
    if isinstance(o, Decimal):
        return str(o)
    if isinstance(o, DATETIME):
        if o.tzinfo:
            return o.strftime('%Y-%m-%dT%H:%M:%S%z')
        return o.strftime("%Y-%m-%dT%H:%M:%S")
    if isinstance(o, DATE):
        return o.strftime("%Y-%m-%d")
    if isinstance(o, TIME):
        if o.tzinfo:
            return o.strftime('%H:%M:%S%z')
        return o.strftime("%H:%M:%S")

    raise TypeError(repr(o) + " is not JSON serializable")

Response:
import datetime
from decimal import Decimal

from django.core.serializers.json import DjangoJSONEncoder

DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)

try:
    import freezegun.api
except ImportError:
    pass
else:
    DATETIME += (freezegun.api.FakeDatetime,)
    DATE += (freezegun.api.FakeDate,)

class TZAwareJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, DATETIME):
            return obj.strftime("%Y-%m-%d %H:%M:%S%z")
        return super(TZAwareJSONEncoder, self).default(obj)

def default(o):
    if hasattr(o, 'to_json'):
        return o.to_json()
    if isinstance(o, Decimal):
        return str(o)
    if isinstance(o, DATETIME):
        if o.tzinfo:
            return o.strftime('%Y-%m-%dT%H:%M:%S%z')
        return o.strftime("%Y-%m-%dT%H:%M:%S")
    if isinstance(o, DATE):
        return o.strftime("%Y-%m-%d")
    if isinstance(o, TIME):
        if o.tzinfo:
            return o.strftime('%H:%M:%S%z')
        return o.strftime("%H:%M:%S")

    raise TypeError(repr(o) + " is not JSON serializable")

Prompt:
Make compatible with freezegun when testing.

import datetime
from decimal import Decimal

from django.core.serializers.json import DjangoJSONEncoder

class TZAwareJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S%z")
        return super(TZAwareJSONEncoder, self).default(obj)

def default(o):
    if hasattr(o, 'to_json'):
        return o.to_json()
    if isinstance(o, Decimal):
        return str(o)
    if isinstance(o, datetime.datetime):
        if o.tzinfo:
            return o.strftime('%Y-%m-%dT%H:%M:%S%z')
        return o.strftime("%Y-%m-%dT%H:%M:%S")
    if isinstance(o, datetime.date):
        return o.strftime("%Y-%m-%d")
    if isinstance(o, datetime.time):
        if o.tzinfo:
            return o.strftime('%H:%M:%S%z')
        return o.strftime("%H:%M:%S")

    raise TypeError(repr(o) + " is not JSON serializable")


# Data sources
database(
    thermoLibraries = ['primaryThermoLibrary'],
    reactionLibraries = [],
    seedMechanisms = [],
    kineticsDepositories = ['training'],
    kineticsFamilies = 'default',
    kineticsEstimator = 'rate rules',
)

# List of species
species(
    label='ethane',
    reactive=True,
    structure=SMILES("CC"),
)

# Reaction systems
simpleReactor(
    temperature=(1350,'K'),
    pressure=(1.0,'bar'),
    initialMoleFractions={
        "ethane": 1.0,
    },
    terminationConversion={
        'ethane': 0.9,
    },
    terminationTime=(1e6,'s'),
)

simulator(
    atol=1e-16,
    rtol=1e-8,
)

model(
    toleranceKeepInEdge=0.0,
    toleranceMoveToCore=0.1,
    toleranceInterruptSimulation=0.1,
    maximumEdgeSpecies=100000
)

options(
    units='si',
    saveRestartPeriod=None,
    drawMolecules=False,
    generatePlots=False,
    saveEdgeSpecies=True,
    saveConcentrationProfiles=True,
)

Response:
# Data sources
database(
    thermoLibraries = ['primaryThermoLibrary'],
    reactionLibraries = [],
    seedMechanisms = [],
    kineticsDepositories = ['training'],
    kineticsFamilies = 'default',
    kineticsEstimator = 'rate rules',
)

# List of species
species(
    label='ethane',
    reactive=True,
    structure=SMILES("CC"),
)

# Reaction systems
simpleReactor(
    temperature=(1350,'K'),
    pressure=(1.0,'bar'),
    initialMoleFractions={
        "ethane": 1.0,
    },
    terminationConversion={
        'ethane': 0.9,
    },
    terminationTime=(1e6,'s'),
)

simulator(
    atol=1e-16,
    rtol=1e-8,
)

model(
    toleranceKeepInEdge=0.0,
    toleranceMoveToCore=0.1,
    toleranceInterruptSimulation=0.1,
    maximumEdgeSpecies=100000
)

options(
    units='si',
    saveRestartPeriod=None,
    drawMolecules=False,
    generatePlots=False,
    saveEdgeSpecies=True,
    saveConcentrationProfiles=True,
)

Prompt:
Set minimal example to 'default' kineticsFamilies.

# Data sources
database(
    thermoLibraries = ['primaryThermoLibrary'],
    reactionLibraries = [],
    seedMechanisms = [],
    kineticsDepositories = ['training'],
    kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
    kineticsEstimator = 'rate rules',
)

# List of species
species(
    label='ethane',
    reactive=True,
    structure=SMILES("CC"),
)

# Reaction systems
simpleReactor(
    temperature=(1350,'K'),
    pressure=(1.0,'bar'),
    initialMoleFractions={
        "ethane": 1.0,
    },
    terminationConversion={
        'ethane': 0.9,
    },
    terminationTime=(1e6,'s'),
)

simulator(
    atol=1e-16,
    rtol=1e-8,
)

model(
    toleranceKeepInEdge=0.0,
    toleranceMoveToCore=0.1,
    toleranceInterruptSimulation=0.1,
    maximumEdgeSpecies=100000
)

options(
    units='si',
    saveRestartPeriod=None,
    drawMolecules=False,
    generatePlots=False,
    saveEdgeSpecies=True,
    saveConcentrationProfiles=True,
)


from datetime import date as vanilla_date

from calendar_testing import CalendarTest

from calexicon.calendars.other import JulianDayNumber

class TestJulianDayNumber(CalendarTest):
    def setUp(self):
        self.calendar = JulianDayNumber()

    def test_make_date(self):
        vd = vanilla_date(2010, 8, 1)
        d = self.calendar.from_date(vd)
        self.assertIsNotNone(d)

    def test_first_date(self):
        vd = vanilla_date(1, 1, 1)
        d = self.calendar.from_date(vd)
        self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)')

    def compare_date_and_number(self, year, month, day, number):
        vd = vanilla_date(year, month, day)
        d = self.calendar.from_date(vd)
        self.assertEqual(d.native_representation(), {'day_number': number})

    def test_other_date(self):
        self.compare_date_and_number(2013, 1, 1, 2456293)

Response:
from datetime import date as vanilla_date

from calendar_testing import CalendarTest

from calexicon.calendars.other import JulianDayNumber

class TestJulianDayNumber(CalendarTest):
    def setUp(self):
        self.calendar = JulianDayNumber()

    def test_make_date(self):
        vd = vanilla_date(2010, 8, 1)
        d = self.calendar.from_date(vd)
        self.assertIsNotNone(d)

    def test_first_date(self):
        vd = vanilla_date(1, 1, 1)
        d = self.calendar.from_date(vd)
        self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)')

    def compare_date_and_number(self, year, month, day, number):
        vd = vanilla_date(year, month, day)
        d = self.calendar.from_date(vd)
        self.assertEqual(d.native_representation(), {'day_number': number})

    def test_other_date(self):
        self.compare_date_and_number(2013, 1, 1, 2456293)

Prompt:
Add a new test - on date to day number conversion.

from datetime import date as vanilla_date

from calendar_testing import CalendarTest

from calexicon.calendars.other import JulianDayNumber

class TestJulianDayNumber(CalendarTest):
    def setUp(self):
        self.calendar = JulianDayNumber()

    def test_make_date(self):
        vd = vanilla_date(2010, 8, 1)
        d = self.calendar.from_date(vd)
        self.assertIsNotNone(d)

    def test_first_date(self):
        vd = vanilla_date(1, 1, 1)
        d = self.calendar.from_date(vd)
        self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)')


from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

import persistent_messages

class Command(BaseCommand):
    help = "Sends a message to all users."

    def handle(self, *args, **options):
        if len(args) < 2:
            print "Need two arbuments: subject and body."

        subject = args[0]
        body = args[1]
        sender = User.objects.get(username = 'astrobin')

        for recipient in User.objects.all():
            if recipient.username != 'astrobin':
                persistent_messages.add_message_without_storage(
                    recipient,
                    sender,
                    persistent_messages.SUCCESS,
                    body,
                    subject = subject)

Add command to message everybody.

Add command to message everybody.

Response:
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

import persistent_messages

class Command(BaseCommand):
    help = "Sends a message to all users."

    def handle(self, *args, **options):
        if len(args) < 2:
            print "Need two arbuments: subject and body."

        subject = args[0]
        body = args[1]
        sender = User.objects.get(username = 'astrobin')

        for recipient in User.objects.all():
            if recipient.username != 'astrobin':
                persistent_messages.add_message_without_storage(
                    recipient,
                    sender,
                    persistent_messages.SUCCESS,
                    body,
                    subject = subject)

Prompt: Add command to message everybody.


from __future__ import unicode_literals

import mopidy
from mopidy import ext
from mopidy.utils import config, formatting

default_config = """
[ext.local]

# If the local extension should be enabled or not
enabled = true

# Path to folder with local music
music_path = $XDG_MUSIC_DIR

# Path to playlist folder with m3u files for local music
playlist_path = $XDG_DATA_DIR/mopidy/playlists

# Path to tag cache for local music
tag_cache_file = $XDG_DATA_DIR/mopidy/tag_cache
"""

__doc__ = """A backend for playing music from a local music archive.

This backend handles URIs starting with ``file:``.

See :ref:`music-from-local-storage` for further instructions on using this
backend.

**Issues:**

https://github.com/mopidy/mopidy/issues?labels=Local+backend

**Dependencies:**

- None

**Default config:**

.. code-block:: ini

%(config)s
""" % {'config': formatting.indent(default_config)}

class Extension(ext.Extension):

    name = 'Mopidy-Local'
    version = mopidy.__version__

    def get_default_config(self):
        return default_config

    def get_config_schema(self):
        schema = config.ExtensionConfigSchema()
        schema['music_path'] = config.String()
        schema['playlist_path'] = config.String()
        schema['tag_cache_file'] = config.String()

    def validate_environment(self):
        pass

    def get_backend_classes(self):
        from .actor import LocalBackend
        return [LocalBackend]

Add default config and config schema

Response:
from __future__ import unicode_literals

import mopidy
from mopidy import ext
from mopidy.utils import config, formatting

default_config = """
[ext.local]

# If the local extension should be enabled or not
enabled = true

# Path to folder with local music
music_path = $XDG_MUSIC_DIR

# Path to playlist folder with m3u files for local music
playlist_path = $XDG_DATA_DIR/mopidy/playlists

# Path to tag cache for local music
tag_cache_file = $XDG_DATA_DIR/mopidy/tag_cache
"""

__doc__ = """A backend for playing music from a local music archive.

This backend handles URIs starting with ``file:``.

See :ref:`music-from-local-storage` for further instructions on using this
backend.

**Issues:**

https://github.com/mopidy/mopidy/issues?labels=Local+backend

**Dependencies:**

- None

**Default config:**

.. code-block:: ini

%(config)s
""" % {'config': formatting.indent(default_config)}

class Extension(ext.Extension):

    name = 'Mopidy-Local'
    version = mopidy.__version__

    def get_default_config(self):
        return default_config

    def get_config_schema(self):
        schema = config.ExtensionConfigSchema()
        schema['music_path'] = config.String()
        schema['playlist_path'] = config.String()
        schema['tag_cache_file'] = config.String()

    def validate_environment(self):
        pass

    def get_backend_classes(self):
        from .actor import LocalBackend
        return [LocalBackend]

Prompt:
local: Add default config and config schema

from __future__ import unicode_literals

import mopidy
from mopidy import ext

__doc__ = """A backend for playing music from a local music archive.

This backend handles URIs starting with ``file:``.

See :ref:`music-from-local-storage` for further instructions on using this
backend.

**Issues:**

https://github.com/mopidy/mopidy/issues?labels=Local+backend

**Dependencies:**

- None

**Settings:**

- :attr:`mopidy.settings.LOCAL_MUSIC_PATH`
- :attr:`mopidy.settings.LOCAL_PLAYLIST_PATH`
- :attr:`mopidy.settings.LOCAL_TAG_CACHE_FILE`
"""

class Extension(ext.Extension):

    name = 'Mopidy-Local'
    version = mopidy.__version__

    def get_default_config(self):
        return '[ext.local]'

    def validate_config(self, config):
        pass

    def validate_environment(self):
        pass

    def get_backend_classes(self):
        from .actor import LocalBackend
        return [LocalBackend]


import itertools

from django.db import models

import amo
from translations.fields import TranslatedField
from translations.models import Translation

class Review(amo.ModelBase):

    version = models.ForeignKey('versions.Version')
    user = models.ForeignKey('users.UserProfile')
    reply_to = models.ForeignKey('self', null=True, unique=True,
                                 db_column='reply_to')

    rating = models.PositiveSmallIntegerField(null=True)
    title = TranslatedField()
    body = TranslatedField()
    ip_address = models.CharField(max_length=255, default='0.0.0.0')

    editorreview = models.BooleanField(default=False)
    flag = models.BooleanField(default=False)
    sandbox = models.BooleanField(default=False)

    class Meta:
        db_table = 'reviews'

    def fetch_translations(self, ids, lang):
        if not ids:
            return []

        rv = {}
        ts = Translation.objects.filter(id__in=ids)

        # If a translation exists for the current language, use it.  Otherwise,
        # make do with whatever is available.  (Reviewers only write reviews in
        # their language).
        for id, translations in itertools.groupby(ts, lambda t: t.id):
            locales = dict((t.locale, t) for t in translations)
            if lang in locales:
                rv[id] = locales[lang]
            else:
                rv[id] = locales.itervalues().next()

        return rv.values()

Response:
import itertools

from django.db import models

import amo
from translations.fields import TranslatedField
from translations.models import Translation

class Review(amo.ModelBase):

    version = models.ForeignKey('versions.Version')
    user = models.ForeignKey('users.UserProfile')
    reply_to = models.ForeignKey('self', null=True, unique=True,
                                 db_column='reply_to')

    rating = models.PositiveSmallIntegerField(null=True)
    title = TranslatedField()
    body = TranslatedField()
    ip_address = models.CharField(max_length=255, default='0.0.0.0')

    editorreview = models.BooleanField(default=False)
    flag = models.BooleanField(default=False)
    sandbox = models.BooleanField(default=False)

    class Meta:
        db_table = 'reviews'

    def fetch_translations(self, ids, lang):
        if not ids:
            return []

        rv = {}
        ts = Translation.objects.filter(id__in=ids)

        # If a translation exists for the current language, use it.  Otherwise,
        # make do with whatever is available.  (Reviewers only write reviews in
        # their language).
        for id, translations in itertools.groupby(ts, lambda t: t.id):
            locales = dict((t.locale, t) for t in translations)
            if lang in locales:
                rv[id] = locales[lang]
            else:
                rv[id] = locales.itervalues().next()

        return rv.values()

Prompt:
Update reviews model for new added field in 5.5

import itertools

from django.db import models

import amo
from translations.fields import TranslatedField
from translations.models import Translation

class Review(amo.ModelBase):

    version = models.ForeignKey('versions.Version')
    user = models.ForeignKey('users.UserProfile')
    reply_to = models.ForeignKey('self', null=True, unique=True,
                                 db_column='reply_to')

    rating = models.PositiveSmallIntegerField(null=True)
    title = TranslatedField()
    body = TranslatedField()

    editorreview = models.BooleanField(default=False)
    flag = models.BooleanField(default=False)
    sandbox = models.BooleanField(default=False)

    class Meta:
        db_table = 'reviews'

    def fetch_translations(self, ids, lang):
        if not ids:
            return []

        rv = {}
        ts = Translation.objects.filter(id__in=ids)

        # If a translation exists for the current language, use it.  Otherwise,
        # make do with whatever is available.  (Reviewers only write reviews in
        # their language).
        for id, translations in itertools.groupby(ts, lambda t: t.id):
            locales = dict((t.locale, t) for t in translations)
            if lang in locales:
                rv[id] = locales[lang]
            else:
                rv[id] = locales.itervalues().next()

        return rv.values()


import json

from django import forms

from .models import PublicBody

class PublicBodySelect(forms.Widget):
    input_type = "text"
    template_name = 'publicbody/_chooser.html'
    initial_search = None

    class Media:
        extend = False
        js = ('js/publicbody.js',)

    def set_initial_search(self, search):
        self.initial_search = search

    def get_context(self, name, value=None, attrs=None):
        pb, pb_desc = None, None
        if value is not None:
            try:
                pb = PublicBody.objects.get(pk=int(value))
                pb_desc = pb.get_label()
            except (ValueError, PublicBody.DoesNotExist):
                pass
        context = super(PublicBodySelect, self).get_context(name, value, attrs)
        context['widget'].update({
            'value_label': pb_desc,
            'search': self.initial_search,
            'publicbody': pb,
            'json': json.dumps({
                'fields': {
                    name: {
                        'value': value,
                        'objects': [pb.as_data()] if pb is not None else None
                    }
                }
            })
        })
        return context

Return a list for objects on pb widget

Return a list for objects on pb widget

Response:
import json

from django import forms

from .models import PublicBody

class PublicBodySelect(forms.Widget):
    input_type = "text"
    template_name = 'publicbody/_chooser.html'
    initial_search = None

    class Media:
        extend = False
        js = ('js/publicbody.js',)

    def set_initial_search(self, search):
        self.initial_search = search

    def get_context(self, name, value=None, attrs=None):
        pb, pb_desc = None, None
        if value is not None:
            try:
                pb = PublicBody.objects.get(pk=int(value))
                pb_desc = pb.get_label()
            except (ValueError, PublicBody.DoesNotExist):
                pass
        context = super(PublicBodySelect, self).get_context(name, value, attrs)
        context['widget'].update({
            'value_label': pb_desc,
            'search': self.initial_search,
            'publicbody': pb,
            'json': json.dumps({
                'fields': {
                    name: {
                        'value': value,
                        'objects': [pb.as_data()] if pb is not None else None
                    }
                }
            })
        })
        return context

Prompt:
Return a list for objects on pb widget
import json

from django import forms

from .models import PublicBody

class PublicBodySelect(forms.Widget):
    input_type = "text"
    template_name = 'publicbody/_chooser.html'
    initial_search = None

    class Media:
        extend = False
        js = ('js/publicbody.js',)

    def set_initial_search(self, search):
        self.initial_search = search

    def get_context(self, name, value=None, attrs=None):
        pb, pb_desc = None, None
        if value is not None:
            try:
                pb = PublicBody.objects.get(pk=int(value))
                pb_desc = pb.get_label()
            except (ValueError, PublicBody.DoesNotExist):
                pass
        context = super(PublicBodySelect, self).get_context(name, value, attrs)
        context['widget'].update({
            'value_label': pb_desc,
            'search': self.initial_search,
            'publicbody': pb,
            'json': json.dumps({
                'fields': {
                    name: {
                        'value': value,
                        'objects': pb.as_data() if pb is not None else None
                    }
                }
            })
        })
        return context


from __future__ import absolute_import
from __future__ import print_function

import datetime

from freezegun import freeze_time

from corehq.celery_monitoring.heartbeat import Heartbeat, HeartbeatNeverRecorded, \
    HEARTBEAT_FREQUENCY
from testil import assert_raises, eq

from corehq.celery_monitoring.signals import TimeToStartTimer

def test_heartbeat():
    hb = Heartbeat('celery_periodic')
    hb.clear_last_seen()

    with assert_raises(HeartbeatNeverRecorded):
        hb.get_last_seen()

    with assert_raises(HeartbeatNeverRecorded):
        hb.get_blockage_duration()

    seen_time = datetime.datetime.utcnow()

    with freeze_time(seen_time):
        hb.mark_seen()
        eq(hb.get_last_seen(), seen_time)
        eq(hb.get_blockage_duration(), datetime.timedelta(seconds=0))

    with freeze_time(seen_time + datetime.timedelta(minutes=10)):
        eq(hb.get_last_seen(), seen_time)
        eq(hb.get_blockage_duration(), datetime.timedelta(minutes=10) - HEARTBEAT_FREQUENCY)

def test_time_to_start_timer():
    task_id = 'abc123'
    delay = datetime.timedelta(seconds=6)

    start_time = datetime.datetime.utcnow()

    # starts empty
    eq(TimeToStartTimer(task_id).stop_and_pop_timing(), None)

    with freeze_time(start_time):
        TimeToStartTimer(task_id).start_timing()

    with freeze_time(start_time + delay):
        time_to_start = TimeToStartTimer(task_id).stop_and_pop_timing()

    eq(time_to_start, delay)
    # can only pop once, second time empty
    eq(TimeToStartTimer(task_id).stop_and_pop_timing(), None)

Response:
from __future__ import absolute_import
from __future__ import print_function

import datetime

from freezegun import freeze_time

from corehq.celery_monitoring.heartbeat import Heartbeat, HeartbeatNeverRecorded, \
    HEARTBEAT_FREQUENCY
from testil import assert_raises, eq

from corehq.celery_monitoring.signals import TimeToStartTimer

def test_heartbeat():
    hb = Heartbeat('celery_periodic')
    hb.clear_last_seen()

    with assert_raises(HeartbeatNeverRecorded):
        hb.get_last_seen()

    with assert_raises(HeartbeatNeverRecorded):
        hb.get_blockage_duration()

    seen_time = datetime.datetime.utcnow()

    with freeze_time(seen_time):
        hb.mark_seen()
        eq(hb.get_last_seen(), seen_time)
        eq(hb.get_blockage_duration(), datetime.timedelta(seconds=0))

    with freeze_time(seen_time + datetime.timedelta(minutes=10)):
        eq(hb.get_last_seen(), seen_time)
        eq(hb.get_blockage_duration(), datetime.timedelta(minutes=10) - HEARTBEAT_FREQUENCY)

def test_time_to_start_timer():
    task_id = 'abc123'
    delay = datetime.timedelta(seconds=6)

    start_time = datetime.datetime.utcnow()

    # starts empty
    eq(TimeToStartTimer(task_id).stop_and_pop_timing(), None)

    with freeze_time(start_time):
        TimeToStartTimer(task_id).start_timing()

    with freeze_time(start_time + delay):
        time_to_start = TimeToStartTimer(task_id).stop_and_pop_timing()

    eq(time_to_start, delay)
    # can only pop once, second time empty
    eq(TimeToStartTimer(task_id).stop_and_pop_timing(), None)

Prompt:
Add simple test for celery time to start timer

from __future__ import absolute_import
from __future__ import print_function

import datetime

from freezegun import freeze_time

from corehq.celery_monitoring.heartbeat import Heartbeat, HeartbeatNeverRecorded, \
    HEARTBEAT_FREQUENCY
from testil import assert_raises, eq

def test_heartbeat():
    hb = Heartbeat('celery_periodic')
    hb.clear_last_seen()

    with assert_raises(HeartbeatNeverRecorded):
        hb.get_last_seen()

    with assert_raises(HeartbeatNeverRecorded):
        hb.get_blockage_duration()

    seen_time = datetime.datetime.utcnow()

    with freeze_time(seen_time):
        hb.mark_seen()
        eq(hb.get_last_seen(), seen_time)
        eq(hb.get_blockage_duration(), datetime.timedelta(seconds=0))

    with freeze_time(seen_time + datetime.timedelta(minutes=10)):
        eq(hb.get_last_seen(), seen_time)
        eq(hb.get_blockage_duration(), datetime.timedelta(minutes=10) - HEARTBEAT_FREQUENCY)


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

import pytest

import numpy as np

import dask.array as da
import dask.array.utils as dau

import dask_distance._compat

@pytest.mark.parametrize("x", [
    list(range(5)),
    np.random.randint(10, size=(15, 16)),
    da.random.randint(10, size=(15, 16), chunks=(5, 5)),
])
def test_asarray(x):
    d = dask_distance._compat._asarray(x)

    assert isinstance(d, da.Array)

    if not isinstance(x, (np.ndarray, da.Array)):
        x = np.asarray(x)

    dau.assert_eq(d, x)

Drop unused import from _compat tests

Drop unused import from _compat tests

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

import pytest

import numpy as np

import dask.array as da
import dask.array.utils as dau

import dask_distance._compat

@pytest.mark.parametrize("x", [
    list(range(5)),
    np.random.randint(10, size=(15, 16)),
    da.random.randint(10, size=(15, 16), chunks=(5, 5)),
])
def test_asarray(x):
    d = dask_distance._compat._asarray(x)

    assert isinstance(d, da.Array)

    if not isinstance(x, (np.ndarray, da.Array)):
        x = np.asarray(x)

    dau.assert_eq(d, x)

Prompt:
Drop unused import from _compat tests

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

import pytest

import numpy as np

import dask
import dask.array as da
import dask.array.utils as dau

import dask_distance._compat

@pytest.mark.parametrize("x", [
    list(range(5)),
    np.random.randint(10, size=(15, 16)),
    da.random.randint(10, size=(15, 16), chunks=(5, 5)),
])
def test_asarray(x):
    d = dask_distance._compat._asarray(x)

    assert isinstance(d, da.Array)

    if not isinstance(x, (np.ndarray, da.Array)):
        x = np.asarray(x)

    dau.assert_eq(d, x)


from collections import namedtuple
from ..prng import PRNG

class LCG(PRNG):
    LCGConstants = namedtuple('LCGConstants', ['a',   # Multiplier
                                               'c',   # Increment
                                               'm'])  # Modulus

    def __init__(self):
        self._state = self.seed(self._DEFAULT_SEED)

    # Returns a tuple with the LCG constants
    def _get_constants(self):
        pass

    def seed(self, val):
        self._state = val % self._get_constants().m

    def next(self):
        constants = self._get_constants()
        self._state = (constants.a * self._state + constants.c) % constants.m
        return self._state

    def recover(self, vals):
        self._verify_input(vals)
        self._state = vals[0]
        self._verify_output(vals[1:])

Response:
from collections import namedtuple
from ..prng import PRNG

class LCG(PRNG):
    LCGConstants = namedtuple('LCGConstants', ['a',   # Multiplier
                                               'c',   # Increment
                                               'm'])  # Modulus

    def __init__(self):
        self._state = self.seed(self._DEFAULT_SEED)

    # Returns a tuple with the LCG constants
    def _get_constants(self):
        pass

    def seed(self, val):
        self._state = val % self._get_constants().m

    def next(self):
        constants = self._get_constants()
        self._state = (constants.a * self._state + constants.c) % constants.m
        return self._state

    def recover(self, vals):
        self._verify_input(vals)
        self._state = vals[0]
        self._verify_output(vals[1:])

Prompt:
Use seed function in constructor since some LCGs might overwrite it.

from collections import namedtuple
from ..prng import PRNG

class LCG(PRNG):
    LCGConstants = namedtuple('LCGConstants', ['a',   # Multiplier
                                               'c',   # Increment
                                               'm'])  # Modulus

    def __init__(self):
        self._state = self._DEFAULT_SEED

    # Returns a tuple with the LCG constants
    def _get_constants(self):
        pass

    def seed(self, val):
        self._state = val % self._get_constants().m

    def next(self):
        constants = self._get_constants()
        self._state = (constants.a * self._state + constants.c) % constants.m
        return self._state

    def recover(self, vals):
        self._verify_input(vals)
        self._state = vals[0]
        self._verify_output(vals[1:])


__author__ = 'Maksim Dmitriev'

import argparse
import os

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
    parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
    parser.add_argument('-f', '--outfile', help='the output file names')

    args = parser.parse_args()
    source_image = args.source
    dest_dir = args.dest
    if dest_dir is None:
        os.makedirs(os.path.dirname(os.path.realpath(source_image)) + os.sep + 'out', exist_ok=True)

Response:
__author__ = 'Maksim Dmitriev'

import argparse
import os

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
    parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
    parser.add_argument('-f', '--outfile', help='the output file names')

    args = parser.parse_args()
    source_image = args.source
    dest_dir = args.dest
    if dest_dir is None:
        os.makedirs(os.path.dirname(os.path.realpath(source_image)) + os.sep + 'out', exist_ok=True)

Prompt:
Create an output directory unless it exists

__author__ = 'Maksim Dmitriev'

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo', help='foo help', required=True)
    args = parser.parse_args()


from django.core.management.base import BaseCommand
from corehq.apps.reminders.models import (CaseReminderHandler,
    UI_COMPLEX, ON_DATETIME, REMINDER_TYPE_DEFAULT,
    RECIPIENT_SURVEY_SAMPLE)
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    """
      The new reminders UI removes support for some edge cases, and the
    purpose of this script is to confirm that there are no reminder
    definitions which use those edge use cases.

    Usage:
        python manage.py check_for_old_reminders
    """
    args = ""
    help = ("A command which checks for edge use cases that are no longer"
        "supported in the new reminders UI")

    def get_reminder_definition_ids(self):
        result = CaseReminderHandler.view(
            "reminders/handlers_by_domain_case_type",
            include_docs=False,
        ).all()
        return [row["id"] for row in result]

    def check_for_ui_type(self, handler):
        if handler.ui_type != UI_COMPLEX:
            print "%s: Handler %s does not have advanced ui flag set" % (
                handler.domain, handler._id)

    def check_for_multiple_fire_time_types(self, handler):
        if len(handler.events) > 1:
            fire_time_type = handler.events[0].fire_time_type
            for event in handler.events[1:]:
                if event.fire_time_type != fire_time_type:
                    print ("%s: Handler %s references multiple fire time "
                        "types" % (handler.domain, handler._id))

    def check_for_datetime_criteria(self, handler):
        if handler.start_condition_type == ON_DATETIME:
            print ("%s: Handler %s starts on datetime criteria and is not a "
                "broadcast" % (handler.domain, handler._id))

    def check_for_case_group_recipient(self, handler):
        if handler.recipient == RECIPIENT_SURVEY_SAMPLE:
            print ("%s: Handler %s sends to case group and is not a "
                "broadcast" % (handler.domain, handler._id))

    def handle(self, *args, **options):
        ids = self.get_reminder_definition_ids()
        for handler_doc in iter_docs(CaseReminderHandler.get_db(), ids):
            handler = CaseReminderHandler.wrap(handler_doc)
            if handler.reminder_type == REMINDER_TYPE_DEFAULT:
                self.check_for_ui_type(handler)
                self.check_for_multiple_fire_time_types(handler)
                self.check_for_datetime_criteria(handler)
                self.check_for_case_group_recipient(handler)

Add script to check for unsupported edge cases

Response:
from django.core.management.base import BaseCommand
from corehq.apps.reminders.models import (CaseReminderHandler,
    UI_COMPLEX, ON_DATETIME, REMINDER_TYPE_DEFAULT,
    RECIPIENT_SURVEY_SAMPLE)
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    """
      The new reminders UI removes support for some edge cases, and the
    purpose of this script is to confirm that there are no reminder
    definitions which use those edge use cases.

    Usage:
        python manage.py check_for_old_reminders
    """
    args = ""
    help = ("A command which checks for edge use cases that are no longer"
        "supported in the new reminders UI")

    def get_reminder_definition_ids(self):
        result = CaseReminderHandler.view(
            "reminders/handlers_by_domain_case_type",
            include_docs=False,
        ).all()
        return [row["id"] for row in result]

    def check_for_ui_type(self, handler):
        if handler.ui_type != UI_COMPLEX:
            print "%s: Handler %s does not have advanced ui flag set" % (
                handler.domain, handler._id)

    def check_for_multiple_fire_time_types(self, handler):
        if len(handler.events) > 1:
            fire_time_type = handler.events[0].fire_time_type
            for event in handler.events[1:]:
                if event.fire_time_type != fire_time_type:
                    print ("%s: Handler %s references multiple fire time "
                        "types" % (handler.domain, handler._id))

    def check_for_datetime_criteria(self, handler):
        if handler.start_condition_type == ON_DATETIME:
            print ("%s: Handler %s starts on datetime criteria and is not a "
                "broadcast" % (handler.domain, handler._id))

    def check_for_case_group_recipient(self, handler):
        if handler.recipient == RECIPIENT_SURVEY_SAMPLE:
            print ("%s: Handler %s sends to case group and is not a "
                "broadcast" % (handler.domain, handler._id))

    def handle(self, *args, **options):
        ids = self.get_reminder_definition_ids()
        for handler_doc in iter_docs(CaseReminderHandler.get_db(), ids):
            handler = CaseReminderHandler.wrap(handler_doc)
            if handler.reminder_type == REMINDER_TYPE_DEFAULT:
                self.check_for_ui_type(handler)
                self.check_for_multiple_fire_time_types(handler)
                self.check_for_datetime_criteria(handler)
                self.check_for_case_group_recipient(handler)

Prompt: Add script to check for unsupported edge cases


# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend

class CoalesceFilterBackend(DjangoFilterBackend):
    """Support Ember Data coalesceFindRequests."""

    def filter_queryset(self, request, queryset, view):
        raw = request.query_params.get('filter[id]')
        if raw:
            ids = raw.split(',')
            view.pagination_class = None
            queryset = queryset.filter(id__in=ids)
        return queryset

Remove unused score filter backend

Remove unused score filter backend

Response:
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend

class CoalesceFilterBackend(DjangoFilterBackend):
    """Support Ember Data coalesceFindRequests."""

    def filter_queryset(self, request, queryset, view):
        raw = request.query_params.get('filter[id]')
        if raw:
            ids = raw.split(',')
            view.pagination_class = None
            queryset = queryset.filter(id__in=ids)
        return queryset

Prompt:
Remove unused score filter backend

# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase

class CoalesceFilterBackend(DjangoFilterBackend):
    """Support Ember Data coalesceFindRequests."""

    def filter_queryset(self, request, queryset, view):
        raw = request.query_params.get('filter[id]')
        if raw:
            ids = raw.split(',')
            view.pagination_class = None
            queryset = queryset.filter(id__in=ids)
        return queryset

class ScoreFilterBackend(DRYPermissionFiltersBase):
    def filter_list_queryset(self, request, queryset, view):
        """Limit all requests to superuser."""
        if request.user.is_authenticated():
            if request.user.is_staff:
                return queryset.all()
            # else:
            #     return queryset.filter(
            #         song__appearance__entry__entity__officers__person__user=request.user,
            #     )
        return queryset.none()


#!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Parse device output to extract LLVM profile data.

The profile data obtained from the device is raw. Thus, it must be indexed
before it can be used to generate coverage reports.

Typical usage:
    stty -F /dev/ttyUSB0 icanon
    cat /dev/ttyUSB0 | ./device_profile_data.py foo.profraw
    llvm-profdata merge -sparse foo.profraw -o foo.profdata
    llvm-cov show OBJECT_FILE -instr-profile=foo.profdata
"""
import argparse
import zlib
import re
import sys

def extract_profile_data(device_output_file):
    """Parse device output to extract LLVM profile data.

    This function returns the LLVM profile data as a byte array after
    verifying its length and checksum.

    Args:
        device_output_file: File that contains the device output.
    Returns:
        LLVM profile data.
    Raises:
        ValueError: If LLVM profile data cannot be detected in the device
            output or its length or checksum is incorrect.
    """
    lines = device_output_file.read().decode('utf-8', 'ignore').splitlines()
    for i, line in zip(reversed(range(len(lines))), reversed(lines)):
        match = re.match(
            r"""
                LLVM\ profile\ data
                \ \(length:\ (?P<length>\d*),
                \ CRC32:\ (?P<checksum>[0-9A-F]*)\):
            """, line, re.VERBOSE)
        if match:
            exp_length = int(match.group('length'))
            exp_checksum = match.group('checksum')
            byte_array = bytes.fromhex(lines[i + 1])
            break
    # Check if output has LLVM profile data
    if not match:
        raise ValueError(
            'Could not detect the LLVM profile data in device output.')
    # Check length
    act_length = len(byte_array)
    if act_length != exp_length:
        raise ValueError(('Length check failed! ',
                          f'Expected: {exp_length}, actual: {act_length}.'))
    # Check checksum
    act_checksum = zlib.crc32(byte_array).to_bytes(4,
                                                   byteorder='little',
                                                   signed=False).hex().upper()
    if act_checksum != exp_checksum:
        raise ValueError(
            ('Checksum check failed! ',
             f'Expected: {exp_checksum}, actual: {act_checksum}.'))
    return byte_array

def main():
    """Parses command line arguments and extracts the profile data from device
    output."""
    argparser = argparse.ArgumentParser(
        description='Extract LLVM profile data from device output.')
    argparser.add_argument(dest='output_file',
                           type=argparse.FileType('wb'),
                           default=sys.stdout,
                           help='output file for writing LLVM profile data')
    argparser.add_argument('--input_file',
                           type=argparse.FileType('rb'),
                           default=sys.stdin.buffer,
                           help='device output')
    args = argparser.parse_args()

    args.output_file.write(extract_profile_data(args.input_file))

if __name__ == '__main__':
    main()

[util] Implement a script for extracting profile data from device output

This change introduces a python script that extracts profile data from
device output.

Signed-off-by: Alphan Ulusoy <23b245cc5a07aacf75a9db847b24c67dee1707bf@google.com>

Response:
#!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Parse device output to extract LLVM profile data.

The profile data obtained from the device is raw. Thus, it must be indexed
before it can be used to generate coverage reports.

Typical usage:
    stty -F /dev/ttyUSB0 icanon
    cat /dev/ttyUSB0 | ./device_profile_data.py foo.profraw
    llvm-profdata merge -sparse foo.profraw -o foo.profdata
    llvm-cov show OBJECT_FILE -instr-profile=foo.profdata
"""
import argparse
import zlib
import re
import sys

def extract_profile_data(device_output_file):
    """Parse device output to extract LLVM profile data.

    This function returns the LLVM profile data as a byte array after
    verifying its length and checksum.

    Args:
        device_output_file: File that contains the device output.
    Returns:
        LLVM profile data.
    Raises:
        ValueError: If LLVM profile data cannot be detected in the device
            output or its length or checksum is incorrect.
    """
    lines = device_output_file.read().decode('utf-8', 'ignore').splitlines()
    for i, line in zip(reversed(range(len(lines))), reversed(lines)):
        match = re.match(
            r"""
                LLVM\ profile\ data
                \ \(length:\ (?P<length>\d*),
                \ CRC32:\ (?P<checksum>[0-9A-F]*)\):
            """, line, re.VERBOSE)
        if match:
            exp_length = int(match.group('length'))
            exp_checksum = match.group('checksum')
            byte_array = bytes.fromhex(lines[i + 1])
            break
    # Check if output has LLVM profile data
    if not match:
        raise ValueError(
            'Could not detect the LLVM profile data in device output.')
    # Check length
    act_length = len(byte_array)
    if act_length != exp_length:
        raise ValueError(('Length check failed! ',
                          f'Expected: {exp_length}, actual: {act_length}.'))
    # Check checksum
    act_checksum = zlib.crc32(byte_array).to_bytes(4,
                                                   byteorder='little',
                                                   signed=False).hex().upper()
    if act_checksum != exp_checksum:
        raise ValueError(
            ('Checksum check failed! ',
             f'Expected: {exp_checksum}, actual: {act_checksum}.'))
    return byte_array

def main():
    """Parses command line arguments and extracts the profile data from device
    output."""
    argparser = argparse.ArgumentParser(
        description='Extract LLVM profile data from device output.')
    argparser.add_argument(dest='output_file',
                           type=argparse.FileType('wb'),
                           default=sys.stdout,
                           help='output file for writing LLVM profile data')
    argparser.add_argument('--input_file',
                           type=argparse.FileType('rb'),
                           default=sys.stdin.buffer,
                           help='device output')
    args = argparser.parse_args()

    args.output_file.write(extract_profile_data(args.input_file))

if __name__ == '__main__':
    main()

Prompt:
[util] Implement a script for extracting profile data from device output

This change introduces a python script that extracts profile data from
device output.

Signed-off-by: Alphan Ulusoy <23b245cc5a07aacf75a9db847b24c67dee1707bf@google.com>


#!/usr/bin/env python

from __future__ import division

import climate
import lmj.cubes
import pandas as pd
import scipy.signal

logging = climate.get_logger('lowpass')

def lowpass(df, freq=10., order=4):
    '''Filter marker data using a butterworth low-pass filter.

    This method alters the data in `df` in-place.

    Parameters
    ----------
    freq : float, optional
        Use a butterworth filter with this cutoff frequency. Defaults to
        10Hz.
    order : int, optional
        Order of the butterworth filter. Defaults to 4.
    '''
    nyquist = 1 / (2 * pd.Series(df.index).diff().mean())
    assert 0 < freq < nyquist
    passes = 2  # filtfilt makes two passes over the data.
    correct = (2 ** (1 / passes) - 1) ** 0.25
    b, a = scipy.signal.butter(order / passes, (freq / correct) / nyquist)
    for c in df.columns:
        if c.startswith('marker') and c[-1] in 'xyz':
            df.loc[:, c] = scipy.signal.filtfilt(b, a, df[c])

@climate.annotate(
    root='load data files from this directory tree',
    output='save smoothed data files to this directory tree',
    pattern=('process only trials matching this pattern', 'option'),
    freq=('lowpass filter at N Hz', 'option', None, float),
)
def main(root, output, pattern='*', freq=None):
    for t in lmj.cubes.Experiment(root).trials_matching(pattern):
        lowpass(t.df, freq)
        t.save(t.root.replace(root, output))

if __name__ == '__main__':
    climate.call(main)

Split lowpass filtering into another script.

Response:
#!/usr/bin/env python

from __future__ import division

import climate
import lmj.cubes
import pandas as pd
import scipy.signal

logging = climate.get_logger('lowpass')

def lowpass(df, freq=10., order=4):
    '''Filter marker data using a butterworth low-pass filter.

    This method alters the data in `df` in-place.

    Parameters
    ----------
    freq : float, optional
        Use a butterworth filter with this cutoff frequency. Defaults to
        10Hz.
    order : int, optional
        Order of the butterworth filter. Defaults to 4.
    '''
    nyquist = 1 / (2 * pd.Series(df.index).diff().mean())
    assert 0 < freq < nyquist
    passes = 2  # filtfilt makes two passes over the data.
    correct = (2 ** (1 / passes) - 1) ** 0.25
    b, a = scipy.signal.butter(order / passes, (freq / correct) / nyquist)
    for c in df.columns:
        if c.startswith('marker') and c[-1] in 'xyz':
            df.loc[:, c] = scipy.signal.filtfilt(b, a, df[c])

@climate.annotate(
    root='load data files from this directory tree',
    output='save smoothed data files to this directory tree',
    pattern=('process only trials matching this pattern', 'option'),
    freq=('lowpass filter at N Hz', 'option', None, float),
)
def main(root, output, pattern='*', freq=None):
    for t in lmj.cubes.Experiment(root).trials_matching(pattern):
        lowpass(t.df, freq)
        t.save(t.root.replace(root, output))

if __name__ == '__main__':
    climate.call(main)

Prompt: Split lowpass filtering into another script.


#! /usr/bin/env python

from subprocess import Popen, PIPE

def launch(cmd):
    """
    Fork the specified command, returning a tuple of (stdout, stderr)
    """
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()

def get_stdout(cmd):
    """
    Fork the specified command, returning stdout
    """
    return launch(cmd)[0]

Add a wrapper to get just stdout back

Add a wrapper to get just stdout back

Response:
#! /usr/bin/env python

from subprocess import Popen, PIPE

def launch(cmd):
    """
    Fork the specified command, returning a tuple of (stdout, stderr)
    """
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()

def get_stdout(cmd):
    """
    Fork the specified command, returning stdout
    """
    return launch(cmd)[0]

Prompt:
Add a wrapper to get just stdout back

#! /usr/bin/env python

from subprocess import Popen, PIPE

def _popen(cmd):
    """
    Fork the specified command, returning a tuple of (stdout, stderr)
    """
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()


# Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.

from trac.db import Table, Column

name = 'mastertickets'
version = 2
tables = [
    Table('mastertickets', key=('source','dest'))[
        Column('source', type='integer'),
        Column('dest', type='integer'),
    ],
]

def convert_to_int(data):
    """Convert both source and dest in the mastertickets table to ints."""
    rows = data['mastertickets'][1]
    for i, (n1, n2) in enumerate(rows):
        rows[i] = [int(n1), int(n2)]

migrations = [
    (xrange(1,2), convert_to_int),
]

Fix the migration to actual work.

Fix the migration to actual work.

Response:
# Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.

from trac.db import Table, Column

name = 'mastertickets'
version = 2
tables = [
    Table('mastertickets', key=('source','dest'))[
        Column('source', type='integer'),
        Column('dest', type='integer'),
    ],
]

def convert_to_int(data):
    """Convert both source and dest in the mastertickets table to ints."""
    rows = data['mastertickets'][1]
    for i, (n1, n2) in enumerate(rows):
        rows[i] = [int(n1), int(n2)]

migrations = [
    (xrange(1,2), convert_to_int),
]

Prompt:
Fix the migration to actual work.
# Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.

from trac.db import Table, Column

name = 'mastertickets'
version = 2
tables = [
    Table('mastertickets', key=('source','dest'))[
        Column('source', type='integer'),
        Column('dest', type='integer'),
    ],
]

def convert_to_int(data):
    """Convert both source and dest in the mastertickets table to ints."""
    for row in data['mastertickets'][1]:
        for i, (n1, n2) in enumerate(row):
            row[i] = [int(n1), int(n2)]

migrations = [
    (xrange(1,2), convert_to_int),
]


from __future__ import absolute_import, division, print_function

from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage

__all__ = ['VispyLayerState']

class VispyLayerState(State):
    """
    A base state object for all Vispy layers
    """

    layer = CallbackProperty()
    visible = CallbackProperty(True)
    zorder = CallbackProperty(0)
    color = CallbackProperty()
    alpha = CallbackProperty()

    def __init__(self, **kwargs):

        super(VispyLayerState, self).__init__(**kwargs)

        self._sync_color = None
        self._sync_alpha = None

        self.add_callback('layer', self._layer_changed)
        self._layer_changed()

        self.add_global_callback(self._notify_layer_update)

    def _notify_layer_update(self, **kwargs):
        message = LayerArtistUpdatedMessage(self)
        if self.layer is not None and self.layer.hub is not None:
            self.layer.hub.broadcast(message)

    def _layer_changed(self):

        if self._sync_color is not None:
            self._sync_color.stop_syncing()

        if self._sync_alpha is not None:
            self._sync_alpha.stop_syncing()

        if self.layer is not None:

            self.color = self.layer.style.color
            self.alpha = self.layer.style.alpha

            self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
            self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')

Response:
from __future__ import absolute_import, division, print_function

from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage

__all__ = ['VispyLayerState']

class VispyLayerState(State):
    """
    A base state object for all Vispy layers
    """

    layer = CallbackProperty()
    visible = CallbackProperty(True)
    zorder = CallbackProperty(0)
    color = CallbackProperty()
    alpha = CallbackProperty()

    def __init__(self, **kwargs):

        super(VispyLayerState, self).__init__(**kwargs)

        self._sync_color = None
        self._sync_alpha = None

        self.add_callback('layer', self._layer_changed)
        self._layer_changed()

        self.add_global_callback(self._notify_layer_update)

    def _notify_layer_update(self, **kwargs):
        message = LayerArtistUpdatedMessage(self)
        if self.layer is not None and self.layer.hub is not None:
            self.layer.hub.broadcast(message)

    def _layer_changed(self):

        if self._sync_color is not None:
            self._sync_color.stop_syncing()

        if self._sync_alpha is not None:
            self._sync_alpha.stop_syncing()

        if self.layer is not None:

            self.color = self.layer.style.color
            self.alpha = self.layer.style.alpha

            self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
            self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')

Prompt:
Make sure layer artist icon updates when changing the color mode or colormaps
from __future__ import absolute_import, division, print_function

from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State

__all__ = ['VispyLayerState']

class VispyLayerState(State):
    """
    A base state object for all Vispy layers
    """

    layer = CallbackProperty()
    visible = CallbackProperty(True)
    zorder = CallbackProperty(0)
    color = CallbackProperty()
    alpha = CallbackProperty()

    def __init__(self, **kwargs):

        super(VispyLayerState, self).__init__(**kwargs)

        self._sync_color = None
        self._sync_alpha = None

        self.add_callback('layer', self._layer_changed)
        self._layer_changed()

    def _layer_changed(self):

        if self._sync_color is not None:
            self._sync_color.stop_syncing()

        if self._sync_alpha is not None:
            self._sync_alpha.stop_syncing()

        if self.layer is not None:

            self.color = self.layer.style.color
            self.alpha = self.layer.style.alpha

            self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
            self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')


from distutils.core import Extension, setup

try:
    from Cython.Build import cythonize
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = cythonize([
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ])

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    license='MIT',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)

Use "cythonize" if Cython is installed.

Use "cythonize" if Cython is installed.

Response:
from distutils.core import Extension, setup

try:
    from Cython.Build import cythonize
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = cythonize([
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ])

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    license='MIT',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)

Prompt:
Use "cythonize" if Cython is installed.

from distutils.core import Extension, setup

try:
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ]

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    license='MIT',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)


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

"""
{{cookiecutter.repo_name}}
============================

The root of :class:`{{cookiecutter.app_class_name}}` is created from the kv file.
"""

import kivy
kivy.require('{{cookiecutter.kivy_version}}')

from kivy.app import App

class {{cookiecutter.app_class_name}}(App):
    """Basic Kivy App with a user defined title."""

    title = '{{cookiecutter.app_title}}'

    def build(self):
        return self.root

Implement a basic kivy application

Implement a basic kivy application

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

"""
{{cookiecutter.repo_name}}
============================

The root of :class:`{{cookiecutter.app_class_name}}` is created from the kv file.
"""

import kivy
kivy.require('{{cookiecutter.kivy_version}}')

from kivy.app import App

class {{cookiecutter.app_class_name}}(App):
    """Basic Kivy App with a user defined title."""

    title = '{{cookiecutter.app_title}}'

    def build(self):
        return self.root

Prompt: Implement a basic kivy application


from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from social.app.models.author import Author

class FriendRequestsListView(generic.ListView):
    context_object_name = "all_friend_requests"
    template_name = "app/friend_requests_list.html"

    def get_queryset(self):
        return self.request.user.profile.incoming_friend_requests.all()

    def post(self, request):
        logged_in_author = self.request.user.profile
        accepted_friend_requests = request.POST.getlist('accepted_friend_requests')

        for new_friend_id in accepted_friend_requests:
            new_friend = Author.objects.get(id=new_friend_id)

            if new_friend.node.local:
                logged_in_author.accept_friend_request(new_friend)
            else:
                r = new_friend.node.post_friend_request(request, logged_in_author, new_friend)

                if 200 <= r.status_code < 300:
                    # Success!
                    logged_in_author.accept_friend_request(new_friend)
                else:
                    r.raise_for_status()

        logged_in_author.save()

        return HttpResponseRedirect(reverse("app:friend-requests-list"))

Put in a raise for status for now

Put in a raise for status for now

Response:
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from social.app.models.author import Author

class FriendRequestsListView(generic.ListView):
    context_object_name = "all_friend_requests"
    template_name = "app/friend_requests_list.html"

    def get_queryset(self):
        return self.request.user.profile.incoming_friend_requests.all()

    def post(self, request):
        logged_in_author = self.request.user.profile
        accepted_friend_requests = request.POST.getlist('accepted_friend_requests')

        for new_friend_id in accepted_friend_requests:
            new_friend = Author.objects.get(id=new_friend_id)

            if new_friend.node.local:
                logged_in_author.accept_friend_request(new_friend)
            else:
                r = new_friend.node.post_friend_request(request, logged_in_author, new_friend)

                if 200 <= r.status_code < 300:
                    # Success!
                    logged_in_author.accept_friend_request(new_friend)
                else:
                    r.raise_for_status()

        logged_in_author.save()

        return HttpResponseRedirect(reverse("app:friend-requests-list"))

Prompt:
Put in a raise for status for now

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from social.app.models.author import Author

class FriendRequestsListView(generic.ListView):
    context_object_name = "all_friend_requests"
    template_name = "app/friend_requests_list.html"

    def get_queryset(self):
        return self.request.user.profile.incoming_friend_requests.all()

    def post(self, request):
        logged_in_author = self.request.user.profile
        accepted_friend_requests = request.POST.getlist('accepted_friend_requests')

        for new_friend_id in accepted_friend_requests:
            new_friend = Author.objects.get(id=new_friend_id)

            if new_friend.node.local:
                logged_in_author.accept_friend_request(new_friend)
            else:
                r = new_friend.node.post_friend_request(request, logged_in_author, new_friend)

                if 200 <= r.status_code < 300:
                    # Success!
                    logged_in_author.accept_friend_request(new_friend)
                else:
                    # This one didn't work. Oh well! No easy way to show an error without ruining other accepts
                    pass

        logged_in_author.save()

        return HttpResponseRedirect(reverse("app:friend-requests-list"))


import requests
MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv"
DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv"
MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv"

def get_events(is_iq: bool=False) -> list:
    """Get a list of iq events or edr events.

    Args:
        is_iq: True for vex iq tournaments, False for vex edr(default).

    Returns:
        A 2D array of the events.

    """
    data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1]
    if is_iq:
        return [match.split(",") for match in data if u"re-viqc" in match]
    else:
        return [match.split(",") for match in data if u"re-vrc" in match]

def get_divisions(event_id: str) -> list:
    """Get a list of the divisions of an event.

    Args:
        event_id: The id of the event.

    Returns:
        A 2D array of the divisions.

    """
    data = requests.get(DIVISION_URL.format(event_id)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

def get_matches(event_id: str, division: str) -> list:
    """Get a list of the matches in a divisions of an event.

    Args:
        event_id: The id of the event.
        division: The division id.

    Returns:
        A 2D array of the matches.

    """
    data = requests.get(MATCH_URL.format(
        event_id, division)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

Add comments to vex via wrapper

Add comments to vex via wrapper

Response:
import requests
MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv"
DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv"
MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv"

def get_events(is_iq: bool=False) -> list:
    """Get a list of iq events or edr events.

    Args:
        is_iq: True for vex iq tournaments, False for vex edr(default).

    Returns:
        A 2D array of the events.

    """
    data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1]
    if is_iq:
        return [match.split(",") for match in data if u"re-viqc" in match]
    else:
        return [match.split(",") for match in data if u"re-vrc" in match]

def get_divisions(event_id: str) -> list:
    """Get a list of the divisions of an event.

    Args:
        event_id: The id of the event.

    Returns:
        A 2D array of the divisions.

    """
    data = requests.get(DIVISION_URL.format(event_id)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

def get_matches(event_id: str, division: str) -> list:
    """Get a list of the matches in a divisions of an event.

    Args:
        event_id: The id of the event.
        division: The division id.

    Returns:
        A 2D array of the matches.

    """
    data = requests.get(MATCH_URL.format(
        event_id, division)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

Prompt:
Add comments to vex via wrapper

import requests
MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv"
DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv"
MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv"

def get_events(iq=False):
    data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1]
    if iq:
        return [match.split(",") for match in data if u"re-viqc" in match]
    else:
        return [match.split(",") for match in data if u"re-vrc" in match]

def get_divisions(event_id):
    data = requests.get(DIVISION_URL.format(event_id)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

def get_matches(event_id, division):
    data = requests.get(MATCH_URL.format(
        event_id, division)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]


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

from django.db import migrations

from extra_countries.models import ExtraCountry

def add_currencies_with_countries(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Currency = apps.get_model("currencies", "Currency")

    for extra_country in ExtraCountry.objects.all():
        print("seeding currency for county: %s" % extra_country.country.name)
        # trying to find a currency with the same code first
        try:
            currency = Currency.objects.get(code=extra_country.country.currency)
        except Currency.DoesNotExist: # no such currency yet
            currency = Currency(code=extra_country.country.currency,
                                name=extra_country.country.currency_name)
            if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''):
                pass
            else:
                currency.save()
                currency.countries.add(extra_country.pk)

def reverse_data(apps, schema_editor):
    Currency = apps.get_model("currencies", "Currency")
    Currency.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('currencies', '0002_currency_countries'),
    ]

    operations = [
        migrations.RunPython(add_currencies_with_countries, reverse_data)
    ]

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

from django.db import migrations

from extra_countries.models import ExtraCountry

def add_currencies_with_countries(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Currency = apps.get_model("currencies", "Currency")

    for extra_country in ExtraCountry.objects.all():
        print("seeding currency for county: %s" % extra_country.country.name)
        # trying to find a currency with the same code first
        try:
            currency = Currency.objects.get(code=extra_country.country.currency)
        except Currency.DoesNotExist: # no such currency yet
            currency = Currency(code=extra_country.country.currency,
                                name=extra_country.country.currency_name)
            if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''):
                pass
            else:
                currency.save()
                currency.countries.add(extra_country.pk)

def reverse_data(apps, schema_editor):
    Currency = apps.get_model("currencies", "Currency")
    Currency.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('currencies', '0002_currency_countries'),
    ]

    operations = [
        migrations.RunPython(add_currencies_with_countries, reverse_data)
    ]

Prompt:
Fix currencies seeding, so it won't have empty currencies

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

from django.db import migrations

from extra_countries.models import ExtraCountry

def add_currencies_with_countries(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Currency = apps.get_model("currencies", "Currency")

    for extra_country in ExtraCountry.objects.all():
        print("seeding currency for county: %s" % extra_country.country.name)
        # trying to find a currency with the same code first
        try:
            currency = Currency.objects.get(code=extra_country.country.currency)
        except Currency.DoesNotExist: # no such currency yet
            currency = Currency(code=extra_country.country.currency,
                                name=extra_country.country.currency_name)
            currency.save()
        currency.countries.add(extra_country.pk)

def reverse_data(apps, schema_editor):
    Currency = apps.get_model("currencies", "Currency")
    Currency.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('currencies', '0002_currency_countries'),
    ]

    operations = [
        migrations.RunPython(add_currencies_with_countries, reverse_data)
    ]


Remove a line of debugging code

Remove a line of debugging code

Response:
from __future__ import division # for Python 2.x compatibility
import numpy

class EuclidField(object):
    p = 5.0
    r = 30.0
    @staticmethod
    def dist(x, y):
        return numpy.hypot(x[0]-y[0], x[1]-y[1])
    def __init__(self, size, dst, obstacles):
        w, h = size
        self.shape = (h, w)
        self.dst = dst
        self.obstacles = obstacles
    def __getitem__(self, q):
        i, j = q
        h, w = self.shape
        if not (i in range(h) and j in range(w)):
            raise IndexError
        base = self.dist(q, self.dst)
        k = 0.0
        p = self.p
        for obj in self.obstacles:
            dist_to_obj = self.dist(q, obj)
            if dist_to_obj <= p:
                k += (1/dist_to_obj - 1/p)**2
        return (1.0 + k) * base**2 + self.r*k
    def __array__(self):
        h, w = self.shape
        return numpy.array([[self[i, j] for j in range(w)] for i in range(h)])

Prompt:
Remove a line of debugging code

from __future__ import division # for Python 2.x compatibility
import numpy

class EuclidField(object):
    p = 5.0
    r = 30.0
    @staticmethod
    def dist(x, y):
        return numpy.hypot(x[0]-y[0], x[1]-y[1])
    def __init__(self, size, dst, obstacles):
        w, h = size
        self.shape = (h, w)
        self.dst = dst
        self.obstacles = obstacles
    def __getitem__(self, q):
        i, j = q
        h, w = self.shape
        if not (i in range(h) and j in range(w)):
            raise IndexError
        base = self.dist(q, self.dst)
        k = 0.0
        p = self.p
        for obj in self.obstacles:
            dist_to_obj = self.dist(q, obj)
            if dist_to_obj <= p:
                k += (1/dist_to_obj - 1/p)**2
        return (1.0 + k) * base**2 + self.r*k
    def __array__(self):
        h, w = self.shape
        return numpy.array([[self[i, j] for j in range(w)] for i in range(h)])

f = EuclidField((3, 3), (0, 0), [(1,1)])


import numpy
from thinc.api import HashEmbed

def test_init():
    model = HashEmbed(64, 1000).initialize()
    assert model.get_dim("nV") == 1000
    assert model.get_dim("nO") == 64
    assert model.get_param("E").shape == (1000, 64)

def test_seed_changes_bucket():
    model1 = HashEmbed(64, 1000, seed=2).initialize()
    model2 = HashEmbed(64, 1000, seed=1).initialize()
    arr = numpy.ones((1,), dtype="uint64")
    vector1 = model1.predict(arr)
    vector2 = model2.predict(arr)
    assert vector1.sum() != vector2.sum()

Fix off-by-one in HashEmbed test

Fix off-by-one in HashEmbed test

Response:
import numpy
from thinc.api import HashEmbed

def test_init():
    model = HashEmbed(64, 1000).initialize()
    assert model.get_dim("nV") == 1000
    assert model.get_dim("nO") == 64
    assert model.get_param("E").shape == (1000, 64)

def test_seed_changes_bucket():
    model1 = HashEmbed(64, 1000, seed=2).initialize()
    model2 = HashEmbed(64, 1000, seed=1).initialize()
    arr = numpy.ones((1,), dtype="uint64")
    vector1 = model1.predict(arr)
    vector2 = model2.predict(arr)
    assert vector1.sum() != vector2.sum()

Prompt:
Fix off-by-one in HashEmbed test

import numpy
from thinc.api import HashEmbed

def test_init():
    model = HashEmbed(64, 1000).initialize()
    assert model.get_dim("nV") == 1000
    assert model.get_dim("nO") == 64
    assert model.get_param("E").shape == (1001, 64)

def test_seed_changes_bucket():
    model1 = HashEmbed(64, 1000, seed=2).initialize()
    model2 = HashEmbed(64, 1000, seed=1).initialize()
    arr = numpy.ones((1,), dtype="uint64")
    vector1 = model1.predict(arr)
    vector2 = model2.predict(arr)
    assert vector1.sum() != vector2.sum()


#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.4',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely',
                        'psycopg2',
                        'keyrings.alt',
                        'pandas >=0.19.1, <=0.19.1'])

Add pandas as required package

Add pandas as required package

Response:
#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.4',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely',
                        'psycopg2',
                        'keyrings.alt',
                        'pandas >=0.19.1, <=0.19.1'])

Prompt:
Add pandas as required package

#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.4',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely',
                        'psycopg2',
                        'keyrings.alt'])


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
uData
'''
from __future__ import unicode_literals

__version__ = '1.6.0.dev'
__description__ = 'Open data portal'

Set base version to 1.6

Set base version to 1.6

Response:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
uData
'''
from __future__ import unicode_literals

__version__ = '1.6.0.dev'
__description__ = 'Open data portal'

Prompt:
Set base version to 1.6

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
uData
'''
from __future__ import unicode_literals

__version__ = '1.5.1.dev'
__description__ = 'Open data portal'


packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []

class packetHook(object):
	def __init__(self, pktType, pktSubtype):
		self.pktType = pktType
		self.pktSubtype = pktSubtype

	def __call__(self, f):
		global packetFunctions
		if (self.pktType, self.pktSubtype) not in packetFunctions:
			packetFunctions[(self.pktType, self.pktSubtype)] = []
		packetFunctions[(self.pktType, self.pktSubtype)].append(f)

class commandHook(object):
	"""docstring for commandHook"""
	def __init__(self, command):
		self.command = command

	def __call__(self, f):
		global commands
		commands[self.command] = f

def onStartHook(f):
	global onStart
	onStart.append(f)
	return f

def onConnectionHook(f):
	global onConnection
	onConnection.append(f)
	return f

def onConnectionLossHook(f):
	global onConnectionLoss
	onConnectionLoss.append(f)
	return f

Allow mutiple hooks for packets

Allow mutiple hooks for packets

Response:
packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []

class packetHook(object):
	def __init__(self, pktType, pktSubtype):
		self.pktType = pktType
		self.pktSubtype = pktSubtype

	def __call__(self, f):
		global packetFunctions
		if (self.pktType, self.pktSubtype) not in packetFunctions:
			packetFunctions[(self.pktType, self.pktSubtype)] = []
		packetFunctions[(self.pktType, self.pktSubtype)].append(f)

class commandHook(object):
	"""docstring for commandHook"""
	def __init__(self, command):
		self.command = command

	def __call__(self, f):
		global commands
		commands[self.command] = f

def onStartHook(f):
	global onStart
	onStart.append(f)
	return f

def onConnectionHook(f):
	global onConnection
	onConnection.append(f)
	return f

def onConnectionLossHook(f):
	global onConnectionLoss
	onConnectionLoss.append(f)
	return f

Prompt:
Allow mutiple hooks for packets

packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []

class packetHook(object):
	def __init__(self, pktType, pktSubtype):
		self.pktType = pktType
		self.pktSubtype = pktSubtype

	def __call__(self, f):
		global packetFunctions
		packetFunctions[(self.pktType, self.pktSubtype)] = f

class commandHook(object):
	"""docstring for commandHook"""
	def __init__(self, command):
		self.command = command

	def __call__(self, f):
		global commands
		commands[self.command] = f

def onStartHook(f):
	global onStart
	onStart.append(f)
	return f

def onConnectionHook(f):
	global onConnection
	onConnection.append(f)
	return f

def onConnectionLossHook(f):
	global onConnectionLoss
	onConnectionLoss.append(f)
	return f


#!/usr/bin/env python
from __future__ import print_function

from stompy.spatial import join_features
from optparse import OptionParser

try:
    from osgeo import ogr
except ImportError:
    import ogr

# # How to use this:
# ### Load shapefile
# ods = ogr.Open("/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped.shp")
# output = "/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped-merged.shp"
# orig_layer = ods.GetLayer(0)
# ## process it
# process_layer(orig_layer,output)

if __name__ == '__main__':

    parser = OptionParser(usage="usage: %prog [options] input.shp output.shp")
    parser.add_option("-p", "--poly",
                      help="create polygons from closed linestrings",
                      action="store_true",
                      dest='create_polygons',default=False)
    parser.add_option("-a", "--arc", dest="close_arc", default=False,
                      action="store_true",
                      help="close the largest open linestring with a circular arc")
    parser.add_option("-t","--tolerance", dest="tolerance", type="float", default=0.0,
                      metavar="DISTANCE",
                      help="Tolerance for joining two endpoints, in geographic units")
    parser.add_option("-m","--multiple", dest="single_feature", default=True,
                      action="store_false",metavar="SINGLE_FEATURE")

    (options, args) = parser.parse_args()
    input_shp,output_shp = args

    ods = ogr.Open(input_shp)
    layer = ods.GetLayer(0)

    join_features.process_layer(layer,output_shp,
                                create_polygons=options.create_polygons,close_arc=options.close_arc,
                                tolerance=options.tolerance,single_feature=options.single_feature)

Add CLI for joining lines to polygons

Add CLI for joining lines to polygons

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

from stompy.spatial import join_features
from optparse import OptionParser

try:
    from osgeo import ogr
except ImportError:
    import ogr

# # How to use this:
# ### Load shapefile
# ods = ogr.Open("/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped.shp")
# output = "/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped-merged.shp"
# orig_layer = ods.GetLayer(0)
# ## process it
# process_layer(orig_layer,output)

if __name__ == '__main__':

    parser = OptionParser(usage="usage: %prog [options] input.shp output.shp")
    parser.add_option("-p", "--poly",
                      help="create polygons from closed linestrings",
                      action="store_true",
                      dest='create_polygons',default=False)
    parser.add_option("-a", "--arc", dest="close_arc", default=False,
                      action="store_true",
                      help="close the largest open linestring with a circular arc")
    parser.add_option("-t","--tolerance", dest="tolerance", type="float", default=0.0,
                      metavar="DISTANCE",
                      help="Tolerance for joining two endpoints, in geographic units")
    parser.add_option("-m","--multiple", dest="single_feature", default=True,
                      action="store_false",metavar="SINGLE_FEATURE")

    (options, args) = parser.parse_args()
    input_shp,output_shp = args

    ods = ogr.Open(input_shp)
    layer = ods.GetLayer(0)

    join_features.process_layer(layer,output_shp,
                                create_polygons=options.create_polygons,close_arc=options.close_arc,
                                tolerance=options.tolerance,single_feature=options.single_feature)

Prompt: Add CLI for joining lines to polygons


from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile

class UserProfileForm(ModelForm):
    first_name = CharField(label='First name', required=False)
    last_name = CharField(label='Last name', required=False)

    class Meta:
        model = UserProfile
        # Don't allow users edit someone else's user page,
        # or to whitelist themselves
        exclude = ('user', 'whitelisted',)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.is_bound:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name

    def save(self):
        first_name = self.cleaned_data.pop('first_name', None)
        last_name = self.cleaned_data.pop('last_name', None)
        profile = super(UserProfileForm, self).save()
        user = profile.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return profile

Response:
from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile

class UserProfileForm(ModelForm):
    first_name = CharField(label='First name', required=False)
    last_name = CharField(label='Last name', required=False)

    class Meta:
        model = UserProfile
        # Don't allow users edit someone else's user page,
        # or to whitelist themselves
        exclude = ('user', 'whitelisted',)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.is_bound:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name

    def save(self):
        first_name = self.cleaned_data.pop('first_name', None)
        last_name = self.cleaned_data.pop('last_name', None)
        profile = super(UserProfileForm, self).save()
        user = profile.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return profile

Prompt:
Fix profile creation. (Need tests badly).
from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile

class UserProfileForm(ModelForm):
    first_name = CharField(label='First name', required=False)
    last_name = CharField(label='Last name', required=False)

    class Meta:
        model = UserProfile
        # Don't allow users edit someone else's user page,
        # or to whitelist themselves
        exclude = ('user', 'whitelisted',)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name

    def save(self):
        first_name = self.cleaned_data.pop('first_name', None)
        last_name = self.cleaned_data.pop('last_name', None)
        profile = super(UserProfileForm, self).save()
        user = profile.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return profile


from setuptools import find_packages, setup

import versioneer

setup(
    name="bmipy",
    version=versioneer.get_version(),
    description="Basic Model Interface for Python",
    author="Eric Hutton",
    author_email="huttone@colorado.edu",
    url="http://csdms.colorado.edu",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Physics",
    ],
    setup_requires=["setuptools"],
    install_requires=["numpy"],
    packages=find_packages(),
    cmdclass=versioneer.get_cmdclass(),
)

Add numpy as an install requirement.

Add numpy as an install requirement.

Response:
from setuptools import find_packages, setup

import versioneer

setup(
    name="bmipy",
    version=versioneer.get_version(),
    description="Basic Model Interface for Python",
    author="Eric Hutton",
    author_email="huttone@colorado.edu",
    url="http://csdms.colorado.edu",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Physics",
    ],
    setup_requires=["setuptools"],
    install_requires=["numpy"],
    packages=find_packages(),
    cmdclass=versioneer.get_cmdclass(),
)

Prompt:
Add numpy as an install requirement.

from setuptools import find_packages, setup

import versioneer

setup(
    name="bmipy",
    version=versioneer.get_version(),
    description="Basic Model Interface for Python",
    author="Eric Hutton",
    author_email="huttone@colorado.edu",
    url="http://csdms.colorado.edu",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Physics",
    ],
    setup_requires=["setuptools"],
    packages=find_packages(),
    cmdclass=versioneer.get_cmdclass(),
)