import unittest

from classes import Paladin
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

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

Test for the __init__ function of the Paladin class

Response:
import unittest

from classes import Paladin
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

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

Prompt: Test for the __init__ function of the Paladin class


# -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:

from gi.repository import GObject, Introspection, Peas

class ExtensionPythonPlugin(GObject.Object, Peas.Activatable,
                            Introspection.Base, Introspection.Callable,
                            Introspection.PropertiesPrerequisite,
                            Introspection.Properties,
                            Introspection.HasPrerequisite):

    object = GObject.property(type=GObject.Object)

    construct_only = GObject.property(type=str)
    read_only = GObject.property(type=str, default="read-only")
    write_only = GObject.property(type=str)
    readwrite = GObject.property(type=str, default="readwrite")
    prerequisite = GObject.property(type=str)

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass

    def do_get_plugin_info(self):
        return self.plugin_info

    def do_get_settings(self):
        return self.plugin_info.get_settings(None)

    def do_call_with_return(self):
        return "Hello, World!"

    def do_call_no_args(self):
        pass

    def do_call_single_arg(self):
        return True

    def do_call_multi_args(self, in_, inout):
        return (inout, in_)

Fix style issues in python test plugin

Response:
# -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:

from gi.repository import GObject, Introspection, Peas

class ExtensionPythonPlugin(GObject.Object, Peas.Activatable,
                            Introspection.Base, Introspection.Callable,
                            Introspection.PropertiesPrerequisite,
                            Introspection.Properties,
                            Introspection.HasPrerequisite):

    object = GObject.property(type=GObject.Object)

    construct_only = GObject.property(type=str)
    read_only = GObject.property(type=str, default="read-only")
    write_only = GObject.property(type=str)
    readwrite = GObject.property(type=str, default="readwrite")
    prerequisite = GObject.property(type=str)

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass

    def do_get_plugin_info(self):
        return self.plugin_info

    def do_get_settings(self):
        return self.plugin_info.get_settings(None)

    def do_call_with_return(self):
        return "Hello, World!"

    def do_call_no_args(self):
        pass

    def do_call_single_arg(self):
        return True

    def do_call_multi_args(self, in_, inout):
        return (inout, in_)

Prompt:
Fix style issues in python test plugin

https://bugzilla.gnome.org/show_bug.cgi?id=678339
# -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:

from gi.repository import GObject, Introspection, Peas

class ExtensionPythonPlugin(GObject.Object, Peas.Activatable,
                            Introspection.Base, Introspection.Callable,
                            Introspection.PropertiesPrerequisite,
                            Introspection.Properties,
                            Introspection.HasPrerequisite):

    object = GObject.property(type=GObject.Object)

    construct_only = GObject.property(type=str)
    read_only = GObject.property(type=str, default="read-only")
    write_only = GObject.property(type=str)
    readwrite = GObject.property(type=str, default="readwrite")
    prerequisite = GObject.property(type=str)

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass

    def do_get_plugin_info(self):
        return self.plugin_info

    def do_get_settings(self):
        return self.plugin_info.get_settings(None)

    def do_call_with_return(self):
        return "Hello, World!";

    def do_call_no_args(self):
        pass

    def do_call_single_arg(self):
        return True

    def do_call_multi_args(self, in_, inout):
        return (inout, in_)


"""Configuration for the Caffe2 installation.
"""

from build import Config
import sys

Config.USE_SYSTEM_PROTOBUF = False
Config.PROTOC_BINARY = 'gen/third_party/google/protoc'
Config.USE_OPENMP = False

if __name__ == '__main__':
    from brewtool.brewery import Brewery
    Brewery.Run(
        Config,
        ['build_android_prepare.py',
         'build', '//third_party/google:protoc'])
else:
    print('This script is not intended to be used as an imported module.')
    sys.exit(1)

Add a simple script to help build android.

Response:
"""Configuration for the Caffe2 installation.
"""

from build import Config
import sys

Config.USE_SYSTEM_PROTOBUF = False
Config.PROTOC_BINARY = 'gen/third_party/google/protoc'
Config.USE_OPENMP = False

if __name__ == '__main__':
    from brewtool.brewery import Brewery
    Brewery.Run(
        Config,
        ['build_android_prepare.py',
         'build', '//third_party/google:protoc'])
else:
    print('This script is not intended to be used as an imported module.')
    sys.exit(1)

Prompt: Add a simple script to help build android.


def binary_search(array, low, high, item):

    if(low>high) :
        return -1

    mid = (low + high)//2

    if(item == array[mid]):
        return mid
    elif item < array[mid]:
        return binary_search(array, low, mid-1, item)
    elif item > array[mid]:
        return binary_search(array, mid+1, high, item)

print ( binary_search([1,4,5,7], 0, 3, 5)) #2
print ( binary_search([1,4,5,7], 0, 3, 10)) #-1

Add recursive binary search implementation

Response:
def binary_search(array, low, high, item):

    if(low>high) :
        return -1

    mid = (low + high)//2

    if(item == array[mid]):
        return mid
    elif item < array[mid]:
        return binary_search(array, low, mid-1, item)
    elif item > array[mid]:
        return binary_search(array, mid+1, high, item)

print ( binary_search([1,4,5,7], 0, 3, 5)) #2
print ( binary_search([1,4,5,7], 0, 3, 10)) #-1

Prompt: Add recursive binary search implementation


import ircbotframe
import sys

class Handler:
    def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
        self.channels = channels
        self.bot = ircbotframe.ircBot(host, port, name, description)
        self.bot.bind("376", self.endMOTD)
        self.bot.start()

    def endMOTD(self, sender, headers, message):
        for chan in self.channels:
            self.bot.joinchan(chan)

def main(cmd, args):
    if len(args) < 2:
        print("Usage: " + cmd + " <host> <channel> [<channel> ...]")
        return
    elif len(args) > 1:
        Handler(host=args[0], channels=args[1:])

if __name__ == "__main__":
    if __name__ == '__main__':
        main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])

Fix bot not joining any channels

Response:
import ircbotframe
import sys

class Handler:
    def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
        self.channels = channels
        self.bot = ircbotframe.ircBot(host, port, name, description)
        self.bot.bind("376", self.endMOTD)
        self.bot.start()

    def endMOTD(self, sender, headers, message):
        for chan in self.channels:
            self.bot.joinchan(chan)

def main(cmd, args):
    if len(args) < 2:
        print("Usage: " + cmd + " <host> <channel> [<channel> ...]")
        return
    elif len(args) > 1:
        Handler(host=args[0], channels=args[1:])

if __name__ == "__main__":
    if __name__ == '__main__':
        main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])

Prompt:
Fix bot not joining any channels

Also removed unnecessary usage comment.

import ircbotframe
import sys

class Handler:
    def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
        self.channels = channels
        self.bot = ircbotframe.ircBot(host, port, name, description)
        self.bot.bind("376", self.endMOTD)
        self.bot.start()

    def endMOTD(self, sender, headers, message):
        for chan in self.channels:
            bot.joinchan(chan)

def main(cmd, args):
    if len(args) < 1:
        print("Usage: `" + cmd + " <host> <channel> [<channel> ...]` (for full arguments, see the readme)")
        return
    else:
        Handler(host=args[0])

if __name__ == "__main__":
    if __name__ == '__main__':
        main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])


from __future__ import unicode_literals

from django import forms

from utilities.forms import BootstrapMixin

OBJ_TYPE_CHOICES = (
    ('', 'All Objects'),
    ('Circuits', (
        ('provider', 'Providers'),
        ('circuit', 'Circuits'),
    )),
    ('DCIM', (
        ('site', 'Sites'),
        ('rack', 'Racks'),
        ('devicetype', 'Device types'),
        ('device', 'Devices'),
    )),
    ('IPAM', (
        ('vrf', 'VRFs'),
        ('aggregate', 'Aggregates'),
        ('prefix', 'Prefixes'),
        ('ipaddress', 'IP addresses'),
        ('vlan', 'VLANs'),
    )),
    ('Secrets', (
        ('secret', 'Secrets'),
    )),
    ('Tenancy', (
        ('tenant', 'Tenants'),
    )),
)

class SearchForm(BootstrapMixin, forms.Form):
    q = forms.CharField(
        label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
    )
    obj_type = forms.ChoiceField(
        choices=OBJ_TYPE_CHOICES, required=False, label='Type'
    )

Fix global search placeholder text

Fix global search placeholder text

Response:
from __future__ import unicode_literals

from django import forms

from utilities.forms import BootstrapMixin

OBJ_TYPE_CHOICES = (
    ('', 'All Objects'),
    ('Circuits', (
        ('provider', 'Providers'),
        ('circuit', 'Circuits'),
    )),
    ('DCIM', (
        ('site', 'Sites'),
        ('rack', 'Racks'),
        ('devicetype', 'Device types'),
        ('device', 'Devices'),
    )),
    ('IPAM', (
        ('vrf', 'VRFs'),
        ('aggregate', 'Aggregates'),
        ('prefix', 'Prefixes'),
        ('ipaddress', 'IP addresses'),
        ('vlan', 'VLANs'),
    )),
    ('Secrets', (
        ('secret', 'Secrets'),
    )),
    ('Tenancy', (
        ('tenant', 'Tenants'),
    )),
)

class SearchForm(BootstrapMixin, forms.Form):
    q = forms.CharField(
        label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
    )
    obj_type = forms.ChoiceField(
        choices=OBJ_TYPE_CHOICES, required=False, label='Type'
    )

Prompt:
Fix global search placeholder text

from __future__ import unicode_literals

from django import forms

from utilities.forms import BootstrapMixin

OBJ_TYPE_CHOICES = (
    ('', 'All Objects'),
    ('Circuits', (
        ('provider', 'Providers'),
        ('circuit', 'Circuits'),
    )),
    ('DCIM', (
        ('site', 'Sites'),
        ('rack', 'Racks'),
        ('devicetype', 'Device types'),
        ('device', 'Devices'),
    )),
    ('IPAM', (
        ('vrf', 'VRFs'),
        ('aggregate', 'Aggregates'),
        ('prefix', 'Prefixes'),
        ('ipaddress', 'IP addresses'),
        ('vlan', 'VLANs'),
    )),
    ('Secrets', (
        ('secret', 'Secrets'),
    )),
    ('Tenancy', (
        ('tenant', 'Tenants'),
    )),
)

class SearchForm(BootstrapMixin, forms.Form):
    q = forms.CharField(
        label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'})
    )
    obj_type = forms.ChoiceField(
        choices=OBJ_TYPE_CHOICES, required=False, label='Type'
    )


