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

import unittest2

from st2common.models.db.pack import PackDB
from st2common.models.db.sensor import SensorTypeDB
from st2common.models.db.action import ActionDB
from st2common.models.db.rule import RuleDB
from st2common.models.db.trigger import TriggerTypeDB
from st2common.models.db.trigger import TriggerDB

__all__ = [
    'DBModelUIDFieldTestCase'
]

class DBModelUIDFieldTestCase(unittest2.TestCase):
    def test_get_uid(self):
        pack_db = PackDB(ref='ma_pack')
        self.assertEqual(pack_db.get_uid(), 'pack:ma_pack')

        sensor_type_db = SensorTypeDB(name='sname', pack='spack')
        self.assertEqual(sensor_type_db.get_uid(), 'sensor_type:spack:sname')

        action_db = ActionDB(name='aname', pack='apack', runner_info={})
        self.assertEqual(action_db.get_uid(), 'action:apack:aname')

        rule_db = RuleDB(name='rname', pack='rpack')
        self.assertEqual(rule_db.get_uid(), 'rule:rpack:rname')

        trigger_type_db = TriggerTypeDB(name='ttname', pack='ttpack')
        self.assertEqual(trigger_type_db.get_uid(), 'trigger_type:ttpack:ttname')

        trigger_db = TriggerDB(name='tname', pack='tpack')
        self.assertTrue(trigger_db.get_uid().startswith('trigger:tpack:tname:'))

Add tests for get_uid() method for common DB models.

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

import unittest2

from st2common.models.db.pack import PackDB
from st2common.models.db.sensor import SensorTypeDB
from st2common.models.db.action import ActionDB
from st2common.models.db.rule import RuleDB
from st2common.models.db.trigger import TriggerTypeDB
from st2common.models.db.trigger import TriggerDB

__all__ = [
    'DBModelUIDFieldTestCase'
]

class DBModelUIDFieldTestCase(unittest2.TestCase):
    def test_get_uid(self):
        pack_db = PackDB(ref='ma_pack')
        self.assertEqual(pack_db.get_uid(), 'pack:ma_pack')

        sensor_type_db = SensorTypeDB(name='sname', pack='spack')
        self.assertEqual(sensor_type_db.get_uid(), 'sensor_type:spack:sname')

        action_db = ActionDB(name='aname', pack='apack', runner_info={})
        self.assertEqual(action_db.get_uid(), 'action:apack:aname')

        rule_db = RuleDB(name='rname', pack='rpack')
        self.assertEqual(rule_db.get_uid(), 'rule:rpack:rname')

        trigger_type_db = TriggerTypeDB(name='ttname', pack='ttpack')
        self.assertEqual(trigger_type_db.get_uid(), 'trigger_type:ttpack:ttname')

        trigger_db = TriggerDB(name='tname', pack='tpack')
        self.assertTrue(trigger_db.get_uid().startswith('trigger:tpack:tname:'))

Prompt: Add tests for get_uid() method for common DB models.


import numpy as np
from sklearn.decomposition import PCA

def measureLength(pointCloud):
    """Returns the length of a point cloud in its longest direction."""

    if len(pointCloud) == 0:
        return 0

    pca = PCA(n_components = 1)
    pc_array = np.asarray(pointCloud)
    pca.fit(pc_array)
    primary_axis = np.dot(pc_array, np.transpose(pca.components_))[:,0]
    return np.max(primary_axis) - np.min(primary_axis)

Response:
import numpy as np
from sklearn.decomposition import PCA

def measureLength(pointCloud):
    """Returns the length of a point cloud in its longest direction."""

    if len(pointCloud) == 0:
        return 0

    pca = PCA(n_components = 1)
    pc_array = np.asarray(pointCloud)
    pca.fit(pc_array)
    primary_axis = np.dot(pc_array, np.transpose(pca.components_))[:,0]
    return np.max(primary_axis) - np.min(primary_axis)

Prompt:
Make sure np.array is used for PCA in measureLength

import numpy as np
from sklearn.decomposition import PCA

def measureLength(pointCloud):
    """Returns the length of a point cloud in its longest direction."""

    if len(pointCloud) == 0:
        return 0

    pca = PCA(n_components = 1)
    pca.fit(np.asarray(pointCloud))
    primary_axis = np.dot(pointCloud, np.transpose(pca.components_))[:,0]
    return np.max(primary_axis) - np.min(primary_axis)


from django.core.management import BaseCommand

from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new
from corehq.util.es.elasticsearch import IndicesClient

class Command(BaseCommand):
    """
    Wipe all data from BlobDB.
    """
    def add_arguments(self, parser):
        parser.add_argument(
            '--commit',
            action='store_true',
            dest='commit',
            default=False,
        )

    def handle(self, *args, **options):
        confirm_destructive_operation()

        data = wipe_es(options['commit'])

        if data:
            print(data)
        if not options['commit']:
            print("You need to run with --commit for the deletion to happen.")

def wipe_es(commit=False):
    """
    The equivalent of calling ::

        $ curl -X DELETE "$PROTO://$HOSTNAME:$PORT/_all"
    """
    es = get_es_new()
    client = IndicesClient(es)
    if commit:
        client.delete('_all')