from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF

Response:
from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF

Prompt:
[Chaco] Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples

from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF


#!/usr/bin/env python3

import subprocess
import atexit
import sys
from utils.safe_schedule import SafeScheduler
from time import sleep
from glob import glob

META_IMPORT = '# narcissa import '
scheduler = SafeScheduler()

def make_exit_graceful():
    original_hook = sys.excepthook

    def new_hook(type, value, traceback):
        if type == KeyboardInterrupt:
            sys.exit("\nBye for now!")
        else:
            original_hook(type, value, traceback)

    sys.excepthook = new_hook

def start_server():
    cmd = 'waitress-serve --port=5000 server:app'
    p = subprocess.Popen(cmd.split(), cwd='server')
    return p

def load_scrapers():
    for scraper_path in glob('scrapers/*.py'):
        with open(scraper_path) as f:
            print(scraper_path)
            scraper_data = f.read()
            exec(scraper_data)

def main():
    make_exit_graceful()
    server = start_server()
    atexit.register(server.terminate)
    load_scrapers()
    while True:
        scheduler.run_pending()
        sleep(1)

if __name__ == '__main__':
    main()

Response:
#!/usr/bin/env python3

import subprocess
import atexit
import sys
from utils.safe_schedule import SafeScheduler
from time import sleep
from glob import glob

META_IMPORT = '# narcissa import '
scheduler = SafeScheduler()

def make_exit_graceful():
    original_hook = sys.excepthook

    def new_hook(type, value, traceback):
        if type == KeyboardInterrupt:
            sys.exit("\nBye for now!")
        else:
            original_hook(type, value, traceback)

    sys.excepthook = new_hook

def start_server():
    cmd = 'waitress-serve --port=5000 server:app'
    p = subprocess.Popen(cmd.split(), cwd='server')
    return p

def load_scrapers():
    for scraper_path in glob('scrapers/*.py'):
        with open(scraper_path) as f:
            print(scraper_path)
            scraper_data = f.read()
            exec(scraper_data)

def main():
    make_exit_graceful()
    server = start_server()
    atexit.register(server.terminate)
    load_scrapers()
    while True:
        scheduler.run_pending()
        sleep(1)

if __name__ == '__main__':
    main()

Prompt:
Change name of start_scrapers() to be more accurate

#!/usr/bin/env python3

import subprocess
import atexit
import sys
from utils.safe_schedule import SafeScheduler
from time import sleep
from glob import glob

META_IMPORT = '# narcissa import '
scheduler = SafeScheduler()

def make_exit_graceful():
    original_hook = sys.excepthook

    def new_hook(type, value, traceback):
        if type == KeyboardInterrupt:
            sys.exit("\nBye for now!")
        else:
            original_hook(type, value, traceback)

    sys.excepthook = new_hook

def start_server():
    cmd = 'waitress-serve --port=5000 server:app'
    p = subprocess.Popen(cmd.split(), cwd='server')
    return p

def start_scrapers():
    for scraper_path in glob('scrapers/*.py'):
        with open(scraper_path) as f:
            print(scraper_path)
            scraper_data = f.read()
            exec(scraper_data)

def main():
    make_exit_graceful()
    server = start_server()
    atexit.register(server.terminate)
    start_scrapers()
    while True:
        scheduler.run_pending()
        sleep(1)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

def add_knight_data(apps, schema_editor):
    Knight = apps.get_model('roundtable', 'Knight')
    Knight.objects.bulk_create([
        Knight(name='Arthur'),
        Knight(name='Bedevere'),
        Knight(name='Bors'),
        Knight(name='Ector'),
        Knight(name='Galahad'),
        Knight(name='Gawain'),
        Knight(name='Lancelot'),
        Knight(name='Robin'),
    ])

def remove_knight_data(apps, schema_editor):
    pass

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(
            add_knight_data,
            reverse_code=remove_knight_data),
    ]

Response:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

def add_knight_data(apps, schema_editor):
    Knight = apps.get_model('roundtable', 'Knight')
    Knight.objects.bulk_create([
        Knight(name='Arthur'),
        Knight(name='Bedevere'),
        Knight(name='Bors'),
        Knight(name='Ector'),
        Knight(name='Galahad'),
        Knight(name='Gawain'),
        Knight(name='Lancelot'),
        Knight(name='Robin'),
    ])

def remove_knight_data(apps, schema_editor):
    pass

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(
            add_knight_data,
            reverse_code=remove_knight_data),
    ]

Prompt:
Implement add_knight_data to generate data directly.

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

def add_knight_data(apps, schema_editor):
    call_command('loaddata', 'knight_data.json')

def remove_knight_data(apps, schema_editor):
    pass

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(
            add_knight_data,
            reverse_code=remove_knight_data),
    ]


#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

class Terminal:
    def __init__(self, symbol, grammar):
        self.__symbol = symbol
        self.__grammar = grammar

    def __hash__(self):
        return hash((self.__symbol, id(self.__grammar)))

    def __eq__(self, other):
        return isinstance(other, Terminal) and hash(self) == hash(other)

Add class represents terminal symbol

Add class represents terminal symbol

Response:
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

class Terminal:
    def __init__(self, symbol, grammar):
        self.__symbol = symbol
        self.__grammar = grammar

    def __hash__(self):
        return hash((self.__symbol, id(self.__grammar)))

    def __eq__(self, other):
        return isinstance(other, Terminal) and hash(self) == hash(other)

Prompt: Add class represents terminal symbol


from datetime import datetime
from flask import current_app

from changes.config import db, queue
from changes.models import Repository

def sync_repo(repo_id):
    repo = Repository.query.get(repo_id)
    if not repo:
        return

    vcs = repo.get_vcs()
    if vcs is None:
        return

    repo.last_update_attempt = datetime.utcnow()
    db.session.add(repo)
    db.session.commit()

    try:
        if vcs.exists():
            vcs.update()
        else:
            vcs.clone()

        # TODO(dcramer): this doesnt scrape everything, and really we wouldn't
        # want to do this all in a single job so we should split this into a
        # backfill task
        might_have_more = True
        parent = None
        while might_have_more:
            might_have_more = False
            for commit in vcs.log(parent=parent):
                revision, created = commit.save(repo)
                db.session.commit()
                if not created:
                    break
                might_have_more = True
                parent = commit.id

        repo.last_update = datetime.utcnow()

        db.session.add(repo)
        db.session.commit()

        queue.delay('sync_repo', kwargs={
            'repo_id': repo_id
        }, countdown=15)

    except Exception as exc:
        # should we actually use retry support here?
        current_app.logger.exception('Failed to sync repository %s', repo_id)
        raise queue.retry('sync_repo', kwargs={
            'repo_id': repo_id,
        }, exc=exc, countdown=120)

Use app logging instead of celery

Use app logging instead of celery

Response:
from datetime import datetime
from flask import current_app

from changes.config import db, queue
from changes.models import Repository

def sync_repo(repo_id):
    repo = Repository.query.get(repo_id)
    if not repo:
        return

    vcs = repo.get_vcs()
    if vcs is None:
        return

    repo.last_update_attempt = datetime.utcnow()
    db.session.add(repo)
    db.session.commit()

    try:
        if vcs.exists():
            vcs.update()
        else:
            vcs.clone()

        # TODO(dcramer): this doesnt scrape everything, and really we wouldn't
        # want to do this all in a single job so we should split this into a
        # backfill task
        might_have_more = True
        parent = None
        while might_have_more:
            might_have_more = False
            for commit in vcs.log(parent=parent):
                revision, created = commit.save(repo)
                db.session.commit()
                if not created:
                    break
                might_have_more = True
                parent = commit.id

        repo.last_update = datetime.utcnow()

        db.session.add(repo)
        db.session.commit()

        queue.delay('sync_repo', kwargs={
            'repo_id': repo_id
        }, countdown=15)

    except Exception as exc:
        # should we actually use retry support here?
        current_app.logger.exception('Failed to sync repository %s', repo_id)
        raise queue.retry('sync_repo', kwargs={
            'repo_id': repo_id,
        }, exc=exc, countdown=120)

Prompt:
Use app logging instead of celery

from datetime import datetime

from changes.config import db, queue
from changes.models import Repository

def sync_repo(repo_id):
    repo = Repository.query.get(repo_id)
    if not repo:
        return

    vcs = repo.get_vcs()
    if vcs is None:
        return

    repo.last_update_attempt = datetime.utcnow()
    db.session.add(repo)
    db.session.commit()

    try:
        if vcs.exists():
            vcs.update()
        else:
            vcs.clone()

        # TODO(dcramer): this doesnt scrape everything, and really we wouldn't
        # want to do this all in a single job so we should split this into a
        # backfill task
        might_have_more = True
        parent = None
        while might_have_more:
            might_have_more = False
            for commit in vcs.log(parent=parent):
                revision, created = commit.save(repo)
                db.session.commit()
                if not created:
                    break
                might_have_more = True
                parent = commit.id

        repo.last_update = datetime.utcnow()

        db.session.add(repo)
        db.session.commit()

        queue.delay('sync_repo', kwargs={
            'repo_id': repo_id
        }, countdown=15)

    except Exception as exc:
        # should we actually use retry support here?
        raise queue.retry('sync_repo', kwargs={
            'repo_id': repo_id,
        }, exc=exc, countdown=120)


import time

import mock
import pytest

import spreadsplug.intervaltrigger as intervaltrigger

@pytest.fixture
def plugin(config):
    config['intervaltrigger']['interval'] = 0.1
    return intervaltrigger.IntervalTrigger(config)

def test_trigger_loop(plugin):
    cbmock = mock.Mock()
    plugin.start_trigger_loop(cbmock)
    time.sleep(0.6)
    plugin.stop_trigger_loop()
    assert cbmock.call_count == 5

Response:
import time

import mock
import pytest

import spreadsplug.intervaltrigger as intervaltrigger

@pytest.fixture
def plugin(config):
    config['intervaltrigger']['interval'] = 0.1
    return intervaltrigger.IntervalTrigger(config)

def test_trigger_loop(plugin):
    cbmock = mock.Mock()
    plugin.start_trigger_loop(cbmock)
    time.sleep(0.6)
    plugin.stop_trigger_loop()
    assert cbmock.call_count == 5

Prompt:
Increase sleep-time in intervaltrigger tests

import time

import mock
import pytest

import spreadsplug.intervaltrigger as intervaltrigger

@pytest.fixture
def plugin(config):
    config['intervaltrigger']['interval'] = 0.1
    return intervaltrigger.IntervalTrigger(config)

def test_trigger_loop(plugin):
    cbmock = mock.Mock()
    plugin.start_trigger_loop(cbmock)
    time.sleep(0.55)
    plugin.stop_trigger_loop()
    assert cbmock.call_count == 5


import os
import gnupg
import logging

from .utils import which

def create_key_input(gpg, passphrase, testing=False):
    key_input = gpg.gen_key_input(
        name_real='Pysswords',
        name_email='pysswords@pysswords',
        name_comment='Autogenerated by Pysswords',
        passphrase=passphrase,
        testing=testing
    )
    return key_input

def create_gpg(binary, database_path, passphrase):
    gnupg_path = os.path.join(database_path, ".gnupg")
    gpg = gnupg.GPG(which(binary), homedir=gnupg_path)
    gpg.gen_key(create_key_input(gpg, passphrase))
    return gpg

def load_gpg(binary, database_path):
    gnupg_path = os.path.join(database_path, ".gnupg")
    gpg = gnupg.GPG(which(binary), homedir=gnupg_path)
    return gpg

Add load gpg to get an instance of gpg

Add load gpg to get an instance of gpg

Response:
import os
import gnupg
import logging

from .utils import which

def create_key_input(gpg, passphrase, testing=False):
    key_input = gpg.gen_key_input(
        name_real='Pysswords',
        name_email='pysswords@pysswords',
        name_comment='Autogenerated by Pysswords',
        passphrase=passphrase,
        testing=testing
    )
    return key_input

def create_gpg(binary, database_path, passphrase):
    gnupg_path = os.path.join(database_path, ".gnupg")
    gpg = gnupg.GPG(which(binary), homedir=gnupg_path)
    gpg.gen_key(create_key_input(gpg, passphrase))
    return gpg

def load_gpg(binary, database_path):
    gnupg_path = os.path.join(database_path, ".gnupg")
    gpg = gnupg.GPG(which(binary), homedir=gnupg_path)
    return gpg

Prompt:
Add load gpg to get an instance of gpg

import os
import gnupg
import logging

from .utils import which

def create_key_input(gpg, passphrase, testing=False):
    key_input = gpg.gen_key_input(
        name_real='Pysswords',
        name_email='pysswords@pysswords',
        name_comment='Autogenerated by Pysswords',
        passphrase=passphrase,
        testing=testing
    )
    return key_input

def create_gpg(binary, database_path, passphrase):
    gnupg_path = os.path.join(database_path, ".gnupg")
    gpg = gnupg.GPG(which(binary), homedir=gnupg_path)
    gpg.gen_key(create_key_input(gpg, passphrase))
    return gpg


#!/usr/bin/env python
# coding: utf-8
import glob as _glob

import setuptools as _st

import tues as _tues

if __name__ == '__main__':
    _st.setup(
        name='tues',
        version=_tues.__version__,
        url='https://github.com/wontfix-org/tues/',
        license='MIT',
        author='Michael van Bracht',
        author_email='michael@wontfix.org',
        description='Easy remote command execution',
        packages=_st.find_packages(),
        scripts=_glob.glob('scripts/tues*'),
        include_package_data=True,
        platforms='any',
        long_description=open("README.md").read(),
        long_description_content_type="text/markdown",
        install_requires=['docopt', 'fabric3', 'requests>=2.4'],
        classifiers=[
            'Programming Language :: Python',
            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3',
            'Natural Language :: English',
        ],
    )

Move to native markdown parsing

Response:
#!/usr/bin/env python
# coding: utf-8
import glob as _glob

import setuptools as _st

import tues as _tues

if __name__ == '__main__':
    _st.setup(
        name='tues',
        version=_tues.__version__,
        url='https://github.com/wontfix-org/tues/',
        license='MIT',
        author='Michael van Bracht',
        author_email='michael@wontfix.org',
        description='Easy remote command execution',
        packages=_st.find_packages(),
        scripts=_glob.glob('scripts/tues*'),
        include_package_data=True,
        platforms='any',
        long_description=open("README.md").read(),
        long_description_content_type="text/markdown",
        install_requires=['docopt', 'fabric3', 'requests>=2.4'],
        classifiers=[
            'Programming Language :: Python',
            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3',
            'Natural Language :: English',
        ],
    )

Prompt:
packaging: Move to native markdown parsing

setuptools-markdown is deprecated

#!/usr/bin/env python
# coding: utf-8
import glob as _glob

import setuptools as _st

import tues as _tues

if __name__ == '__main__':
    _st.setup(
        name='tues',
        version=_tues.__version__,
        url='https://github.com/wontfix-org/tues/',
        license='MIT',
        author='Michael van Bracht',
        author_email='michael@wontfix.org',
        description='Easy remote command execution',
        packages=_st.find_packages(),
        scripts=_glob.glob('scripts/tues*'),
        include_package_data=True,
        platforms='any',
        setup_requires=['setuptools-markdown'],
        long_description_markdown_filename='README.md',
        install_requires=['docopt', 'fabric3', 'requests>=2.4'],
        classifiers=[
            'Programming Language :: Python',
            'Programming Language :: Python :: 2.7',
            'Natural Language :: English',
        ],
    )


import tempfile
import os.path as op
import numpy as np
import IPython.display as display

import nibabel as nib
from dipy.viz import fvtk
from dipy.viz.colormap import line_colors

from palettable.tableau import Tableau_20

def visualize_bundles(trk, ren=None, inline=True, interact=False):
    """
    Visualize bundles in 3D using fvtk

    """
    if isinstance(trk, str):
        trk = nib.streamlines.load(trk)

    if ren is None:
        ren = fvtk.ren()

    # There are no bundles in here:
    if list(trk.tractogram.data_per_streamline.keys()) == []:
        streamlines = list(trk.streamlines)
        sl_actor = fvtk.line(streamlines, line_colors(streamlines))
        fvtk.add(ren, sl_actor)

    for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
        idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
        this_sl = list(trk.streamlines[idx])
        sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
        fvtk.add(ren, sl_actor)

    if inline:
        tdir = tempfile.gettempdir()
        fname = op.join(tdir, "fig.png")
        fvtk.record(ren, out_path=fname)
        display.display_png(display.Image(fname))

    if interact:
        fvtk.show(ren)

    return ren

Response:
import tempfile
import os.path as op
import numpy as np
import IPython.display as display

import nibabel as nib
from dipy.viz import fvtk
from dipy.viz.colormap import line_colors

from palettable.tableau import Tableau_20

def visualize_bundles(trk, ren=None, inline=True, interact=False):
    """
    Visualize bundles in 3D using fvtk

    """
    if isinstance(trk, str):
        trk = nib.streamlines.load(trk)

    if ren is None:
        ren = fvtk.ren()

    # There are no bundles in here:
    if list(trk.tractogram.data_per_streamline.keys()) == []:
        streamlines = list(trk.streamlines)
        sl_actor = fvtk.line(streamlines, line_colors(streamlines))
        fvtk.add(ren, sl_actor)

    for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
        idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
        this_sl = list(trk.streamlines[idx])
        sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
        fvtk.add(ren, sl_actor)

    if inline:
        tdir = tempfile.gettempdir()
        fname = op.join(tdir, "fig.png")
        fvtk.record(ren, out_path=fname)
        display.display_png(display.Image(fname))

    if interact:
        fvtk.show(ren)

    return ren

Prompt:
Enable visualizing trk files without bundle designations.

import tempfile
import os.path as op
import numpy as np
import IPython.display as display

import nibabel as nib
from dipy.viz import fvtk
from palettable.tableau import Tableau_20

def visualize_bundles(trk, ren=None, inline=True, interact=False):
    """
    Visualize bundles in 3D using fvtk

    """
    if isinstance(trk, str):
        trk = nib.streamlines.load(trk)

    if ren is None:
        ren = fvtk.ren()

    for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
        idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
        this_sl = list(trk.streamlines[idx])
        sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
        fvtk.add(ren, sl_actor)

    if inline:
        tdir = tempfile.gettempdir()
        fname = op.join(tdir, "fig.png")
        fvtk.record(ren, out_path=fname)
        display.display_png(display.Image(fname))

    if interact:
        fvtk.show(ren)

    return ren


#!/usr/bin/python

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import sys
import re

# If you add a line like this to the ctor for a class:
#   printf_stderr("ZZZ CREATE %p\n", this);
# and a line line this to the dtor for a class:
#   printf_stderr("ZZZ DESTROY %p\n", this);
# then this log will process the resulting mochitest log
# and give you the mochitest that was running when any such
# objects were allocated that had no matching dtor.

cdMatch = re.compile('^.* ZZZ (CREATE|DESTROY) ([0-9A-F]+)\r?$')
anyUnknown = False

live = {}

currTest = None

for l in sys.stdin:
    if not 'ZZ' in l:
        if l.find("TEST-START") > -1:
            currTest = l.split('|')[1].strip()
        continue

    cdm = cdMatch.match(l)
    if not cdm:
        print 'Unknown line: ', l,
        anyUnknown = True
        continue
    isCreate = cdm.group(1) == 'CREATE'
    assert isCreate or cdm.group(1) == 'DESTROY'
    addr = cdm.group(2)
    if len(addr) != 8:
        print 'Not enough characters in address:', addr, l,

    if isCreate:
        assert not addr in live
        assert currTest
        live[addr] = currTest
    else:
        assert addr in live
        del live[addr]

if anyUnknown:
    exit(-1)

testCounts = {}
for liveAddr, inTest in live.iteritems():
    testCounts[inTest] = testCounts.setdefault(inTest, 0) + 1

for t, n in testCounts.iteritems():
    print n, t

Add leak matcher for figuring out which test is leaking objects of a type

Response:
#!/usr/bin/python

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import sys
import re

# If you add a line like this to the ctor for a class:
#   printf_stderr("ZZZ CREATE %p\n", this);
# and a line line this to the dtor for a class:
#   printf_stderr("ZZZ DESTROY %p\n", this);
# then this log will process the resulting mochitest log
# and give you the mochitest that was running when any such
# objects were allocated that had no matching dtor.

cdMatch = re.compile('^.* ZZZ (CREATE|DESTROY) ([0-9A-F]+)\r?$')
anyUnknown = False

live = {}

currTest = None

for l in sys.stdin:
    if not 'ZZ' in l:
        if l.find("TEST-START") > -1:
            currTest = l.split('|')[1].strip()
        continue

    cdm = cdMatch.match(l)
    if not cdm:
        print 'Unknown line: ', l,
        anyUnknown = True
        continue
    isCreate = cdm.group(1) == 'CREATE'
    assert isCreate or cdm.group(1) == 'DESTROY'
    addr = cdm.group(2)
    if len(addr) != 8:
        print 'Not enough characters in address:', addr, l,

    if isCreate:
        assert not addr in live
        assert currTest
        live[addr] = currTest
    else:
        assert addr in live
        del live[addr]