Use IndicesClient to get full URL

Use IndicesClient to get full URL

Response:
from django.core.management import BaseCommand

from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new
from corehq.util.es.elasticsearch import IndicesClient

class Command(BaseCommand):
    """
    Wipe all data from BlobDB.
    """
    def add_arguments(self, parser):
        parser.add_argument(
            '--commit',
            action='store_true',
            dest='commit',
            default=False,
        )

    def handle(self, *args, **options):
        confirm_destructive_operation()

        data = wipe_es(options['commit'])

        if data:
            print(data)
        if not options['commit']:
            print("You need to run with --commit for the deletion to happen.")

def wipe_es(commit=False):
    """
    The equivalent of calling ::

        $ curl -X DELETE "$PROTO://$HOSTNAME:$PORT/_all"
    """
    es = get_es_new()
    client = IndicesClient(es)
    if commit:
        client.delete('_all')

Prompt:
Use IndicesClient to get full URL

from django.core.management import BaseCommand

from corehq.apps.cleanup.utils import confirm_destructive_operation
from corehq.elastic import get_es_new

class Command(BaseCommand):
    """
    Wipe all data from BlobDB.
    """
    def add_arguments(self, parser):
        parser.add_argument(
            '--commit',
            action='store_true',
            dest='commit',
            default=False,
        )

    def handle(self, *args, **options):
        confirm_destructive_operation()

        data = wipe_es(options['commit'])

        if data:
            print(data)
        if not options['commit']:
            print("You need to run with --commit for the deletion to happen.")

def wipe_es(commit=False):
    """
    The equivalent of calling ::

        $ curl -X DELETE "$PROTO://$HOSTNAME:$PORT/_all"
    """
    es = get_es_new()
    if commit:
        return es.transport.perform_request('DELETE', '_all')


import numpy as np

def get_leftside_average(self):
    """Return the value of the Average of the left_most_points."""
    width = self.size[0]
    height = self.size[1]
    left_most_points = []
    for row in range(height):
        for column in range(width):
            if image.getpixel(row, column) > 200:
                left_most_points.append(row)
                break

    return np.median(left_most_points)

def get_rightside_average(self):
    """Return the value of the average of the right_most_points."""
    width = self.size[0]
    height = self.size[1]
    right_most_points = []
    for row in range(height):
        for column in range(width, -1, -1):     #Indices moving right to left
            if image.getpixel(row column) > 200:
                right_most_points.append(row)
                break

    return np.median(right_most_points)

Add get_rightside_face and Fix bug

Add get_rightside_face and Fix bug

Response:
import numpy as np

def get_leftside_average(self):
    """Return the value of the Average of the left_most_points."""
    width = self.size[0]
    height = self.size[1]
    left_most_points = []
    for row in range(height):
        for column in range(width):
            if image.getpixel(row, column) > 200:
                left_most_points.append(row)
                break

    return np.median(left_most_points)

def get_rightside_average(self):
    """Return the value of the average of the right_most_points."""
    width = self.size[0]
    height = self.size[1]
    right_most_points = []
    for row in range(height):
        for column in range(width, -1, -1):     #Indices moving right to left
            if image.getpixel(row column) > 200:
                right_most_points.append(row)
                break

    return np.median(right_most_points)

Prompt:
Add get_rightside_face and Fix bug

import numpy as np

def get_leftside_average(self):
    """Return Array of Left Most Points."""
    width = self.size[0]
    height = self.size[1]
    left_most_points = []
    for row in range(height):
        for column in range(width):
            if image.getpixel(row, column) > 200:
                left_most_points.append(column)
                break

    return np.median(left_most_points)


#!/usr/bin/env python3

from os import curdir, pardir
from os.path import join
from distutils.core import setup
from Cython.Distutils import Extension, build_ext

setup(
    name = "VapourSynth",
    description = "A frameserver for the 21st century",
    url = "http://www.vapoursynth.com/",
    download_url = "http://code.google.com/p/vapoursynth/",
    author = "Fredrik Mellbin",
    author_email = "fredrik.mellbin@gmail.com",
    license = "LGPL 2.1 or later",
    version = "1.0.0",
    long_description = "A portable replacement for Avisynth",
    platforms = "All",
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("vapoursynth", [join("src", "cython", "vapoursynth.pyx")],
                             libraries = ["vapoursynth"],
                             library_dirs = [curdir, "build"],
                             include_dirs = [curdir, join("src", "cython")],
                             cython_c_in_temp = 1)]
)

Response:
#!/usr/bin/env python3

from os import curdir, pardir
from os.path import join
from distutils.core import setup
from Cython.Distutils import Extension, build_ext

setup(
    name = "VapourSynth",
    description = "A frameserver for the 21st century",
    url = "http://www.vapoursynth.com/",
    download_url = "http://code.google.com/p/vapoursynth/",
    author = "Fredrik Mellbin",
    author_email = "fredrik.mellbin@gmail.com",
    license = "LGPL 2.1 or later",
    version = "1.0.0",
    long_description = "A portable replacement for Avisynth",
    platforms = "All",
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("vapoursynth", [join("src", "cython", "vapoursynth.pyx")],
                             libraries = ["vapoursynth"],
                             library_dirs = [curdir, "build"],
                             include_dirs = [curdir, join("src", "cython")],
                             cython_c_in_temp = 1)]
)