if anyUnknown:
    exit(-1)

testCounts = {}
for liveAddr, inTest in live.iteritems():
    testCounts[inTest] = testCounts.setdefault(inTest, 0) + 1

for t, n in testCounts.iteritems():
    print n, t

Prompt: Add leak matcher for figuring out which test is leaking objects of a type


#!/usr/bin/env python

import os
import re
import shutil
import sys

""" Automate updating multiple HDP jars for debugging/hotfix purposes.
Agnostic to the target directory layout which can differ across HDP versions.
"""

if (len(sys.argv) != 4):
  print("Usage: replace-jars.pl <source-dir> <source-version> <dst-version>")
  print("       source-dir     : Directory containing the new jar versions.")
  print("       source-version : Version string of the new jars.")
  print("       dst-version    : Installed HDP version to be updated.")
  sys.exit(1)

# Strip out the first three digits which are the Apache version
# from dst_ver.
#
src, src_ver, dst_ver = sys.argv[1:]
ver_pattern = re.compile('^\d+\.\d+\.\d+\.')
dst = "/usr/hdp/" + re.sub(ver_pattern, "", dst_ver)

# Sanity checks.
#
if not os.path.isdir(dst):
  print("Directory {} does not exist".format(dst))
  sys.exit(1)

if not os.path.isdir(src):
  print("Directory {} does not exist".format(src))
  sys.exit(1)

# Build a map of source jar name to its full path under
# the source directory.
#
sources = {}
for root, dirs, files in os.walk(src):
  for f in files:
    if f.endswith('.jar') and f not in sources:
      sources[f] = os.path.join(root, f)

print("Got {} source jars.".format(len(sources)))

# List destination jars, and replace each with the corresponding
# source jar.
# TODO: Create a backup of the jars being replaced.
#
jars_replaced = 0
for root, dirs, files in os.walk(dst):
  for f in files:
    if f.endswith('.jar') and f.startswith('hadoop'):
      dest = os.path.join(root, f)
      src_jar_name = f.replace(dst_ver, src_ver, 1)
      if src_jar_name in sources and os.path.isfile(dest):
        print("{} -> {}".format(dest, sources[src_jar_name]))
        shutil.copy2(sources[src_jar_name], dest)
        jars_replaced += 1

print("Replaced {} jars.".format(jars_replaced))

Add script to automate replacing HDP jars.

Response:
#!/usr/bin/env python

import os
import re
import shutil
import sys

""" Automate updating multiple HDP jars for debugging/hotfix purposes.
Agnostic to the target directory layout which can differ across HDP versions.
"""

if (len(sys.argv) != 4):
  print("Usage: replace-jars.pl <source-dir> <source-version> <dst-version>")
  print("       source-dir     : Directory containing the new jar versions.")
  print("       source-version : Version string of the new jars.")
  print("       dst-version    : Installed HDP version to be updated.")
  sys.exit(1)

# Strip out the first three digits which are the Apache version
# from dst_ver.
#
src, src_ver, dst_ver = sys.argv[1:]
ver_pattern = re.compile('^\d+\.\d+\.\d+\.')
dst = "/usr/hdp/" + re.sub(ver_pattern, "", dst_ver)

# Sanity checks.
#
if not os.path.isdir(dst):
  print("Directory {} does not exist".format(dst))
  sys.exit(1)

if not os.path.isdir(src):
  print("Directory {} does not exist".format(src))
  sys.exit(1)

# Build a map of source jar name to its full path under
# the source directory.
#
sources = {}
for root, dirs, files in os.walk(src):
  for f in files:
    if f.endswith('.jar') and f not in sources:
      sources[f] = os.path.join(root, f)

print("Got {} source jars.".format(len(sources)))

# List destination jars, and replace each with the corresponding
# source jar.
# TODO: Create a backup of the jars being replaced.
#
jars_replaced = 0
for root, dirs, files in os.walk(dst):
  for f in files:
    if f.endswith('.jar') and f.startswith('hadoop'):
      dest = os.path.join(root, f)
      src_jar_name = f.replace(dst_ver, src_ver, 1)
      if src_jar_name in sources and os.path.isfile(dest):
        print("{} -> {}".format(dest, sources[src_jar_name]))
        shutil.copy2(sources[src_jar_name], dest)
        jars_replaced += 1

print("Replaced {} jars.".format(jars_replaced))

Prompt: Add script to automate replacing HDP jars.


# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-03 18:13
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('articles', '0090_auto_20170502_1621'),
    ]

    operations = [
        migrations.AddField(
            model_name='articlepage',
            name='reading_time',
            field=models.PositiveIntegerField(default=0),
        ),
    ]

Add reading_time to article pages.

Add reading_time to article pages.

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-03 18:13
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('articles', '0090_auto_20170502_1621'),
    ]

    operations = [
        migrations.AddField(
            model_name='articlepage',
            name='reading_time',
            field=models.PositiveIntegerField(default=0),
        ),
    ]

Prompt: Add reading_time to article pages.


#Create a function to get a mesh file 'f'
def getMesh(fname):

	#Open the file
	f = open(fname, "r")

	#Store the lines as a list
	f = list(f)

	#Strip newlines from the list
	for l in range(len(f)):
		f[l] = f[l].replace("\n","")

	#Store the number of vertices, edges and sides
	v = int(f[0])
	e = int(f[1])
	s = int(f[2])

	#Create empty lists to hold the data
	vertices = []
	edges = []
	sides = []

	#Loop over all of the vertices and add them to the list
	for i in range(3, v + 3):

		#Split the vertex into a list of coordinates
		vertex = f[i].split(",")

		#Turn the coordinates into integers and append to the vertex
		vertices.append((int(vertex[0]), int(vertex[1]), int(vertex[2])))

	#Loop over all of the edges and add them to the list
	for i in range(v + 3, e + v + 3):

		#Split the edge into a list of vertices
		edge = f[i].split(",")

		#Turn the vertices indexes into integers and add to the side
		edges.append((int(edge[0]), int(edge[1])))

	#Loop over all of the sides and add them to the list
	for i in range(e + v + 3, s + e + v + 3):

		#Split the side into a list of vertices
		side = f[i].split(",")

		#Create a new side list to hold the data
		newside = []

		#For each vertex index in the side, add it to the new side variable
		for p in side:
			newside.append(int(p))

		#Add the side to the list of sides
		sides.append(tuple(newside))

	#Return the data
	return (vertices, edges, sides)

Write function to read in vertices, edges and sides from file.

Response:
#Create a function to get a mesh file 'f'
def getMesh(fname):

	#Open the file
	f = open(fname, "r")

	#Store the lines as a list
	f = list(f)

	#Strip newlines from the list
	for l in range(len(f)):
		f[l] = f[l].replace("\n","")

	#Store the number of vertices, edges and sides
	v = int(f[0])
	e = int(f[1])
	s = int(f[2])

	#Create empty lists to hold the data
	vertices = []
	edges = []
	sides = []

	#Loop over all of the vertices and add them to the list
	for i in range(3, v + 3):

		#Split the vertex into a list of coordinates
		vertex = f[i].split(",")

		#Turn the coordinates into integers and append to the vertex
		vertices.append((int(vertex[0]), int(vertex[1]), int(vertex[2])))

	#Loop over all of the edges and add them to the list
	for i in range(v + 3, e + v + 3):

		#Split the edge into a list of vertices
		edge = f[i].split(",")

		#Turn the vertices indexes into integers and add to the side
		edges.append((int(edge[0]), int(edge[1])))

	#Loop over all of the sides and add them to the list
	for i in range(e + v + 3, s + e + v + 3):

		#Split the side into a list of vertices
		side = f[i].split(",")

		#Create a new side list to hold the data
		newside = []

		#For each vertex index in the side, add it to the new side variable
		for p in side:
			newside.append(int(p))

		#Add the side to the list of sides
		sides.append(tuple(newside))

	#Return the data
	return (vertices, edges, sides)

Prompt: Write function to read in vertices, edges and sides from file.


import os
from queue import Queue
from threading import Thread

from elasticsearch_raven.transport import ElasticsearchTransport
from elasticsearch_raven.utils import get_index

host = os.environ.get('ELASTICSEARCH_HOST', 'localhost:9200')
transport = ElasticsearchTransport(host)
blocking_queue = Queue()

def send():
    while True:
        data, index = blocking_queue.get()
        transport.send(data, index)
        blocking_queue.task_done()

sender = Thread(target=send)
sender.daemon = True
sender.start()

def application(environ, start_response):
    index = get_index(environ)
    length = int(environ.get('CONTENT_LENGTH', '0'))
    data = environ['wsgi.input'].read(length)
    blocking_queue.put((data, index))

    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain')]
    start_response(status, response_headers)
    return [''.encode('utf-8')]

Response:
import os
from queue import Queue
from threading import Thread

from elasticsearch_raven.transport import ElasticsearchTransport
from elasticsearch_raven.utils import get_index

host = os.environ.get('ELASTICSEARCH_HOST', 'localhost:9200')
transport = ElasticsearchTransport(host)
blocking_queue = Queue()

def send():
    while True:
        data, index = blocking_queue.get()
        transport.send(data, index)
        blocking_queue.task_done()

sender = Thread(target=send)
sender.daemon = True
sender.start()

def application(environ, start_response):
    index = get_index(environ)
    length = int(environ.get('CONTENT_LENGTH', '0'))
    data = environ['wsgi.input'].read(length)
    blocking_queue.put((data, index))

    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain')]
    start_response(status, response_headers)
    return [''.encode('utf-8')]

Prompt:
Send data to elasticsearch asynchronously.

import os

from elasticsearch_raven.transport import ElasticsearchTransport
from elasticsearch_raven.utils import get_index

host = os.environ.get('ELASTICSEARCH_HOST', 'localhost:9200')
transport = ElasticsearchTransport(host)

def application(environ, start_response):
    index = get_index(environ)
    transport.send(environ['wsgi.input'].read(), index)

    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain')]
    start_response(status, response_headers)
    return [''.encode('utf-8')]


# -*- encoding: utf-8 -*-

__author__ = 'Sebastian Vetter'
__version__ = VERSION = '0.0.0'
__license__ = 'MIT'

Add author and lincense variables

Add author and lincense variables

Response:
# -*- encoding: utf-8 -*-