Prompt:
Use the Cython Extension class so we can place generated C files in the build dir.

git-svn-id: ac1113e4705722bd5ee69cef058b32c421e857b8@491 f9120d27-2007-6f97-8312-0f4ebfa7710f

#!/usr/bin/env python3

from os import curdir, pardir
from os.path import join
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
    name = "VapourSynth",
    description = "A frameserver for the 21st century",
    url = "http://www.vapoursynth.com/",
    download_url = "http://code.google.com/p/vapoursynth/",
    author = "Fredrik Mellbin",
    author_email = "fredrik.mellbin@gmail.com",
    license = "LGPL 2.1 or later",
    version = "1.0.0",
    long_description = "A portable replacement for Avisynth",
    platforms = "All",
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("vapoursynth", [join("src", "cython", "vapoursynth.pyx")],
                             libraries = ["vapoursynth"],
                             library_dirs = [curdir, "build"],
                             include_dirs = [curdir, join("src", "cython")])]
)


# -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import django
from django.conf import settings

INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
    'modeltranslation.tests',
)

LANGUAGES = (('de', 'Deutsch'),
             ('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'de'

USE_I18N = True
USE_TZ = False
MIDDLEWARE_CLASSES = ()

MODELTRANSLATION_AUTO_POPULATE = False
MODELTRANSLATION_FALLBACK_LANGUAGES = ()

ROOT_URLCONF = 'modeltranslation.tests.urls'

if django.VERSION < (1, 11):
    # TODO: Check what this was about
    MIGRATION_MODULES = {'auth': 'modeltranslation.tests.auth_migrations'}
else:
    MIGRATION_MODULES = {}

Response:
# -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import django
from django.conf import settings

INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
    'modeltranslation.tests',
)

LANGUAGES = (('de', 'Deutsch'),
             ('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'de'

USE_I18N = True
USE_TZ = False
MIDDLEWARE_CLASSES = ()

MODELTRANSLATION_AUTO_POPULATE = False
MODELTRANSLATION_FALLBACK_LANGUAGES = ()

ROOT_URLCONF = 'modeltranslation.tests.urls'

if django.VERSION < (1, 11):
    # TODO: Check what this was about
    MIGRATION_MODULES = {'auth': 'modeltranslation.tests.auth_migrations'}
else:
    MIGRATION_MODULES = {}

Prompt:
Set empty MIGRATION_MODULES setting for Django 1.11. Should make the tests run again.

# -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
from django.conf import settings

INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
    'modeltranslation.tests',
)

LANGUAGES = (('de', 'Deutsch'),
             ('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'de'

USE_I18N = True
USE_TZ = False
MIDDLEWARE_CLASSES = ()

MODELTRANSLATION_AUTO_POPULATE = False
MODELTRANSLATION_FALLBACK_LANGUAGES = ()

ROOT_URLCONF = 'modeltranslation.tests.urls'

MIGRATION_MODULES = {'auth': 'modeltranslation.tests.auth_migrations'}


import os

from setuptools import setup, find_packages

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

requires = [
        'oauth2client',
        'google-api-python-client',
    ]

tests_require = []

testing_requires =  tests_require + [
    'nose',
    'coverage',
    ]

develop_requires = [
    ]

setup(name='acctwatch',
      version='0.0',
      description='acctwatch',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        ],
      author='Bert JW Regeer',
      author_email='bertjw@regeer.org',
      url='',
      keywords='',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='acctwatch.tests',
      install_requires=requires,
      tests_require=tests_require,
      extras_require = {
          'develop': develop_requires,
          'testing': testing_requires,
          },
      entry_points="""\
      [console_scripts]
      acctwatch = acctwatch.acctwatch:main
      """,
      )

Response:
import os

from setuptools import setup, find_packages

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

requires = [
        'oauth2client',
        'google-api-python-client',
    ]

tests_require = []

testing_requires =  tests_require + [
    'nose',
    'coverage',
    ]

develop_requires = [
    ]

setup(name='acctwatch',
      version='0.0',
      description='acctwatch',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        ],
      author='Bert JW Regeer',
      author_email='bertjw@regeer.org',
      url='',
      keywords='',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='acctwatch.tests',
      install_requires=requires,
      tests_require=tests_require,
      extras_require = {
          'develop': develop_requires,
          'testing': testing_requires,
          },
      entry_points="""\
      [console_scripts]
      acctwatch = acctwatch.acctwatch:main
      """,
      )

Prompt:
Add the Google API client as a requirement

import os

from setuptools import setup, find_packages

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

requires = [
        'oauth2client',
    ]

tests_require = []

testing_requires =  tests_require + [
    'nose',
    'coverage',
    ]

develop_requires = [
    ]

setup(name='acctwatch',
      version='0.0',
      description='acctwatch',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        ],
      author='Bert JW Regeer',
      author_email='bertjw@regeer.org',
      url='',
      keywords='',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='acctwatch.tests',
      install_requires=requires,
      tests_require=tests_require,
      extras_require = {
          'develop': develop_requires,
          'testing': testing_requires,
          },
      entry_points="""\
      [console_scripts]
      acctwatch = acctwatch.acctwatch:main
      """,
      )


''' Tests for BaseUtils
'''
import unittest
import sys
sys.path.append('../src')
import BaseUtils

class TestBaseUtils(unittest.TestCase):
    ''' Main test class for the BaseUtils '''
    def test_word_segmenter_with_empty(self):
        ''' For an empty string, the segmenter returns
        just an empty list '''
        segments = BaseUtils.get_words('')
        self.assertEqual(segments, [])

    def test_word_segmenter(self):
        ''' The word segmenter returns the expected
        array of strings '''
        segments = BaseUtils.get_words('this is a random sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

    def test_ignoring_whitespace(self):
        ''' Whitespace in the input string is ignored
        in the input string '''
        segments = BaseUtils.get_words('this   is   a random sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

    def test_ignoring_special_chars(self):
        ''' If there are special characters in the input,
        they are ignored as well '''
        segments = BaseUtils.get_words('this   is   $$%%a random --00sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

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

Add test for empty string; cleanup

Add test for empty string; cleanup

Response:
''' Tests for BaseUtils
'''
import unittest
import sys
sys.path.append('../src')
import BaseUtils

class TestBaseUtils(unittest.TestCase):
    ''' Main test class for the BaseUtils '''
    def test_word_segmenter_with_empty(self):
        ''' For an empty string, the segmenter returns
        just an empty list '''
        segments = BaseUtils.get_words('')
        self.assertEqual(segments, [])

    def test_word_segmenter(self):
        ''' The word segmenter returns the expected
        array of strings '''
        segments = BaseUtils.get_words('this is a random sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

    def test_ignoring_whitespace(self):
        ''' Whitespace in the input string is ignored
        in the input string '''
        segments = BaseUtils.get_words('this   is   a random sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

    def test_ignoring_special_chars(self):
        ''' If there are special characters in the input,
        they are ignored as well '''
        segments = BaseUtils.get_words('this   is   $$%%a random --00sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

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

Prompt:
Add test for empty string; cleanup

import unittest
import sys
sys.path.append('../src')
import BaseUtils

class TestBaseUtils(unittest.TestCase):
    def test_word_segmenter(self):
        segments = BaseUtils.get_words('this is a random sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

    def test_word_segmenter_ignores_whitespace(self):
        segments = BaseUtils.get_words('this   is   a random sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

    def test_word_segmenter_ignores_special_chars(self):
        segments = BaseUtils.get_words('this   is   $$%%a random --00sentence')
        self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])

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


from django.contrib.contenttypes.models import ContentType

# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################

# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs):
    """
    Creates a content instance from a content plugin class.

    :param content_plugin_class: The class of the content plugin.
    :param test_page: The fluent_page instance to create the content
    instance one.
    :param placeholder_name: The placeholder name defined in the
    template. [DEFAULT: main]
    :param kwargs: Additional keyword arguments to be used in the
    content instance creation.
    :return: The content instance created.
    """
    # Get the placeholders that are currently available for the slot.
    placeholders = test_page.get_placeholder_by_slot(placeholder_name)

    # If a placeholder exists for the placeholder_name use the first one provided otherwise create
    # a new placeholder instance.
    if placeholders.exists():
        placeholder = placeholders[0]
    else:
        placeholder = test_page.create_placeholder(placeholder_name)

    # Obtain the content type for the page instance class.
    ct = ContentType.objects.get_for_model(type(test_page))

    # Create the actual plugin instance.
    content_instance = content_plugin_class.objects.create(
        parent_type=ct,
        parent_id=test_page.id,
        placeholder=placeholder,
        **kwargs
    )
    return content_instance

# END Fluent Contents Helper Functions #############################################################

Response:
from django.contrib.contenttypes.models import ContentType

# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################

# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs):
    """
    Creates a content instance from a content plugin class.

    :param content_plugin_class: The class of the content plugin.
    :param test_page: The fluent_page instance to create the content
    instance one.
    :param placeholder_name: The placeholder name defined in the
    template. [DEFAULT: main]
    :param kwargs: Additional keyword arguments to be used in the
    content instance creation.
    :return: The content instance created.
    """
    # Get the placeholders that are currently available for the slot.
    placeholders = test_page.get_placeholder_by_slot(placeholder_name)

    # If a placeholder exists for the placeholder_name use the first one provided otherwise create
    # a new placeholder instance.
    if placeholders.exists():
        placeholder = placeholders[0]
    else:
        placeholder = test_page.create_placeholder(placeholder_name)

    # Obtain the content type for the page instance class.
    ct = ContentType.objects.get_for_model(type(test_page))

    # Create the actual plugin instance.
    content_instance = content_plugin_class.objects.create(
        parent_type=ct,
        parent_id=test_page.id,
        placeholder=placeholder,
        **kwargs
    )
    return content_instance

# END Fluent Contents Helper Functions #############################################################

Prompt:
Change argument name to stop probable name clash.

from django.contrib.contenttypes.models import ContentType

# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################

# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs):
    """
    Creates a content instance from a content plugin class.

    :param content_plugin_class: The class of the content plugin.
    :param page: The fluent_page instance to create the content
    instance one.
    :param placeholder_name: The placeholder name defined in the
    template. [DEFAULT: main]
    :param kwargs: Additional keyword arguments to be used in the
    content instance creation.
    :return: The content instance created.
    """
    # Get the placeholders that are currently available for the slot.
    placeholders = page.get_placeholder_by_slot(placeholder_name)

    # If a placeholder exists for the placeholder_name use the first one provided otherwise create
    # a new placeholder instance.
    if placeholders.exists():
        placeholder = placeholders[0]
    else:
        placeholder = page.create_placeholder(placeholder_name)

    # Obtain the content type for the page instance class.
    ct = ContentType.objects.get_for_model(type(page))

    # Create the actual plugin instance.
    content_instance = content_plugin_class.objects.create(
        parent_type=ct,
        parent_id=page.id,
        placeholder=placeholder,
        **kwargs
    )
    return content_instance

# END Fluent Contents Helper Functions #############################################################


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

from optparse import make_option
from optparse import OptionParser

from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS

class VcsCommand(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            "-u",
            "--url",
            dest="url",
            help='Clone URL, it can be SSH or HTTPS. Git only for now.',
            metavar="REPO_URL"
        ),

        make_option(
            "-t",
            "--target",
            dest="target",
            default='.',
            help="Target directory where the repo will be cloned.",
            metavar="TARGET"
        ),
    )

    help = 'Command to clone github repos'

    def run(self, *args, **options):
        url = options.get('url')
        tgt = options.get('target')

        boot = VCS(url)
        boot.clone(target_dir=tgt)

Remove __init__ method, not needed.

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

from optparse import make_option
from optparse import OptionParser

from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS

class VcsCommand(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            "-u",
            "--url",
            dest="url",
            help='Clone URL, it can be SSH or HTTPS. Git only for now.',
            metavar="REPO_URL"
        ),

        make_option(
            "-t",
            "--target",
            dest="target",
            default='.',
            help="Target directory where the repo will be cloned.",
            metavar="TARGET"
        ),
    )

    help = 'Command to clone github repos'

    def run(self, *args, **options):
        url = options.get('url')
        tgt = options.get('target')

        boot = VCS(url)
        boot.clone(target_dir=tgt)

Prompt:
VcsCommand: Remove __init__ method, not needed.

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

from optparse import make_option
from optparse import OptionParser

from scaffolder.core.commands import BaseCommand
from scaffolder.vcs import VCS

class VcsCommand(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            "-u",
            "--url",
            dest="url",
            help='Clone URL, it can be SSH or HTTPS. Git only for now.',
            metavar="REPO_URL"
        ),

        make_option(
            "-t",
            "--target",
            dest="target",
            default='.',
            help="Target directory where the repo will be cloned.",
            metavar="TARGET"
        ),
    )

    def __init__(self, name, help='', aliases=(), stdout=None, stderr=None):
        help = 'Command to clone github repos'
        aliases = ('git','hg',)
        #TODO: Move to BaseCommand, create methods and have each subcommand override
        parser = OptionParser(
            version=self.get_version(),
            option_list=self.get_option_list(),
            usage='\n  %prog {0} [OPTIONS] FILE...'.format(name),
            description='',
            epilog=''

        )
        BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases)
        # self.update_parser()

    def update_parser(self):
        self.parser.set_usage('%prog [OPTIONS] FILE...')
        # self.parser.prog = '%s %s' % (self.parser.get_prog_name(), self.name)
        self.parser.version = self.get_version()
        self.parser.option_list = sorted(self.get_option_list())

    def run(self, *args, **options):
        url = options.get('url')
        tgt = options.get('target')

        boot = VCS(url)
        boot.clone(target_dir=tgt)


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

setup(
    name='django-oscar-fancypages',
    version=":versiontools:fancypages:",
    url='https://github.com/tangentlabs/django-oscar-fancypages',
    author="Sebastian Vetter",
    author_email="sebastian.vetter@tangentsnowball.com.au",
    description="Adding fancy CMS-style pages to Oscar",
    long_description=open('README.rst').read(),
    keywords="django, oscar, e-commerce, cms, pages, flatpages",
    license='BSD',
    platforms=['linux'],
    packages=find_packages(exclude=["sandbox*", "tests*"]),
    include_package_data=True,
    install_requires=[
        'versiontools>=1.9.1',
        'Django>=1.4.2',
        'django-oscar>=0.3',
        'django-model-utils>=1.1.0',
        'django-compressor>=1.2',
    ],
    dependency_links=[
        'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4'
    ],
    # See http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
      'Environment :: Web Environment',
      'Intended Audience :: Developers',
      #'License :: OSI Approved :: BSD License',
      'Operating System :: Unix',
      'Programming Language :: Python'
    ]
)

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

setup(
    name='django-oscar-fancypages',
    version=":versiontools:fancypages:",
    url='https://github.com/tangentlabs/django-oscar-fancypages',
    author="Sebastian Vetter",
    author_email="sebastian.vetter@tangentsnowball.com.au",
    description="Adding fancy CMS-style pages to Oscar",
    long_description=open('README.rst').read(),
    keywords="django, oscar, e-commerce, cms, pages, flatpages",
    license='BSD',
    platforms=['linux'],
    packages=find_packages(exclude=["sandbox*", "tests*"]),
    include_package_data=True,
    install_requires=[
        'versiontools>=1.9.1',
        'Django>=1.4.2',
        'django-oscar>=0.3',
        'django-model-utils>=1.1.0',
        'django-compressor>=1.2',
    ],
    dependency_links=[
        'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4'
    ],
    # See http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
      'Environment :: Web Environment',
      'Intended Audience :: Developers',
      #'License :: OSI Approved :: BSD License',
      'Operating System :: Unix',
      'Programming Language :: Python'
    ]
)

Prompt:
Update django to use latest security release

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

setup(
    name='django-oscar-fancypages',
    version=":versiontools:fancypages:",
    url='https://github.com/tangentlabs/django-oscar-fancypages',
    author="Sebastian Vetter",
    author_email="sebastian.vetter@tangentsnowball.com.au",
    description="Adding fancy CMS-style pages to Oscar",
    long_description=open('README.rst').read(),
    keywords="django, oscar, e-commerce, cms, pages, flatpages",
    license='BSD',
    platforms=['linux'],
    packages=find_packages(exclude=["sandbox*", "tests*"]),
    include_package_data=True,
    install_requires=[
        'versiontools>=1.9.1',
        'Django>=1.4.1',
        'django-oscar>=0.3',
        'django-model-utils>=1.1.0',
        'django-compressor>=1.2',
    ],
    dependency_links=[
        'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4'
    ],
    # See http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
      'Environment :: Web Environment',
      'Intended Audience :: Developers',
      #'License :: OSI Approved :: BSD License',
      'Operating System :: Unix',
      'Programming Language :: Python'
    ]
)


import unittest

from . import models
from sir.schema.searchentities import SearchEntity as E, SearchField as F

class QueryResultToDictTest(unittest.TestCase):
    def setUp(self):
        self.entity = E(models.B, [
            F("id", "id"),
            F("c_bar", "c.bar"),
            F("c_bar_trans", "c.bar", transformfunc=lambda v:
                v.union(set(["yay"])))
        ],
            1.1
        )
        self.expected = {
            "id": 1,
            "c_bar": "foo",
            "c_bar_trans": set(["foo", "yay"]),
        }
        c = models.C(id=2, bar="foo")
        self.val = models.B(id=1, c=c)

    def test_fields(self):
        res = self.entity.query_result_to_dict(self.val)
        self.assertDictEqual(self.expected, res)

Add a test for query_result_to_dict

Add a test for query_result_to_dict

Response:
import unittest

from . import models
from sir.schema.searchentities import SearchEntity as E, SearchField as F

class QueryResultToDictTest(unittest.TestCase):
    def setUp(self):
        self.entity = E(models.B, [
            F("id", "id"),
            F("c_bar", "c.bar"),
            F("c_bar_trans", "c.bar", transformfunc=lambda v:
                v.union(set(["yay"])))
        ],
            1.1
        )
        self.expected = {
            "id": 1,
            "c_bar": "foo",
            "c_bar_trans": set(["foo", "yay"]),
        }
        c = models.C(id=2, bar="foo")
        self.val = models.B(id=1, c=c)

    def test_fields(self):
        res = self.entity.query_result_to_dict(self.val)
        self.assertDictEqual(self.expected, res)