__author__ = 'Sebastian Vetter'
__version__ = VERSION = '0.0.0'
__license__ = 'MIT'

Prompt:
Add author and lincense variables

# -*- encoding: utf-8 -*-

__version__ = VERSION = '0.0.0'


"""Package command line interface."""

import click

from .curse import Game, Mod

# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}

@click.group()
def cli():
    """Minecraft Curse CLI client."""

@cli.command()
@click.option(
    '--refresh', is_flag=True, default=False,
    help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
    """Search for TEXT in mods on CurseForge."""

    if not text:
        raise SystemExit('No text to search for!')

    mc = Game(**MINECRAFT)

    text = ' '.join(text)
    refresh = refresh or not mc.have_fresh_data()

    if refresh:
        click.echo('Refreshing search data, please wait…', err=True)
        mc.refresh_data()

    mod_fmt = '{0.name}: {0.summary}'
    for mod in Mod.search(mc.database.session(), text):
        click.echo(mod_fmt.format(mod))

# If run as a package, run whole cli
cli()

Response:
"""Package command line interface."""

import click

from .curse import Game, Mod

# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}

@click.group()
def cli():
    """Minecraft Curse CLI client."""

@cli.command()
@click.option(
    '--refresh', is_flag=True, default=False,
    help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
    """Search for TEXT in mods on CurseForge."""

    if not text:
        raise SystemExit('No text to search for!')

    mc = Game(**MINECRAFT)

    text = ' '.join(text)
    refresh = refresh or not mc.have_fresh_data()

    if refresh:
        click.echo('Refreshing search data, please wait…', err=True)
        mc.refresh_data()

    mod_fmt = '{0.name}: {0.summary}'
    for mod in Mod.search(mc.database.session(), text):
        click.echo(mod_fmt.format(mod))

# If run as a package, run whole cli
cli()

Prompt:
Raise error when there is no term to search for

"""Package command line interface."""

import click

from .curse import Game, Mod

# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}

@click.group()
def cli():
    """Minecraft Curse CLI client."""

@cli.command()
@click.option(
    '--refresh', is_flag=True, default=False,
    help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
    """Search for TEXT in mods on CurseForge."""

    mc = Game(**MINECRAFT)

    text = ' '.join(text)
    refresh = refresh or not mc.have_fresh_data()

    if refresh:
        click.echo('Refreshing search data, please wait…', err=True)
        mc.refresh_data()

    mod_fmt = '{0.name}: {0.summary}'
    for mod in Mod.search(mc.database.session(), text):
        click.echo(mod_fmt.format(mod))

# If run as a package, run whole cli
cli()


def shapeArea(n):
    if n < 1 or n > 10**4:
        raise ValueError
    if n == 1:
        return 1
    else:
        innerArea = shapeArea(n - 1)
        return innerArea + (n - 1) * 4

def main():
    tests = [-1, 10**5, 1, 2, 3, 4]
    results = [False, False, 1, 5, 13, 25]
    for i, t in enumerate(tests):
        try:
            r = shapeArea(t)
            if r == results[i]:
                print("PASSED: shapeArea({}) returned {}".format(t, r))
            else:
                print("FAILED: shapeArea({}) returned\
                 {}, vs {}".format(t, r, results[i]))
        except ValueError:
            print("PASSED ValueError test")

if __name__ == '__main__':
    main()

Add code fight shape area solution

Add code fight shape area solution

Response:
def shapeArea(n):
    if n < 1 or n > 10**4:
        raise ValueError
    if n == 1:
        return 1
    else:
        innerArea = shapeArea(n - 1)
        return innerArea + (n - 1) * 4

def main():
    tests = [-1, 10**5, 1, 2, 3, 4]
    results = [False, False, 1, 5, 13, 25]
    for i, t in enumerate(tests):
        try:
            r = shapeArea(t)
            if r == results[i]:
                print("PASSED: shapeArea({}) returned {}".format(t, r))
            else:
                print("FAILED: shapeArea({}) returned\
                 {}, vs {}".format(t, r, results[i]))
        except ValueError:
            print("PASSED ValueError test")

if __name__ == '__main__':
    main()

Prompt: Add code fight shape area solution


import abc

from website.util import web_url_for

class AddonSerializer(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self, addon_node_settings, user):
        self.addon_node_settings = addon_node_settings
        self.user = user

    @abc.abstractproperty
    def serialized_urls(self):
        pass

    @abc.abstractproperty
    def has_valid_credentials(self):
        pass

    @abc.abstractproperty
    def node_has_auth(self):
        pass

    @abc.abstractproperty
    def user_has_auth(self):
        pass

    @abc.abstractproperty
    def user_is_owner(self):
        pass

    @abc.abstractproperty
    def credentials_owner(self):
        pass

    @property
    def serialized_settings(self):

        node_has_auth = self.node_has_auth
        result = {
            'nodeHasAuth': node_has_auth,
            'userHasAuth': self.user_has_auth,
            'userIsOwner': self.user_is_owner,
            'validCredentials': self.has_valid_credentials,
            'urls': self.serialized_urls,
        }

        if node_has_auth:
            owner = self.credentials_owner
            if owner:
                result['urls']['owner'] = web_url_for('profile_view_id',
                                                  uid=owner._primary_key)
                result['ownerName'] = owner.fullname

        return result

class StorageAddonSerializer(AddonSerializer):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def serialized_folder(self):
        pass

    @property
    def serialized_settings(self):

        result = super(StorageAddonSerializer, self).serialized_settings
        result['folder'] = self.serialized_folder
        return result

class CitationsAddonSerializer(AddonSerializer):
    __metaclass__ = abc.ABCMeta

Add base class for serializing addons.

Add base class for serializing addons.

Response:
import abc

from website.util import web_url_for

class AddonSerializer(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self, addon_node_settings, user):
        self.addon_node_settings = addon_node_settings
        self.user = user

    @abc.abstractproperty
    def serialized_urls(self):
        pass

    @abc.abstractproperty
    def has_valid_credentials(self):
        pass

    @abc.abstractproperty
    def node_has_auth(self):
        pass

    @abc.abstractproperty
    def user_has_auth(self):
        pass

    @abc.abstractproperty
    def user_is_owner(self):
        pass

    @abc.abstractproperty
    def credentials_owner(self):
        pass

    @property
    def serialized_settings(self):

        node_has_auth = self.node_has_auth
        result = {
            'nodeHasAuth': node_has_auth,
            'userHasAuth': self.user_has_auth,
            'userIsOwner': self.user_is_owner,
            'validCredentials': self.has_valid_credentials,
            'urls': self.serialized_urls,
        }

        if node_has_auth:
            owner = self.credentials_owner
            if owner:
                result['urls']['owner'] = web_url_for('profile_view_id',
                                                  uid=owner._primary_key)
                result['ownerName'] = owner.fullname

        return result

class StorageAddonSerializer(AddonSerializer):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def serialized_folder(self):
        pass

    @property
    def serialized_settings(self):

        result = super(StorageAddonSerializer, self).serialized_settings
        result['folder'] = self.serialized_folder
        return result

class CitationsAddonSerializer(AddonSerializer):
    __metaclass__ = abc.ABCMeta

Prompt: Add base class for serializing addons.


# Date: August 2017
# Author: Kutay B. Sezginel
"""
Thermal conductivity calculations of porous crystals using Lammps
"""
from .simulation import Simulation
from .trajectory import Trajectory
from .parameters import Parameters
from .mof import MOF

Add parameter import to main module

Add parameter import to main module

Response:
# Date: August 2017
# Author: Kutay B. Sezginel
"""
Thermal conductivity calculations of porous crystals using Lammps
"""
from .simulation import Simulation
from .trajectory import Trajectory
from .parameters import Parameters
from .mof import MOF

Prompt:
Add parameter import to main module

# Date: August 2017
# Author: Kutay B. Sezginel
"""
Thermal conductivity calculations of porous crystals using Lammps
"""
from .simulation import Simulation
from .trajectory import Trajectory
from .mof import MOF


#!/usr/bin/env python

"""Delete login user events older than a given number of days.

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from datetime import datetime, timedelta

import click

from byceps.database import db
from byceps.services.user.models.event import UserEvent as DbUserEvent
from byceps.util.system import get_config_filename_from_env_or_exit

from _util import app_context

@click.command()
@click.option(
    '--dry-run', is_flag=True, help='count but do not delete affected records',
)
@click.argument('minimum_age_in_days', type=int)
def execute(dry_run, minimum_age_in_days):
    latest_occurred_at = get_latest_occurred_at(minimum_age_in_days)

    click.secho(
        f'Deleting all user login events older than {minimum_age_in_days} days '
        f'(i.e. before {latest_occurred_at:%Y-%m-%d %H:%M:%S}) ...'
    )

    num_deleted = delete_user_login_events_before(latest_occurred_at, dry_run)

    click.secho(f'{num_deleted} user login events deleted.')

    if dry_run:
        click.secho(
            f'This was a dry run; no records have been deleted.', fg='yellow'
        )

def get_latest_occurred_at(minimum_age_in_days: int) -> datetime:
    now = datetime.utcnow()
    return now - timedelta(days=minimum_age_in_days)

def delete_user_login_events_before(
    latest_occurred_at: datetime, dry_run: bool
) -> int:
    num_deleted = DbUserEvent.query \
        .filter_by(event_type='user-logged-in') \
        .filter(DbUserEvent.occurred_at <= latest_occurred_at) \
        .delete()

    if not dry_run:
        db.session.commit()

    return num_deleted

if __name__ == '__main__':
    config_filename = get_config_filename_from_env_or_exit()
    with app_context(config_filename):
        execute()

Add script to delete user login events older than a number of days

Response:
#!/usr/bin/env python

"""Delete login user events older than a given number of days.

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from datetime import datetime, timedelta

import click

from byceps.database import db
from byceps.services.user.models.event import UserEvent as DbUserEvent
from byceps.util.system import get_config_filename_from_env_or_exit

from _util import app_context

@click.command()
@click.option(
    '--dry-run', is_flag=True, help='count but do not delete affected records',
)
@click.argument('minimum_age_in_days', type=int)
def execute(dry_run, minimum_age_in_days):
    latest_occurred_at = get_latest_occurred_at(minimum_age_in_days)

    click.secho(
        f'Deleting all user login events older than {minimum_age_in_days} days '
        f'(i.e. before {latest_occurred_at:%Y-%m-%d %H:%M:%S}) ...'
    )

    num_deleted = delete_user_login_events_before(latest_occurred_at, dry_run)

    click.secho(f'{num_deleted} user login events deleted.')

    if dry_run:
        click.secho(
            f'This was a dry run; no records have been deleted.', fg='yellow'
        )

def get_latest_occurred_at(minimum_age_in_days: int) -> datetime:
    now = datetime.utcnow()
    return now - timedelta(days=minimum_age_in_days)

def delete_user_login_events_before(
    latest_occurred_at: datetime, dry_run: bool
) -> int:
    num_deleted = DbUserEvent.query \
        .filter_by(event_type='user-logged-in') \
        .filter(DbUserEvent.occurred_at <= latest_occurred_at) \
        .delete()

    if not dry_run:
        db.session.commit()

    return num_deleted

if __name__ == '__main__':
    config_filename = get_config_filename_from_env_or_exit()
    with app_context(config_filename):
        execute()

Prompt: Add script to delete user login events older than a number of days


#!/usr/bin/env python

# Google Code Jam
# Google Code Jam 2016
# Qualification Round 2016
# Problem B. Revenge of the Pancakes

# Solved all test sets

from __future__ import print_function

def calc_min_flip_step(s):
    grouped_height = 1 + s.count('-+') + s.count('+-')
    if s.endswith('-'):
        return grouped_height
    else:
        return grouped_height - 1

if __name__ == '__main__':
    import os

    samples = [
        '-',
        '-+',
        '+-',
        '+++',
        '--+-'
    ]

    for sample in samples:
        print(calc_min_flip_step(sample))

    data_files = ['B-small-practice',
                  'B-large-practice']
    for f in data_files:
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                  '{0}.in'.format(f)), 'r') as input_file:
            lines = input_file.readlines()
        input_count = int(lines[0].replace('\n' ,''))
        inputs = [line.replace('\n', '') for line in lines[1:]]

        i = 1
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                  '{0}.out'.format(f)), 'w') as output_file:
            for in_ in inputs:
                output_file.write('Case #{0}: {1}\n'.format(i, calc_min_flip_step(in_)))
                i += 1

Add revenge of the pancakes

Add revenge of the pancakes

Response:
#!/usr/bin/env python

# Google Code Jam
# Google Code Jam 2016
# Qualification Round 2016
# Problem B. Revenge of the Pancakes

# Solved all test sets

from __future__ import print_function

def calc_min_flip_step(s):
    grouped_height = 1 + s.count('-+') + s.count('+-')
    if s.endswith('-'):
        return grouped_height
    else:
        return grouped_height - 1

if __name__ == '__main__':
    import os

    samples = [
        '-',
        '-+',
        '+-',
        '+++',
        '--+-'
    ]

    for sample in samples:
        print(calc_min_flip_step(sample))

    data_files = ['B-small-practice',
                  'B-large-practice']
    for f in data_files:
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                  '{0}.in'.format(f)), 'r') as input_file:
            lines = input_file.readlines()
        input_count = int(lines[0].replace('\n' ,''))
        inputs = [line.replace('\n', '') for line in lines[1:]]

        i = 1
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                  '{0}.out'.format(f)), 'w') as output_file:
            for in_ in inputs:
                output_file.write('Case #{0}: {1}\n'.format(i, calc_min_flip_step(in_)))
                i += 1

Prompt: Add revenge of the pancakes


"""Load and parse configuration file."""
import yaml
from io import open

CONFIG = {}

def load_config(config_file):
    """Loads a configuration file."""
    config = {}
    try:
        with open(config_file, 'r') as f:
            content = yaml.load(f, Loader=yaml.FullLoader)
            config.update(content)
            return content
    except IOError as e:
        e.message = 'Could not open configuration file "{}".'.format(config_file)
        raise e

def load_yaml_config(config_file):
    """Load YAML config file

    :param str config_file: The path to the configuration file.

    :returns: A dict of the parsed config file.
    :rtype: dict
    :raises IOError: If the config file cannot be opened.
    """
    try:
        with open(config_file, 'r') as f:
            content = yaml.load(f, Loader=yaml.FullLoader)
            CONFIG.update(content)
            return content
    except IOError as e:
        e.message = 'Could not open configuration file "{}".'.format(config_file)
        raise e

Remove unused file type check

Remove unused file type check

Response:
"""Load and parse configuration file."""
import yaml
from io import open

CONFIG = {}

def load_config(config_file):
    """Loads a configuration file."""
    config = {}
    try:
        with open(config_file, 'r') as f:
            content = yaml.load(f, Loader=yaml.FullLoader)
            config.update(content)
            return content
    except IOError as e:
        e.message = 'Could not open configuration file "{}".'.format(config_file)
        raise e

def load_yaml_config(config_file):
    """Load YAML config file

    :param str config_file: The path to the configuration file.

    :returns: A dict of the parsed config file.
    :rtype: dict
    :raises IOError: If the config file cannot be opened.
    """
    try:
        with open(config_file, 'r') as f:
            content = yaml.load(f, Loader=yaml.FullLoader)
            CONFIG.update(content)
            return content
    except IOError as e:
        e.message = 'Could not open configuration file "{}".'.format(config_file)
        raise e

Prompt:
Remove unused file type check

"""Load and parse configuration file."""
import yaml
from io import open

CONFIG = {}

def load_config(config_file):
    """Loads a configuration file."""
    config = {}
    if type(config_file) is file:
        config.update(yaml.load(config_file, Loader=yaml.FullLoader) or {})
        return config
    else:
        try:
            with open(config_file, 'r') as f:
                content = yaml.load(f, Loader=yaml.FullLoader)
                config.update(content)
                return content
        except IOError as e:
            e.message = 'Could not open configuration file "{}".'.format(config_file)
            raise e

def load_yaml_config(config_file):
    """Load YAML config file

    :param str config_file: The path to the configuration file.

    :returns: A dict of the parsed config file.
    :rtype: dict
    :raises IOError: If the config file cannot be opened.
    """
    if type(config_file) is file:
        CONFIG.update(yaml.load(config_file, Loader=yaml.FullLoader) or {})
        return CONFIG
    else:
        try:
            with open(config_file, 'r') as f:
                content = yaml.load(f, Loader=yaml.FullLoader)
                CONFIG.update(content)
                return content
        except IOError as e:
            e.message = 'Could not open configuration file "{}".'.format(config_file)
            raise e


import unittest
from steam import user

class ProfileTestCase(unittest.TestCase):
    VALID_ID64 = 76561198014028523
    INVALID_ID64 = 123
    # This is weird but there should be no reason that it's invalid
    # So Valve, if you see this, be gewd guys and make 33 bit (condensed)
    # IDs work properly. Or at least put a more appropriate error. Currently
    # It's impossible to distinguish between this and a bad ID (all are code 8)
    WEIRD_ID64 = (VALID_ID64 >> 33 << 33) ^ VALID_ID64

class VanityTestCase(unittest.TestCase):
    VALID_VANITY = "stragglerastic"
    INVALID_VANITY = "*F*SDF9"

    def test_invalid_vanity(self):
        vanity = user.vanity_url(self.INVALID_VANITY)
        self.assertRaises(user.VanityError, lambda: vanity.id64)

    def test_pathed_vanity(self):
        vanity = user.vanity_url('/' + self.VALID_VANITY + '/')
        self.assertEqual(vanity.id64, ProfileTestCase.VALID_ID64)

    def test_valid_vanity(self):
        vanity = user.vanity_url(self.VALID_VANITY)
        self.assertEqual(vanity.id64, ProfileTestCase.VALID_ID64)

class ProfileIdTestCase(ProfileTestCase):
    def test_invalid_id(self):
        profile = user.profile(self.INVALID_ID64)
        self.assertRaises(user.ProfileNotFoundError, lambda: profile.id64)

    def test_pathed_id(self):
        profile = user.profile('/' + str(self.VALID_ID64) + '/')
        self.assertEqual(profile.id64, self.VALID_ID64)

    def test_valid_id(self):
        profile = user.profile(self.VALID_ID64)
        self.assertEqual(profile.id64, self.VALID_ID64)

    def test_weird_id(self):
        profile = user.profile(self.WEIRD_ID64)
        self.assertRaises(user.ProfileNotFoundError, lambda: profile.id64)

Add initial steam.user test fixtures

Add initial steam.user test fixtures

Response:
import unittest
from steam import user

class ProfileTestCase(unittest.TestCase):
    VALID_ID64 = 76561198014028523
    INVALID_ID64 = 123
    # This is weird but there should be no reason that it's invalid
    # So Valve, if you see this, be gewd guys and make 33 bit (condensed)
    # IDs work properly. Or at least put a more appropriate error. Currently
    # It's impossible to distinguish between this and a bad ID (all are code 8)
    WEIRD_ID64 = (VALID_ID64 >> 33 << 33) ^ VALID_ID64

class VanityTestCase(unittest.TestCase):
    VALID_VANITY = "stragglerastic"
    INVALID_VANITY = "*F*SDF9"

    def test_invalid_vanity(self):
        vanity = user.vanity_url(self.INVALID_VANITY)
        self.assertRaises(user.VanityError, lambda: vanity.id64)

    def test_pathed_vanity(self):
        vanity = user.vanity_url('/' + self.VALID_VANITY + '/')
        self.assertEqual(vanity.id64, ProfileTestCase.VALID_ID64)

    def test_valid_vanity(self):
        vanity = user.vanity_url(self.VALID_VANITY)
        self.assertEqual(vanity.id64, ProfileTestCase.VALID_ID64)

class ProfileIdTestCase(ProfileTestCase):
    def test_invalid_id(self):
        profile = user.profile(self.INVALID_ID64)
        self.assertRaises(user.ProfileNotFoundError, lambda: profile.id64)

    def test_pathed_id(self):
        profile = user.profile('/' + str(self.VALID_ID64) + '/')
        self.assertEqual(profile.id64, self.VALID_ID64)

    def test_valid_id(self):
        profile = user.profile(self.VALID_ID64)
        self.assertEqual(profile.id64, self.VALID_ID64)

    def test_weird_id(self):
        profile = user.profile(self.WEIRD_ID64)
        self.assertRaises(user.ProfileNotFoundError, lambda: profile.id64)

Prompt: Add initial steam.user test fixtures


import bbcode
import markdown
import html

from c2corg_ui.format.wikilinks import C2CWikiLinkExtension
from markdown.extensions.nl2br import Nl2BrExtension
from markdown.extensions.toc import TocExtension

_markdown_parser = None
_bbcode_parser = None

def _get_markdown_parser():
    global _markdown_parser
    if not _markdown_parser:
        extensions = [
            C2CWikiLinkExtension(),
            Nl2BrExtension(),
            TocExtension(marker='[toc]', baselevel=2),
        ]
        _markdown_parser = markdown.Markdown(output_format='xhtml5',
                                             extensions=extensions)
    return _markdown_parser