Prompt: Add a test for query_result_to_dict


import sqlalchemy as sa
from sqlalchemy_continuum.plugins import PropertyModTrackerPlugin
from tests import TestCase

class TestPropertyModificationsTracking(TestCase):
    plugins = [PropertyModTrackerPlugin]

    def create_models(self):
        class User(self.Model):
            __tablename__ = 'text_item'
            __versioned__ = {
                'base_classes': (self.Model, ),
                'track_property_modifications': True
            }
            id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)

            name = sa.Column(sa.Unicode(255))

            age = sa.Column(sa.Integer)

        self.User = User

    def test_each_column_generates_additional_mod_column(self):
        UserHistory = self.User.__versioned__['class']
        assert 'name_mod' in UserHistory.__table__.c
        column = UserHistory.__table__.c['name_mod']
        assert not column.nullable
        assert isinstance(column.type, sa.Boolean)

    def test_primary_keys_not_included(self):
        UserHistory = self.User.__versioned__['class']
        assert 'id_mod' not in UserHistory.__table__.c

    def test_mod_properties_get_updated(self):
        user = self.User(name=u'John')
        self.session.add(user)
        self.session.commit()

        assert user.versions[-1].name_mod

Add tests for PropertyModTracker plugin

Add tests for PropertyModTracker plugin