def _get_bbcode_parser():
    global _bbcode_parser
    if not _bbcode_parser:
        _bbcode_parser = bbcode.Parser(escape_html=False, newline='\n')
    return _bbcode_parser

def parse_code(text, md=True, bb=True):
    if md:
        text = _get_markdown_parser().convert(text)
    if bb:
        text = _get_bbcode_parser().format(text)
    return text

def sanitize(text):
    return html.escape(text)

Response:
import bbcode
import markdown
import html

from c2corg_ui.format.wikilinks import C2CWikiLinkExtension
from markdown.extensions.nl2br import Nl2BrExtension
from markdown.extensions.toc import TocExtension

_markdown_parser = None
_bbcode_parser = None

def _get_markdown_parser():
    global _markdown_parser
    if not _markdown_parser:
        extensions = [
            C2CWikiLinkExtension(),
            Nl2BrExtension(),
            TocExtension(marker='[toc]', baselevel=2),
        ]
        _markdown_parser = markdown.Markdown(output_format='xhtml5',
                                             extensions=extensions)
    return _markdown_parser

def _get_bbcode_parser():
    global _bbcode_parser
    if not _bbcode_parser:
        _bbcode_parser = bbcode.Parser(escape_html=False, newline='\n')
    return _bbcode_parser

def parse_code(text, md=True, bb=True):
    if md:
        text = _get_markdown_parser().convert(text)
    if bb:
        text = _get_bbcode_parser().format(text)
    return text

def sanitize(text):
    return html.escape(text)

Prompt:
Enable markdown extensions for TOC and linebreaks

import bbcode
import markdown
import html

from c2corg_ui.format.wikilinks import C2CWikiLinkExtension

_markdown_parser = None
_bbcode_parser = None

def _get_markdown_parser():
    global _markdown_parser
    if not _markdown_parser:
        extensions = [
            C2CWikiLinkExtension(),
        ]
        _markdown_parser = markdown.Markdown(output_format='xhtml5',
                                             extensions=extensions)
    return _markdown_parser

def _get_bbcode_parser():
    global _bbcode_parser
    if not _bbcode_parser:
        _bbcode_parser = bbcode.Parser(escape_html=False, newline='\n')
    return _bbcode_parser

def parse_code(text, md=True, bb=True):
    if md:
        text = _get_markdown_parser().convert(text)
    if bb:
        text = _get_bbcode_parser().format(text)
    return text

def sanitize(text):
    return html.escape(text)


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

from django.db import migrations, models

class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='article',
            name='slug',
            field=models.SlugField(max_length=255),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='article',
            name='title',
            field=models.CharField(max_length=255),
            preserve_default=False,
        ),
    ]

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

from django.db import migrations, models

class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='article',
            name='slug',
            field=models.SlugField(max_length=255),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='article',
            name='title',
            field=models.CharField(max_length=255),
            preserve_default=False,
        ),
    ]

Prompt:
Remove vestigial (?) "woo" default for article slug and title fields.

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

from django.db import migrations, models

class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='article',
            name='slug',
            field=models.SlugField(max_length=255, default='woo'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='article',
            name='title',
            field=models.CharField(max_length=255, default='woo'),
            preserve_default=False,
        ),
    ]


import smugmug
import unittest

class MockNode(object):
  def __init__(self):
    self._reset_times = 0

  def reset_cache(self):
    self._reset_times += 1

class TestChildCacheGarbageCollector(unittest.TestCase):

  def test_clears_child_cache(self):
    gc = smugmug.ChildCacheGarbageCollector(3)
    nodes = [MockNode(), MockNode(), MockNode(), MockNode(), MockNode()]
    gc.visited(nodes[0])
    gc.visited(nodes[1])
    gc.visited(nodes[2])
    gc.visited(nodes[3])
    gc.visited(nodes[4])

    self.assertEqual(nodes[0]._reset_times, 1)
    self.assertEqual(nodes[1]._reset_times, 1)
    self.assertEqual(nodes[2]._reset_times, 0)
    self.assertEqual(nodes[3]._reset_times, 0)
    self.assertEqual(nodes[4]._reset_times, 0)

  def test_repeated_visit_are_ignored(self):
    gc = smugmug.ChildCacheGarbageCollector(2)
    nodes = [MockNode(), MockNode(), MockNode()]
    gc.visited(nodes[0])
    gc.visited(nodes[1])
    gc.visited(nodes[2])
    gc.visited(nodes[2])
    gc.visited(nodes[2])

    self.assertEqual(nodes[0]._reset_times, 1)
    self.assertEqual(nodes[1]._reset_times, 0)
    self.assertEqual(nodes[2]._reset_times, 0)

Add a unit test for the ChildCacheGarbageColleector class.

Response:
import smugmug
import unittest

class MockNode(object):
  def __init__(self):
    self._reset_times = 0

  def reset_cache(self):
    self._reset_times += 1

class TestChildCacheGarbageCollector(unittest.TestCase):

  def test_clears_child_cache(self):
    gc = smugmug.ChildCacheGarbageCollector(3)
    nodes = [MockNode(), MockNode(), MockNode(), MockNode(), MockNode()]
    gc.visited(nodes[0])
    gc.visited(nodes[1])
    gc.visited(nodes[2])
    gc.visited(nodes[3])
    gc.visited(nodes[4])

    self.assertEqual(nodes[0]._reset_times, 1)
    self.assertEqual(nodes[1]._reset_times, 1)
    self.assertEqual(nodes[2]._reset_times, 0)
    self.assertEqual(nodes[3]._reset_times, 0)
    self.assertEqual(nodes[4]._reset_times, 0)

  def test_repeated_visit_are_ignored(self):
    gc = smugmug.ChildCacheGarbageCollector(2)
    nodes = [MockNode(), MockNode(), MockNode()]
    gc.visited(nodes[0])
    gc.visited(nodes[1])
    gc.visited(nodes[2])
    gc.visited(nodes[2])
    gc.visited(nodes[2])

    self.assertEqual(nodes[0]._reset_times, 1)
    self.assertEqual(nodes[1]._reset_times, 0)
    self.assertEqual(nodes[2]._reset_times, 0)

Prompt: Add a unit test for the ChildCacheGarbageColleector class.


from django.db import models
from django.utils import timezone

class Task(models.Model):

    EQUALS_CHECK = 'EQ'
    REGEX_CHECK = 'RE'

    CHECK_CHOICES = (
        (EQUALS_CHECK, 'Equals'),
        (REGEX_CHECK, 'Regex'),
    )

    title_ru = models.CharField(null=False, blank=False, max_length=256)
    title_en = models.CharField(null=False, blank=False, max_length=256)
    category = models.CharField(null=False, blank=False, max_length=256)
    cost = models.IntegerField(null=False, blank=False)
    desc_ru = models.TextField(null=False, blank=False)
    desc_en = models.TextField(null=False, blank=False)
    writeup_ru = models.TextField(null=False, blank=False)
    writeup_en = models.TextField(null=False, blank=False)
    flag = models.CharField(max_length=1024)
    is_case_insensitive_check = models.BooleanField(default=False)
    is_trimmed_check = models.BooleanField(default=False)
    check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES)
    created_at = models.DateTimeField(null=False, blank=True)

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.created_at = timezone.now()
        return super(Task, self).save(*args, **kwargs)

Add new fields to the task model

Add new fields to the task model

Response:
from django.db import models
from django.utils import timezone

class Task(models.Model):

    EQUALS_CHECK = 'EQ'
    REGEX_CHECK = 'RE'

    CHECK_CHOICES = (
        (EQUALS_CHECK, 'Equals'),
        (REGEX_CHECK, 'Regex'),
    )

    title_ru = models.CharField(null=False, blank=False, max_length=256)
    title_en = models.CharField(null=False, blank=False, max_length=256)
    category = models.CharField(null=False, blank=False, max_length=256)
    cost = models.IntegerField(null=False, blank=False)
    desc_ru = models.TextField(null=False, blank=False)
    desc_en = models.TextField(null=False, blank=False)
    writeup_ru = models.TextField(null=False, blank=False)
    writeup_en = models.TextField(null=False, blank=False)
    flag = models.CharField(max_length=1024)
    is_case_insensitive_check = models.BooleanField(default=False)
    is_trimmed_check = models.BooleanField(default=False)
    check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES)
    created_at = models.DateTimeField(null=False, blank=True)

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.created_at = timezone.now()
        return super(Task, self).save(*args, **kwargs)

Prompt:
Add new fields to the task model

from django.db import models
from django.utils import timezone

class Task(models.Model):

    EQUALS_CHECK = 'EQ'
    REGEX_CHECK = 'RE'

    CHECK_CHOICES = (
        (EQUALS_CHECK, 'Equals'),
        (REGEX_CHECK, 'Regex'),
    )

    title_ru = models.CharField(null=False, blank=False, max_length=256)
    title_en = models.CharField(null=False, blank=False, max_length=256)
    desc_ru = models.TextField(null=False, blank=False)
    desc_en = models.TextField(null=False, blank=False)
    writeup_ru = models.TextField(null=False, blank=False)
    writeup_en = models.TextField(null=False, blank=False)
    flag = models.CharField(max_length=1024)
    is_case_insensitive_check = models.BooleanField(default=False)
    is_trimmed_check = models.BooleanField(default=False)
    check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES)
    created_at = models.DateTimeField(null=False, blank=True)

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.created_at = timezone.now()
        return super(Task, self).save(*args, **kwargs)


import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)

import django
from django.test.utils import get_runner
from django.conf import settings

def runtests():
    if django.VERSION[0] == 1 and django.VERSION[1] < 7:
        from django.test.utils import setup_test_environment
        setup_test_environment()

    if django.VERSION[0] == 1 and django.VERSION[1] >= 7:
        django.setup()

    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(['geelweb.django.editos'])
    sys.exit(bool(failures))

Response:
import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)

import django
from django.test.utils import get_runner
from django.conf import settings

def runtests():
    if django.VERSION[0] == 1 and django.VERSION[1] < 7:
        from django.test.utils import setup_test_environment
        setup_test_environment()

    if django.VERSION[0] == 1 and django.VERSION[1] >= 7:
        django.setup()

    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(['geelweb.django.editos'])
    sys.exit(bool(failures))

Prompt:
Upgrade to test using django 1.7 and 1.8

import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)

from django.test.utils import get_runner
from django.conf import settings

def runtests():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['geelweb.django.editos'])
    sys.exit(bool(failures))