Response:
import sqlalchemy as sa
from sqlalchemy_continuum.plugins import PropertyModTrackerPlugin
from tests import TestCase

class TestPropertyModificationsTracking(TestCase):
    plugins = [PropertyModTrackerPlugin]

    def create_models(self):
        class User(self.Model):
            __tablename__ = 'text_item'
            __versioned__ = {
                'base_classes': (self.Model, ),
                'track_property_modifications': True
            }
            id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)

            name = sa.Column(sa.Unicode(255))

            age = sa.Column(sa.Integer)

        self.User = User

    def test_each_column_generates_additional_mod_column(self):
        UserHistory = self.User.__versioned__['class']
        assert 'name_mod' in UserHistory.__table__.c
        column = UserHistory.__table__.c['name_mod']
        assert not column.nullable
        assert isinstance(column.type, sa.Boolean)

    def test_primary_keys_not_included(self):
        UserHistory = self.User.__versioned__['class']
        assert 'id_mod' not in UserHistory.__table__.c

    def test_mod_properties_get_updated(self):
        user = self.User(name=u'John')
        self.session.add(user)
        self.session.commit()

        assert user.versions[-1].name_mod

Prompt: Add tests for PropertyModTracker plugin


import numpy as np

reveal_type(np)  # E: ModuleType