import pylibmc
from pylibmc.test import make_test_client
from tests import PylibmcTestCase
from nose.tools import eq_, ok_

class ClientTests(PylibmcTestCase):
    def test_zerokey(self):
        bc = make_test_client(binary=True)
        k = "\x00\x01"
        ok_(bc.set(k, "test"))
        rk = bc.get_multi([k]).keys()[0]
        eq_(k, rk)

    def test_cas(self):
        k = "testkey"
        mc = make_test_client(binary=False, behaviors={"cas": True})
        ok_(mc.set(k, 0))
        while True:
            rv, cas = mc.gets(k)
            ok_(mc.cas(k, rv + 1, cas))
            if rv == 10:
                break

Add tests for CAS and other things

Add tests for CAS and other things

Refs #63

Response:
import pylibmc
from pylibmc.test import make_test_client
from tests import PylibmcTestCase
from nose.tools import eq_, ok_

class ClientTests(PylibmcTestCase):
    def test_zerokey(self):
        bc = make_test_client(binary=True)
        k = "\x00\x01"
        ok_(bc.set(k, "test"))
        rk = bc.get_multi([k]).keys()[0]
        eq_(k, rk)

    def test_cas(self):
        k = "testkey"
        mc = make_test_client(binary=False, behaviors={"cas": True})
        ok_(mc.set(k, 0))
        while True:
            rv, cas = mc.gets(k)
            ok_(mc.cas(k, rv + 1, cas))
            if rv == 10:
                break

Prompt:
Add tests for CAS and other things

Refs #63


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import json

import six
import websocket

from polyaxon_client.logger import logger

class SocketTransportMixin(object):
    """Socket operations transport."""
    def socket(self, url, message_handler, headers=None):
        webs = websocket.WebSocketApp(
            url,
            on_message=lambda ws, message: self._on_message(message_handler, message),
            on_error=self._on_error,
            on_close=self._on_close,
            header=self._get_headers(headers)
        )
        return webs

    def stream(self, url, message_handler, headers=None):
        webs = self.socket(url=url, message_handler=message_handler, headers=headers)
        webs.run_forever(ping_interval=30, ping_timeout=10)

    def _on_message(self, message_handler, message):
        if message_handler and message:
            if not isinstance(message, six.string_types):
                message = message.decode('utf-8')
            message_handler(json.loads(message))

    @staticmethod
    def _on_error(ws, error):
        if isinstance(error, (KeyboardInterrupt, SystemExit)):
            logger.info('Quitting... The session will be running in the background.')
        else:
            logger.debug('Termination cause: %s', error)
            logger.debug('Session disconnected.')

    @staticmethod
    def _on_close(ws):
        logger.info('Session ended')

Check if string before decoding

Check if string before decoding

Response:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import json

import six
import websocket

from polyaxon_client.logger import logger

class SocketTransportMixin(object):
    """Socket operations transport."""
    def socket(self, url, message_handler, headers=None):
        webs = websocket.WebSocketApp(
            url,
            on_message=lambda ws, message: self._on_message(message_handler, message),
            on_error=self._on_error,
            on_close=self._on_close,
            header=self._get_headers(headers)
        )
        return webs

    def stream(self, url, message_handler, headers=None):
        webs = self.socket(url=url, message_handler=message_handler, headers=headers)
        webs.run_forever(ping_interval=30, ping_timeout=10)

    def _on_message(self, message_handler, message):
        if message_handler and message:
            if not isinstance(message, six.string_types):
                message = message.decode('utf-8')
            message_handler(json.loads(message))

    @staticmethod
    def _on_error(ws, error):
        if isinstance(error, (KeyboardInterrupt, SystemExit)):
            logger.info('Quitting... The session will be running in the background.')
        else:
            logger.debug('Termination cause: %s', error)
            logger.debug('Session disconnected.')

    @staticmethod
    def _on_close(ws):
        logger.info('Session ended')

Prompt:
Check if string before decoding

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import json

import websocket

from polyaxon_client.logger import logger

class SocketTransportMixin(object):
    """Socket operations transport."""
    def socket(self, url, message_handler, headers=None):
        webs = websocket.WebSocketApp(
            url,
            on_message=lambda ws, message: self._on_message(message_handler, message),
            on_error=self._on_error,
            on_close=self._on_close,
            header=self._get_headers(headers)
        )
        return webs

    def stream(self, url, message_handler, headers=None):
        webs = self.socket(url=url, message_handler=message_handler, headers=headers)
        webs.run_forever(ping_interval=30, ping_timeout=10)

    def _on_message(self, message_handler, message):
        if message_handler and message:
            message_handler(json.loads(message.decode('utf-8')))

    @staticmethod
    def _on_error(ws, error):
        if isinstance(error, (KeyboardInterrupt, SystemExit)):
            logger.info('Quitting... The session will be running in the background.')
        else:
            logger.debug('Termination cause: %s', error)
            logger.debug('Session disconnected.')

    @staticmethod
    def _on_close(ws):
        logger.info('Session ended')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings

VERSION = (0, 0, 1)

__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"

__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"
__copyright__ = u"Copyright 2013, YACOWS"

settings.INSTALLED_APPS += ('opps.article',
        'opps.image',
        'opps.channel',
        'opps.source',
        'redactor',
        'tagging',)

settings.REDACTOR_OPTIONS = {'lang': 'en'}
settings.REDACTOR_UPLOAD = 'uploads/'

Add installed app on opps init

Add installed app on opps init

Response:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings

VERSION = (0, 0, 1)

__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"

__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"
__copyright__ = u"Copyright 2013, YACOWS"

settings.INSTALLED_APPS += ('opps.article',
        'opps.image',
        'opps.channel',
        'opps.source',
        'redactor',
        'tagging',)

settings.REDACTOR_OPTIONS = {'lang': 'en'}
settings.REDACTOR_UPLOAD = 'uploads/'

Prompt:
Add installed app on opps init

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

VERSION = (0, 0, 1)

__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"

__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"
__copyright__ = u"Copyright 2013, YACOWS"


from fabric.api import cd, run, sudo, env, execute, task
from datetime import datetime

env.hosts = ['andrewlorente.com']
apps = {
    'bloge': ['bloge@andrewlorente.com'],
    'andrewlorente': ['andrewlorente@andrewlorente.com'],
}

@task
def deploy(app):
    if app not in apps.keys():
        raise Exception("Unknown deploy target '{0}'".format(app))

    release_id = datetime.now().strftime("%Y%m%d%H%M%S")

    execute(build, app, release_id, hosts=apps[app])
    execute(release, app, hosts=['alorente@andrewlorente.com'])

def build(app, release_id):
    release_dir = "/u/apps/{0}/releases/{1}".format(app, release_id)
    repo = "https://github.com/AndrewLorente/{0}.git".format(app)
    run("git clone -q {0} {1}".format(repo, release_dir))

    with cd(release_dir):
        run("cabal update")
        run("cabal install --constraint 'template-haskell installed' "
            "--dependencies-only --force-reinstall")
        run("cabal configure")
        run("cabal build")
    run("ln -nfs {0} /u/apps/{1}/current".format(release_dir, app))

def release(app):
    sudo("initctl restart " + app)

Response:
from fabric.api import cd, run, sudo, env, execute, task
from datetime import datetime

env.hosts = ['andrewlorente.com']
apps = {
    'bloge': ['bloge@andrewlorente.com'],
    'andrewlorente': ['andrewlorente@andrewlorente.com'],
}

@task
def deploy(app):
    if app not in apps.keys():
        raise Exception("Unknown deploy target '{0}'".format(app))

    release_id = datetime.now().strftime("%Y%m%d%H%M%S")

    execute(build, app, release_id, hosts=apps[app])
    execute(release, app, hosts=['alorente@andrewlorente.com'])

def build(app, release_id):
    release_dir = "/u/apps/{0}/releases/{1}".format(app, release_id)
    repo = "https://github.com/AndrewLorente/{0}.git".format(app)
    run("git clone -q {0} {1}".format(repo, release_dir))

    with cd(release_dir):
        run("cabal update")
        run("cabal install --constraint 'template-haskell installed' "
            "--dependencies-only --force-reinstall")
        run("cabal configure")
        run("cabal build")
    run("ln -nfs {0} /u/apps/{1}/current".format(release_dir, app))

def release(app):
    sudo("initctl restart " + app)

Prompt:
Hide support functions from the public interface

from fabric.api import cd, run, sudo, env, execute
from datetime import datetime

env.hosts = ['andrewlorente.com']
apps = {
    'bloge': ['bloge@andrewlorente.com'],
    'andrewlorente': ['andrewlorente@andrewlorente.com'],
}

def deploy(app):
    if app not in apps.keys():
        raise Exception("Unknown deploy target '{0}'".format(app))

    release_id = datetime.now().strftime("%Y%m%d%H%M%S")

    execute(build, app, release_id, hosts=apps[app])
    execute(release, app, hosts=['alorente@andrewlorente.com'])

def build(app, release_id):
    release_dir = "/u/apps/{0}/releases/{1}".format(app, release_id)
    repo = "https://github.com/AndrewLorente/{0}.git".format(app)
    run("git clone -q {0} {1}".format(repo, release_dir))

    with cd(release_dir):
        run("cabal update")
        run("cabal install --constraint 'template-haskell installed' "
            "--dependencies-only --force-reinstall")
        run("cabal configure")
        run("cabal build")
    run("ln -nfs {0} /u/apps/{1}/current".format(release_dir, app))

def release(app):
    sudo("initctl restart " + app)


Add test for BCH electrum header

Add test for BCH electrum header

Response:
import electrumx.lib.coins as coins

def test_bitcoin_cash():
    raw_header = bytes.fromhex(
        "00000020df975c121dcbc18bbb7ddfd0419fc368b45db86b48c87e0"
        "1000000000000000036ae3dd40a10a40d3050de13ca546a2f81589d"
        "e2d2f317925a43a115437e2381f5bf535b94da0118ac8df8c5"
    )
    height = 540000
    electrum_header = {
        'block_height': 540000,
        'version': 536870912,
        'prev_block_hash':
        '0000000000000000017ec8486bb85db468c39f41d0df7dbb8bc1cb1d125c97df',
        'merkle_root':
        '81237e4315a1435a9217f3d2e29d58812f6a54ca13de50300da4100ad43dae36',
        'timestamp': 1532215285,
        'bits': 402774676,
        'nonce': 3321400748
    }

    assert coins.BitcoinCash.electrum_header(
        raw_header, height) == electrum_header

Prompt: Add test for BCH electrum header