reveal_type(np.char)  # E: ModuleType
reveal_type(np.ctypeslib)  # E: ModuleType
reveal_type(np.emath)  # E: ModuleType
reveal_type(np.fft)  # E: ModuleType
reveal_type(np.lib)  # E: ModuleType
reveal_type(np.linalg)  # E: ModuleType
reveal_type(np.ma)  # E: ModuleType
reveal_type(np.matrixlib)  # E: ModuleType
reveal_type(np.polynomial)  # E: ModuleType
reveal_type(np.random)  # E: ModuleType
reveal_type(np.rec)  # E: ModuleType
reveal_type(np.testing)  # E: ModuleType
reveal_type(np.version)  # E: ModuleType

# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal)  # E: Any

Response:
import numpy as np

reveal_type(np)  # E: ModuleType

reveal_type(np.char)  # E: ModuleType
reveal_type(np.ctypeslib)  # E: ModuleType
reveal_type(np.emath)  # E: ModuleType
reveal_type(np.fft)  # E: ModuleType
reveal_type(np.lib)  # E: ModuleType
reveal_type(np.linalg)  # E: ModuleType
reveal_type(np.ma)  # E: ModuleType
reveal_type(np.matrixlib)  # E: ModuleType
reveal_type(np.polynomial)  # E: ModuleType
reveal_type(np.random)  # E: ModuleType
reveal_type(np.rec)  # E: ModuleType
reveal_type(np.testing)  # E: ModuleType
reveal_type(np.version)  # E: ModuleType

# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal)  # E: Any

Prompt:
TST: Remove `compat` and `core` from the tests

import numpy as np

reveal_type(np)  # E: ModuleType

reveal_type(np.char)  # E: ModuleType
reveal_type(np.compat)  # E: ModuleType
reveal_type(np.core)  # E: ModuleType
reveal_type(np.ctypeslib)  # E: ModuleType
reveal_type(np.emath)  # E: ModuleType
reveal_type(np.fft)  # E: ModuleType
reveal_type(np.lib)  # E: ModuleType
reveal_type(np.linalg)  # E: ModuleType
reveal_type(np.ma)  # E: ModuleType
reveal_type(np.matrixlib)  # E: ModuleType
reveal_type(np.polynomial)  # E: ModuleType
reveal_type(np.random)  # E: ModuleType
reveal_type(np.rec)  # E: ModuleType
reveal_type(np.testing)  # E: ModuleType
reveal_type(np.version)  # E: ModuleType

# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal)  # E: Any


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

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

"""
import matplotlib.pyplot as plt

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

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

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

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

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

plt.show()

Response:
"""
==============
Edge operators
==============

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

"""
import matplotlib.pyplot as plt

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

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

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

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

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

plt.show()

Prompt:
Add short description to edge filter example

import matplotlib.pyplot as plt

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

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

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

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

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

plt.show()


import logging

from flask import (
	Flask,
	render_template,
	abort
)

from glanerbeard.server import Server

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

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

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

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

Use a template to render json.

Use a template to render json.

Response:
import logging

from flask import (
	Flask,
	render_template,
	abort
)

from glanerbeard.server import Server

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

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

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

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

Prompt:
Use a template to render json.

import logging

from flask import (
	Flask,
	render_template,
	abort
)

from glanerbeard.server import Server

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

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

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

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

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


import re

class InvalidBoard(ValueError):
    pass

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

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

Response:
import re

class InvalidBoard(ValueError):
    pass

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

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

Prompt:
Add note regarding use of bool in validation

import re

class InvalidBoard(ValueError):
    pass

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

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


import numpy as np
import km3pipe as kp

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

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

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

Add a dummy script which creates an hdf5 file

Response:
import numpy as np
import km3pipe as kp

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

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

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

Prompt: Add a dummy script which creates an hdf5 file


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

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

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

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

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

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

Prompt:
Allow observing more than one action at once

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

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

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


import os
import sys

from setuptools import setup, find_packages

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

sys.path.insert(0, here)

from titlecase import __version__

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

Add python3 support for nosetests

Add python3 support for nosetests

Response:
import os
import sys

from setuptools import setup, find_packages

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

sys.path.insert(0, here)

from titlecase import __version__

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

Prompt:
Add python3 support for nosetests

import os
import sys

from setuptools import setup, find_packages

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

sys.path.insert(0, here)

from titlecase import __version__

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


import sys

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

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

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

Response:
import sys

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

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

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

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

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

import sys

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

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

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


import hashlib

from digestive.io import Sink

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

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

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

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

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

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

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

Response:
import hashlib

from digestive.io import Sink

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

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

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

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

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

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

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

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

import hashlib

from digestive.io import Sink

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

        log("Finished", self.readable_command)

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

if __name__ == "__main__": howlong()

Print debug info to stderr

MINOR: Print debug info to stderr

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

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

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

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

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

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

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

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

        log("Finished", self.readable_command)

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

if __name__ == "__main__": howlong()

Prompt:
MINOR: Print debug info to stderr

#!/usr/bin/env python3

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

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

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

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

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

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

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

        print("Finished", self.readable_command)

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

if __name__ == "__main__": howlong()


import socket
import os

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

from client import StatsClient

__all__ = ['StatsClient', 'statsd']

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

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

Response:
import socket
import os

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

from client import StatsClient

__all__ = ['StatsClient', 'statsd']

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

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

Prompt:
Read settings from environment, if available

import socket

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

from client import StatsClient

__all__ = ['StatsClient', 'statsd']

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

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


import logbook

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

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

    """

    _db = None

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

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

        return self._db

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

    """

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

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

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

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

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

        return 'db', self.run

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

Response:
import logbook

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

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

    """

    _db = None

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

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

        return self._db

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

    """

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

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

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

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

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

        return 'db', self.run

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

Prompt:
Add first iteration of LazyDatabaseMixin()

import logbook

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

    """

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

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

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

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

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

        return 'db', self.run

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


from django import forms

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

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

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

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

Response:
from django import forms

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

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

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

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

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

from django import forms

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

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

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


import scholarly
import requests

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

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

    print("Number of results:", num)

Response:
import scholarly
import requests

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

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

    print("Number of results:", num)

Prompt:
Make year range arguments optional in search

import scholarly
import requests

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

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

    print("Number of results:", num)


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

import pytest

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

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

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

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

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

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

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

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

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

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

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

    assert now == k.valid_start_date(now)

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

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

    assert a_month_ago == k.valid_end_date(a_month_ago)

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

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

Add tests for base class.

Add tests for base class.

Response:
"""Test the Reporter base class."""

import pytest

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

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

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

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

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

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

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

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

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

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

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

    assert now == k.valid_start_date(now)

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

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

    assert a_month_ago == k.valid_end_date(a_month_ago)

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

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

Prompt: Add tests for base class.


"""empty message

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

"""

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

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

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

    ### end Alembic commands ###

Add default permissions for existing services.

Response:
"""empty message

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

"""

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

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

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

    ### end Alembic commands ###

Prompt: Add default permissions for existing services.


import datetime
import math

from core import test_helper

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

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

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

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

if __name__ == '__main__':
    main()

Revert "Added solutions for lesson 4"

Response:
import datetime
import math

from core import test_helper

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

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

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

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

if __name__ == '__main__':
    main()

Prompt:
Revert "Added solutions for lesson 4"

This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.

import datetime
import math

from core import test_helper

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

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

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

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

if __name__ == '__main__':
    main()


from ..utils import *

##
# Minions

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

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

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

##
# Spells

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

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

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

##
# Secrets

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

Response:
from ..utils import *

##
# Minions

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

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

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

##
# Spells

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

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

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

##
# Secrets

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

Prompt:
Implement Mage cards for The Grand Tournament

from ..utils import *

##
# Secrets

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


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

db = db(env())

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

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

print("Done.")

Add script for migrating tips to new teams

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

db = db(env())

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

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

print("Done.")

Prompt: Add script for migrating tips to new teams


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

Usage:
    python setup.py py2app
"""

from setuptools import setup
from glob import glob
import syncplay

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

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

Update py2app script for Qt 5.11

Update py2app script for Qt 5.11

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

Usage:
    python setup.py py2app
"""

from setuptools import setup
from glob import glob
import syncplay

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

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

Prompt:
Update py2app script for Qt 5.11

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

Usage:
    python setup.py py2app
"""

from setuptools import setup
from glob import glob
import syncplay

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

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


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

import os
import unittest

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

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

class InsertionSortTester(unittest.TestCase):

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

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

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

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

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

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

if __name__ == '__main__':

    unittest.main()

Add unit test for heap sort implementation.

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

import os
import unittest

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

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

class InsertionSortTester(unittest.TestCase):

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

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

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

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

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

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

if __name__ == '__main__':

    unittest.main()

Prompt: Add unit test for heap sort implementation.


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

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

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

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

Update the pic download base url.

Update the pic download base url.

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

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

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

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

Prompt:
Update the pic download base url.

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

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

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

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


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

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

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

class NestedIterator(object):

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

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

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

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

Use stack to solve the problem

Use stack to solve the problem

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

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

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

class NestedIterator(object):

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

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

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

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

Prompt: Use stack to solve the problem