from setuptools import setup, find_packages

package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
      version = "0.2.0",
      description = "A django HTML 5 audio player",
      author = "Justin Michalicek",
      author_email = "jmichalicek@gmail.com",
      url = "https://github.com/jmichalicek/djukebox/",
      license = "www.opensource.org/licenses/bsd-license.php",
      packages = find_packages(),
      #'package' package must contain files (see list above)
      package_data = {'djukebox' : package_data },
      install_requires = dependencies,
      long_description = """A HTML 5 audio player using Django"""
      #This next part it for the Cheese Shop, look a little down the page.
      #classifiers = []
)

Response:
from setuptools import setup, find_packages

package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
      version = "0.2.0",
      description = "A django HTML 5 audio player",
      author = "Justin Michalicek",
      author_email = "jmichalicek@gmail.com",
      url = "https://github.com/jmichalicek/djukebox/",
      license = "www.opensource.org/licenses/bsd-license.php",
      packages = find_packages(),
      #'package' package must contain files (see list above)
      package_data = {'djukebox' : package_data },
      install_requires = dependencies,
      long_description = """A HTML 5 audio player using Django"""
      #This next part it for the Cheese Shop, look a little down the page.
      #classifiers = []
)

Prompt:
Set full versions on all dependencies and updated most to latest version

from setuptools import setup, find_packages

package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['pillow', 'django-celery==2.5.5', 'mutagen', 'simplejson', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
      version = "0.2.0",
      description = "A django HTML 5 audio player",
      author = "Justin Michalicek",
      author_email = "jmichalicek@gmail.com",
      url = "https://github.com/jmichalicek/djukebox/",
      license = "www.opensource.org/licenses/bsd-license.php",
      packages = find_packages(),
      #'package' package must contain files (see list above)
      package_data = {'djukebox' : package_data },
      install_requires = dependencies,
      long_description = """A HTML 5 audio player using Django"""
      #This next part it for the Cheese Shop, look a little down the page.
      #classifiers = []
)


from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement

class OutputIntegrationTestCase(TestCase):
    """
    Tests to make sure that output adapters
    function correctly when using Django.
    """

    def test_output_format_adapter(self):
        from chatterbot.output import OutputFormatAdapter

        adapter = OutputFormatAdapter()

        statement = Statement(text='_')
        result = adapter.process_response(statement)

        self.assertEqual(result.text, '_')

Test that the output format adapter works with Django

Response:
from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement

class OutputIntegrationTestCase(TestCase):
    """
    Tests to make sure that output adapters
    function correctly when using Django.
    """

    def test_output_format_adapter(self):
        from chatterbot.output import OutputFormatAdapter

        adapter = OutputFormatAdapter()

        statement = Statement(text='_')
        result = adapter.process_response(statement)

        self.assertEqual(result.text, '_')

Prompt: Test that the output format adapter works with Django


#!/usr/bin/python

import sys

def fib(n):
 a,b = 0,1
 yield a
 if n>0 :
  yield b
  for i in range(2,n+1):
   a,b = b, a+b
   yield b

num = int(sys.argv[1])
gen = fib(num)
for i in gen:
 print i

Add function for Fibonacci sequence

Add function for Fibonacci sequence

Response:
#!/usr/bin/python

import sys

def fib(n):
 a,b = 0,1
 yield a
 if n>0 :
  yield b
  for i in range(2,n+1):
   a,b = b, a+b
   yield b

num = int(sys.argv[1])
gen = fib(num)
for i in gen:
 print i

Prompt: Add function for Fibonacci sequence


from cyclone import web
from oonib.deck import handlers
from oonib import config

deckAPI = [
    (r"/deck", handlers.DeckListHandler),
    (r"/deck/([a-z0-9]{64})$", handlers.DeckDescHandler),
    (r"/deck/([a-z0-9]{64})/yaml$", web.StaticFileHandler, {"path":
        config.main.deck_dir}),
]

Use sha256 as per oonib.md spec

Use sha256 as per oonib.md spec

Response:
from cyclone import web
from oonib.deck import handlers
from oonib import config

deckAPI = [
    (r"/deck", handlers.DeckListHandler),
    (r"/deck/([a-z0-9]{64})$", handlers.DeckDescHandler),
    (r"/deck/([a-z0-9]{64})/yaml$", web.StaticFileHandler, {"path":
        config.main.deck_dir}),
]

Prompt:
Use sha256 as per oonib.md spec

from cyclone import web
from oonib.deck import handlers
from oonib import config

deckAPI = [
    (r"/deck", handlers.DeckListHandler),
    (r"/deck/([a-z0-9]{40})$", handlers.DeckDescHandler),
    (r"/deck/([a-z0-9]{40})/yaml$", web.StaticFileHandler, {"path":
        config.main.deck_dir}),
]


from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest

class TestMoviePepper(unittest.TestCase):

    def test_crawl(self):
        try:
            shutil.rmtree('./movie_scrape/crawls')
            os.remove('./movie_scrape/imdb.json')
            os.remove('./db.json')
        except FileNotFoundError:
            pass
        except OSError:
            pass

        subprocess.run(['START_URL="http://www.imdb.com/search/title?role=nm0000095&title_type=feature&user_rating=8.0,10" ./scrap.sh'], cwd="./movie_scrape/", shell=True)

        try:
            with open('./movie_scrape/imdb.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

    def test_tfidf_lsa(self):
        calculate_corpus_var(max_df=200, min_df=2, n_components=10, max_features=None)

        try:
            with open('./db.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

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

Add a basic crawler and tfidf_lsa creation test

Response:
from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest

class TestMoviePepper(unittest.TestCase):

    def test_crawl(self):
        try:
            shutil.rmtree('./movie_scrape/crawls')
            os.remove('./movie_scrape/imdb.json')
            os.remove('./db.json')
        except FileNotFoundError:
            pass
        except OSError:
            pass

        subprocess.run(['START_URL="http://www.imdb.com/search/title?role=nm0000095&title_type=feature&user_rating=8.0,10" ./scrap.sh'], cwd="./movie_scrape/", shell=True)

        try:
            with open('./movie_scrape/imdb.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

    def test_tfidf_lsa(self):
        calculate_corpus_var(max_df=200, min_df=2, n_components=10, max_features=None)

        try:
            with open('./db.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

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

Prompt: Add a basic crawler and tfidf_lsa creation test


import csv

class Table():
    '''A Table is an object which represents a 2-dimensional CSV file. Both rows
    and columns can be accessed via their key as in a dictionary. This means that
    keys cannot appear as both a row and column label.'''

    def __init__(self, filename):
        self._internal_table = self.load_from_filename(filename)

    def load_from_filename(self, filename):
        '''Load a CSV file into a list of lists. The following CSV:
            ,a,b,c
           d,1,2,3
           e,4,5,6
           f,7,8,9
        would become the list:
           [['', 'a', 'b', 'c'],
            ['d', '1', '2', '3'] ...]'''
        with open(filename, 'r') as f:
            reader = csv.reader(f)
            return [row for row in reader]

    def get_row(self, key):
        '''Gets a list containing all elements of the row specified by key.
        Returns a ValueError if the row doesn't exist.'''
        for row in self._internal_table:
            if row[0] == key:
                return row[1:]
        raise ValueError('Row not found')

    def get_column(self, key):
        '''Gets a list containing all elements of the column specified by key.
        Returns a ValueError if the column doesn't exist.'''
        for i, column in enumerate(self._internal_table[0]):
            if column == key:
                return [row[i] for row in self._internal_table[1:]]
        raise ValueError('Column not found')

    def __getitem__(self, key):
        '''Returns the row or column linked to the given key, accessed using
        subscript notation.'''
        if not isinstance(key, str):
            raise TypeError('Key must be a string')

        try:
            return self.get_row(key)
        except ValueError:
            try:
                return self.get_column(key)
            except ValueError:
                raise ValueError('Key not found in table')

Create Table object for representing phonetic inventory

Response:
import csv

class Table():
    '''A Table is an object which represents a 2-dimensional CSV file. Both rows
    and columns can be accessed via their key as in a dictionary. This means that
    keys cannot appear as both a row and column label.'''

    def __init__(self, filename):
        self._internal_table = self.load_from_filename(filename)

    def load_from_filename(self, filename):
        '''Load a CSV file into a list of lists. The following CSV:
            ,a,b,c
           d,1,2,3
           e,4,5,6
           f,7,8,9
        would become the list:
           [['', 'a', 'b', 'c'],
            ['d', '1', '2', '3'] ...]'''
        with open(filename, 'r') as f:
            reader = csv.reader(f)
            return [row for row in reader]

    def get_row(self, key):
        '''Gets a list containing all elements of the row specified by key.
        Returns a ValueError if the row doesn't exist.'''
        for row in self._internal_table:
            if row[0] == key:
                return row[1:]
        raise ValueError('Row not found')

    def get_column(self, key):
        '''Gets a list containing all elements of the column specified by key.
        Returns a ValueError if the column doesn't exist.'''
        for i, column in enumerate(self._internal_table[0]):
            if column == key:
                return [row[i] for row in self._internal_table[1:]]
        raise ValueError('Column not found')

    def __getitem__(self, key):
        '''Returns the row or column linked to the given key, accessed using
        subscript notation.'''
        if not isinstance(key, str):
            raise TypeError('Key must be a string')

        try:
            return self.get_row(key)
        except ValueError:
            try:
                return self.get_column(key)
            except ValueError:
                raise ValueError('Key not found in table')

Prompt: Create Table object for representing phonetic inventory


from praw.models import ModmailConversation

from ... import UnitTest

class TestModmailConversation(UnitTest):
    def test_parse(self):
        conversation = ModmailConversation(self.reddit,
                                           _data={'id': 'ik72'})
        assert str(conversation) == 'ik72'

Test that ModmailConversation.id is preserved after fetch

Response:
from praw.models import ModmailConversation

from ... import UnitTest

class TestModmailConversation(UnitTest):
    def test_parse(self):
        conversation = ModmailConversation(self.reddit,
                                           _data={'id': 'ik72'})
        assert str(conversation) == 'ik72'

Prompt: Test that ModmailConversation.id is preserved after fetch


Response:
__all__ = (
    'FeatureExtraction'
)

Prompt:
Resolve import issue in color_normalization_test

from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample

__all__ = (
    'FeatureExtraction'
)


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

import pbr.version

__version__ = pbr.version.VersionInfo('python-keystoneclient').version_string()

Fix --version to output version

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

import pbr.version

__version__ = pbr.version.VersionInfo('python-keystoneclient').version_string()

Prompt:
Fix --version to output version

Change-Id: I7d8dc83ac7c2ad7519633d136c1c32ce8537dce8
Fixes: bug 1182675

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

import inspect
import os

def _get_client_version():
    """Read version from versioninfo file."""
    mod_abspath = inspect.getabsfile(inspect.currentframe())
    client_path = os.path.dirname(mod_abspath)
    version_path = os.path.join(client_path, 'versioninfo')

    if os.path.exists(version_path):
        version = open(version_path).read().strip()
    else:
        version = "Unknown, couldn't find versioninfo file at %s"\
                  % version_path

    return version

__version__ = _get_client_version()


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter

path = "downloads"

class OnlineparticipationdatasetPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        if not os.path.isdir(path):
            os.makedirs(path)
        self.file = open("downloads/items_"+spider.name+".json", 'wb')
        self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

Create path if it doesnt exists

Create path if it doesnt exists

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter

path = "downloads"

class OnlineparticipationdatasetPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        if not os.path.isdir(path):
            os.makedirs(path)
        self.file = open("downloads/items_"+spider.name+".json", 'wb')
        self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

Prompt:
Create path if it doesnt exists

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter

class OnlineparticipationdatasetPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        self.file = open("downloads/items_"+spider.name+".json", 'wb')
        self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item


# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
            email_send_activation, email_activate, email_make_primary

#add an email to a User account
urlpatterns = patterns('',
    url(
        r'^email/add/$',
        email_add,
        name='emailmgr_email_add'
        ),
    url(
        r'^email/send_activation/(?P<identifier>\w+)/$',
        email_send_activation,
        name='emailmgr_email_send_activation'
        ),
    url(
        r'^email/activate/(?P<identifier>\w+)/$',
        email_activate,
        name='emailmgr_email_activate'
        ),
    url(
        r'^email/make_primary/(?P<identifier>\w+)/$',
        email_make_primary,
        name='emailmgr_email_make_primary'
        ),
    url(
        r'^email/delete/(?P<identifier>\w+)/$',
        email_delete,
        name='emailmgr_email_delete'
        ),
    url(
        r'^email/$',
        email_list,
        name='emailmgr_email_list'
        ),
)

Fix import for django 1.6

Fix import for django 1.6

Response:
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
            email_send_activation, email_activate, email_make_primary

#add an email to a User account
urlpatterns = patterns('',
    url(
        r'^email/add/$',
        email_add,
        name='emailmgr_email_add'
        ),
    url(
        r'^email/send_activation/(?P<identifier>\w+)/$',
        email_send_activation,
        name='emailmgr_email_send_activation'
        ),
    url(
        r'^email/activate/(?P<identifier>\w+)/$',
        email_activate,
        name='emailmgr_email_activate'
        ),
    url(
        r'^email/make_primary/(?P<identifier>\w+)/$',
        email_make_primary,
        name='emailmgr_email_make_primary'
        ),
    url(
        r'^email/delete/(?P<identifier>\w+)/$',
        email_delete,
        name='emailmgr_email_delete'
        ),
    url(
        r'^email/$',
        email_list,
        name='emailmgr_email_list'
        ),
)

Prompt:
Fix import for django 1.6
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
            email_send_activation, email_activate, email_make_primary

#add an email to a User account
urlpatterns = patterns('',
    url(
        r'^email/add/$',
        email_add,
        name='emailmgr_email_add'
        ),
    url(
        r'^email/send_activation/(?P<identifier>\w+)/$',
        email_send_activation,
        name='emailmgr_email_send_activation'
        ),
    url(
        r'^email/activate/(?P<identifier>\w+)/$',
        email_activate,
        name='emailmgr_email_activate'
        ),
    url(
        r'^email/make_primary/(?P<identifier>\w+)/$',
        email_make_primary,
        name='emailmgr_email_make_primary'
        ),
    url(
        r'^email/delete/(?P<identifier>\w+)/$',
        email_delete,
        name='emailmgr_email_delete'
        ),
    url(
        r'^email/$',
        email_list,
        name='emailmgr_email_list'
        ),
)


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

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/control/auth/login/')
def index(request):
    return HttpResponseRedirect("/control/events/")

@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
    # Get redirect path
    if 'r' in request.GET:
        r = request.GET['r']
        if r[0] != "/":
            r = "/control/"
    else:
        r = "/control/"

    # Set session variable
    try:
        request.session['m_event_id'] = int(event_id)
    except:
        raise Http404

    # Redirect
    return HttpResponseRedirect(r)

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

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/control/auth/login/')
def index(request):
    return HttpResponseRedirect("/control/events/")

@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
    # Get redirect path
    if 'r' in request.GET:
        r = request.GET['r']
        if r[0] != "/":
            r = "/control/"
    else:
        r = "/control/"

    # Set session variable
    try:
        request.session['m_event_id'] = int(event_id)
    except:
        raise Http404

    # Redirect
    return HttpResponseRedirect(r)

Prompt:
admin_base: Fix default refirect when url is /control/

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

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/control/auth/login/')
def index(request):
    return HttpResponseRedirect("/control/files/")

@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
    # Get redirect path
    if 'r' in request.GET:
        r = request.GET['r']
        if r[0] != "/":
            r = "/control/"
    else:
        r = "/control/"

    # Set session variable
    try:
        request.session['m_event_id'] = int(event_id)
    except:
        raise Http404

    # Redirect
    return HttpResponseRedirect(r)


# -*- coding: utf-8 -*-
"""
    website.snat.forms
    ~~~~~~~~~~~~~~~~~~

    vpn forms:
        /sant

    :copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""

from flask_wtf import Form
from wtforms import TextField, ValidationError
from wtforms.validators import Required, IPAddress

def IPorNet(message=u"无效的IP 或网段！"):
    def _ipornet(form, field):
        value = field.data
        ip = value.split('/')[0]
        if '/' in value:
            try:
                mask = int(value.split('/')[1])
            except:
                raise ValidationError(message)
            if mask < 0 or mask > 32:
                    raise ValidationError(message)
        parts = ip.split('.')
        if len(parts) == 4 and all(x.isdigit() for x in parts):
            numbers = list(int(x) for x in parts)
            if not all(num >= 0 and num < 256 for num in numbers):
                raise ValidationError(message)
            return True
        raise ValidationError(message)
    return _ipornet

class SnatForm(Form):
    source = TextField(u'SNAT源IP（段）',
                       validators=[Required(message=u'这是一个必选项！'),
                                   IPorNet(message=u"无效的IP 或网段！")])
    gateway = TextField(u'SNAT转发IP',
                        validators=[Required(message=u'这是一个必选项！'),
                                    IPAddress(message=u'无效的IP 地址！')])

Add snat ip or net validator.

Add snat ip or net validator.

Response:
# -*- coding: utf-8 -*-
"""
    website.snat.forms
    ~~~~~~~~~~~~~~~~~~

    vpn forms:
        /sant

    :copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""

from flask_wtf import Form
from wtforms import TextField, ValidationError
from wtforms.validators import Required, IPAddress

def IPorNet(message=u"无效的IP 或网段！"):
    def _ipornet(form, field):
        value = field.data
        ip = value.split('/')[0]
        if '/' in value:
            try:
                mask = int(value.split('/')[1])
            except:
                raise ValidationError(message)
            if mask < 0 or mask > 32:
                    raise ValidationError(message)
        parts = ip.split('.')
        if len(parts) == 4 and all(x.isdigit() for x in parts):
            numbers = list(int(x) for x in parts)
            if not all(num >= 0 and num < 256 for num in numbers):
                raise ValidationError(message)
            return True
        raise ValidationError(message)
    return _ipornet

class SnatForm(Form):
    source = TextField(u'SNAT源IP（段）',
                       validators=[Required(message=u'这是一个必选项！'),
                                   IPorNet(message=u"无效的IP 或网段！")])
    gateway = TextField(u'SNAT转发IP',
                        validators=[Required(message=u'这是一个必选项！'),
                                    IPAddress(message=u'无效的IP 地址！')])

Prompt:
Add snat ip or net validator.

# -*- coding: utf-8 -*-
"""
    website.snat.forms
    ~~~~~~~~~~~~~~~~~~

    vpn forms:
        /sant

    :copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""

from flask_wtf import Form
from wtforms import TextField
from wtforms.validators import Required, IPAddress

class SnatForm(Form):
    source = TextField(u'SNAT源IP（段）',
                       validators=[Required(message=u'这是一个必选项！')])
    gateway = TextField(u'SNAT转发IP',
                        validators=[Required(message=u'这是一个必选项！'),
                                    IPAddress(message=u'无效的ip 地址！')])


import sys
import os
import uuid
from time import sleep

if len(sys.argv) != 3:
    print "Wrong number of args"
    exit(1)

workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])

for this_run in range(num_runs):

    run_uuid = str(uuid.uuid4())

    launch_command = "airflow trigger_dag -r " + run_uuid + " " + workflow_name
    print("Launching workflow with command: " + launch_command)
    os.system(launch_command)
    print("Workflow %s launched.", run_uuid)
    sleep(1)

Response:
import sys
import os
import uuid
from time import sleep

if len(sys.argv) != 3:
    print "Wrong number of args"
    exit(1)

workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])

for this_run in range(num_runs):

    run_uuid = str(uuid.uuid4())

    launch_command = "airflow trigger_dag -r " + run_uuid + " " + workflow_name
    print("Launching workflow with command: " + launch_command)
    os.system(launch_command)
    print("Workflow %s launched.", run_uuid)
    sleep(1)

Prompt:
Use longer sleep time for workflow launcher.

import sys
import os
import uuid
from time import sleep

if len(sys.argv) != 3:
    print "Wrong number of args"
    exit(1)

workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])

for this_run in range(num_runs):

    run_uuid = str(uuid.uuid4())

    launch_command = "airflow trigger_dag -r " + run_uuid + " " + workflow_name
    print("Launching workflow with command: " + launch_command)
    os.system(launch_command)
    print("Workflow %s launched.", run_uuid)
    sleep(0.5)


import flask
from donut.modules.groups import helpers as groups

def has_permission(user_id, permission_id):
    '''
    Returns True if [user_id] holds a position that directly
    or indirectly (through a position relation) grants
    them [permission_id]. Otherwise returns False.
    '''
    if not (isinstance(user_id, int) and isinstance(permission_id, int)):
        return False
    # get all position id's with this permission
    query = '''SELECT pos_id FROM position_permissions WHERE permission_id = %s'''
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, permission_id)
        result = cursor.fetchall()
    pos_ids = [row['pos_id'] for row in result]
    for pos_id in pos_ids:
        holders = groups.get_position_holders(pos_id)
        holders = [row['user_id'] for row in holders]
        if user_id in holders:
            return True
    return False

Fix failing test and make lint

Fix failing test and make lint

Response:
import flask
from donut.modules.groups import helpers as groups

def has_permission(user_id, permission_id):
    '''
    Returns True if [user_id] holds a position that directly
    or indirectly (through a position relation) grants
    them [permission_id]. Otherwise returns False.
    '''
    if not (isinstance(user_id, int) and isinstance(permission_id, int)):
        return False
    # get all position id's with this permission
    query = '''SELECT pos_id FROM position_permissions WHERE permission_id = %s'''
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, permission_id)
        result = cursor.fetchall()
    pos_ids = [row['pos_id'] for row in result]
    for pos_id in pos_ids:
        holders = groups.get_position_holders(pos_id)
        holders = [row['user_id'] for row in holders]
        if user_id in holders:
            return True
    return False

Prompt:
Fix failing test and make lint

import flask
from donut.modules.groups import helpers as groups

def has_permission(user_id, permission_id):
    '''
    Returns True if [user_id] holds a position that directly
    or indirectly (through a position relation) grants
    them [permission_id]. Otherwise returns False.
    '''
    if not (isinstance(user_id, int) and isinstance(permission_id, int)):
        return False
    # get all position id's with this permission
    query = '''SELECT pos_id FROM position_permissions WHERE permission_id = %s'''
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, permission_id)
        result = cursor.fetchall()
    pos_ids = [row['pos_id'] for row in result]
    for pos_id in pos_ids:
        holders = groups.get_position_holders(pos_id)
        if {'user_id': user_id} in holders:
            return True
    return False


from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers

class SubcategoryListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subcategory
        fields = ('pk', 'name')

class CategorySerializer(serializers.ModelSerializer):
    subcategories = SubcategoryListSerializer(many=True, source='subcategory_set')

    class Meta:
        model = Category
        fields = ('pk', 'name', 'weight', 'is_active', 'comment_required', 'subcategories')

class KeywordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword

class SubcategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Subcategory
        fields = ('pk', 'name', 'is_active')

Response:
from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers

class SubcategoryListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subcategory
        fields = ('pk', 'name')

class CategorySerializer(serializers.ModelSerializer):
    subcategories = SubcategoryListSerializer(many=True, source='subcategory_set')

    class Meta:
        model = Category
        fields = ('pk', 'name', 'weight', 'is_active', 'comment_required', 'subcategories')

class KeywordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword

class SubcategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Subcategory
        fields = ('pk', 'name', 'is_active')

Prompt:
Remove category serializer from subcategory serializer

from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers

class SubcategoryListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subcategory
        fields = ('pk', 'name')

class CategorySerializer(serializers.ModelSerializer):
    subcategories = SubcategoryListSerializer(many=True, source='subcategory_set')

    class Meta:
        model = Category
        fields = ('pk', 'name', 'weight', 'is_active', 'comment_required', 'subcategories')

class KeywordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword

class SubcategorySerializer(serializers.ModelSerializer):
    category = CategorySerializer(read_only=True, many=True)

    class Meta:
        model = Subcategory


# flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.

# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# may override settings already defined.

import os
from .base import *

if os.environ.get('ENVIRONMENTCONFIG'):
    from whats_fresh.environment_config import *
else:
    from .yaml_config import *

Response:
# flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.

# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# may override settings already defined.

import os
from .base import *

if os.environ.get('ENVIRONMENTCONFIG'):
    from whats_fresh.environment_config import *
else:
    from .yaml_config import *

Prompt:
Use dict.get not dict[] to fail gracefully

# flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.

# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# may override settings already defined.

import os
from .base import *

if os.environ['ENVIRONMENTCONFIG']:
    from whats_fresh.environment_config import *
else:
    from .yaml_config import *


#!/usr/bin/env python

from distutils.core import setup

from avena import avena

_classifiers = [
    'Development Status :: 4 - Beta',
    'Environment :: Console',
    'Intended Audience :: End Users/Desktop',
    'License :: OSI Approved :: ISC License (ISCL)',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Topic :: Multimedia :: Graphics',
]

with open('README.rst', 'r') as rst_file:
    _long_description = rst_file.read()

_setup_args = {
    'author':           avena.__author__,
    'author_email':     avena.__email__,
    'classifiers':      _classifiers,
    'description':      avena.__doc__,
    'license':          avena.__license__,
    'long_description': _long_description,
    'name':             'Avena',
    'url':              'https://bitbucket.org/eliteraspberries/avena',
    'version':          avena.__version__,
}

if __name__ == '__main__':

    setup(packages=['avena'], scripts=['scripts/avena'],
          **_setup_args)

Install the script with the library.

Install the script with the library.

Response:
#!/usr/bin/env python

from distutils.core import setup

from avena import avena

_classifiers = [
    'Development Status :: 4 - Beta',
    'Environment :: Console',
    'Intended Audience :: End Users/Desktop',
    'License :: OSI Approved :: ISC License (ISCL)',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Topic :: Multimedia :: Graphics',
]

with open('README.rst', 'r') as rst_file:
    _long_description = rst_file.read()

_setup_args = {
    'author':           avena.__author__,
    'author_email':     avena.__email__,
    'classifiers':      _classifiers,
    'description':      avena.__doc__,
    'license':          avena.__license__,
    'long_description': _long_description,
    'name':             'Avena',
    'url':              'https://bitbucket.org/eliteraspberries/avena',
    'version':          avena.__version__,
}

if __name__ == '__main__':

    setup(packages=['avena'], scripts=['scripts/avena'],
          **_setup_args)

Prompt:
Install the script with the library.

#!/usr/bin/env python

from distutils.core import setup

from avena import avena

_classifiers = [
    'Development Status :: 4 - Beta',
    'Environment :: Console',
    'Intended Audience :: End Users/Desktop',
    'License :: OSI Approved :: ISC License (ISCL)',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Topic :: Multimedia :: Graphics',
]

with open('README.rst', 'r') as rst_file:
    _long_description = rst_file.read()

_setup_args = {
    'author':           avena.__author__,
    'author_email':     avena.__email__,
    'classifiers':      _classifiers,
    'description':      avena.__doc__,
    'license':          avena.__license__,
    'long_description': _long_description,
    'name':             'Avena',
    'url':              'https://bitbucket.org/eliteraspberries/avena',
    'version':          avena.__version__,
}

if __name__ == '__main__':

    setup(packages=['avena'],
          **_setup_args)


import json
import os

import requests

class APIWrapper(object):

    def __init__(self, base_url=None, auth_token=None):

        if base_url:
            self.base_url = base_url
        else:
            self.base_url = "http://api.football-data.org/v1"

        if auth_token:
            self.headers = {
                'X-Auth-Token': auth_token
            }
        else:
            self.headers = {}

    def do_request(self, url, filters=None):
        params = filters if filters else {}
        r = requests.get(url=url, params=params, headers=self.headers)
        if r.status_code == requests.codes.ok:
            return r.json()
        return None

    def all_competitions(self):
        url = "%s/competitions" % self.base_url
        response = self.do_request(url=url)
        return response

def main():
    api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"])
    res = api.do_request("http://api.football-data.org/v1/competitions")
    print(res)

if __name__ == "__main__":
    main()

Add the start of an api wrapper

Add the start of an api wrapper

Response:
import json
import os

import requests

class APIWrapper(object):

    def __init__(self, base_url=None, auth_token=None):

        if base_url:
            self.base_url = base_url
        else:
            self.base_url = "http://api.football-data.org/v1"

        if auth_token:
            self.headers = {
                'X-Auth-Token': auth_token
            }
        else:
            self.headers = {}

    def do_request(self, url, filters=None):
        params = filters if filters else {}
        r = requests.get(url=url, params=params, headers=self.headers)
        if r.status_code == requests.codes.ok:
            return r.json()
        return None

    def all_competitions(self):
        url = "%s/competitions" % self.base_url
        response = self.do_request(url=url)
        return response

def main():
    api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"])
    res = api.do_request("http://api.football-data.org/v1/competitions")
    print(res)

if __name__ == "__main__":
    main()

Prompt: Add the start of an api wrapper


Response:
#
# ========================================================
# Copyright (c) 2012 Whamcloud, Inc.  All rights reserved.
# ========================================================

Prompt:
Remove some cruft that was accidentally pushed

Change-Id: If75577316398c9d02230882766463f00aa13efd9

#
# ========================================================
# Copyright (c) 2012 Whamcloud, Inc.  All rights reserved.
# ========================================================

from chroma_cli.commands.dispatcher import CommandDispatcher
CommandDispatcher  # stupid pyflakes


def flatten(lst):
    """Completely flatten an arbitrarily-deep list"""
    return [*_flatten(lst)]

def _flatten(lst):
    """Generator for flattening arbitrarily-deep lists"""
    for item in lst:
        if isinstance(item, (list, tuple)):
            yield from _flatten(item)
        elif item is not None:
            yield item

Tidy and simplify generator code

Tidy and simplify generator code

Response:
def flatten(lst):
    """Completely flatten an arbitrarily-deep list"""
    return [*_flatten(lst)]

def _flatten(lst):
    """Generator for flattening arbitrarily-deep lists"""
    for item in lst:
        if isinstance(item, (list, tuple)):
            yield from _flatten(item)
        elif item is not None:
            yield item

Prompt:
Tidy and simplify generator code

def flatten(lst):
    """Completely flatten an arbitrarily-deep list"""
    return [*_flatten(lst)]

def _flatten(lst):
    """Generator for flattening arbitrarily-deep lists"""
    if isinstance(lst, (list, tuple)):
        for item in lst:
            if item is None:
                continue
            else:
                yield from _flatten(item)
    else:
        yield lst


from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
from xmonad import MonadTall

Add MonadTall to layout module proper.

Response:
from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
from xmonad import MonadTall

Prompt:
Add MonadTall to layout module proper.

Fixes #126

from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice


import unittest
from spotpy import objectivefunctions as of
import numpy as np

#https://docs.python.org/3/library/unittest.html

class TestObjectiveFunctions(unittest.TestCase):

    # How many digits to match in case of floating point answers
    tolerance = 10

    def setUp(self):
        np.random.seed(42)
        self.simulation = np.random.randn(10)
        self.evaluation = np.random.randn(10)

        print(self.simulation)
        print(self.evaluation)

    def test_bias(self):
        res = of.bias(self.evaluation, self.simulation)
        self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)

    def test_length_mismatch_return_nan(self):
        all_funcs = of._all_functions

        for func in all_funcs:
            res = func([0], [0, 1])
            self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))

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

Add tests for bias and length mismatch

Add tests for bias and length mismatch

Response:
import unittest
from spotpy import objectivefunctions as of
import numpy as np

#https://docs.python.org/3/library/unittest.html

class TestObjectiveFunctions(unittest.TestCase):

    # How many digits to match in case of floating point answers
    tolerance = 10

    def setUp(self):
        np.random.seed(42)
        self.simulation = np.random.randn(10)
        self.evaluation = np.random.randn(10)

        print(self.simulation)
        print(self.evaluation)

    def test_bias(self):
        res = of.bias(self.evaluation, self.simulation)
        self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)

    def test_length_mismatch_return_nan(self):
        all_funcs = of._all_functions

        for func in all_funcs:
            res = func([0], [0, 1])
            self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))

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

Prompt: Add tests for bias and length mismatch


from itertools import chain
from typing import Container, Iterable, Sized

class RangeSet(Sized, Iterable, Container):
    def __init__(self, *ranges):
        self.ranges = []

        for r in ranges:
            if isinstance(r, range):
                self.ranges.append(r)
                continue

            try:
                element = list(r.ranges)
            except AttributeError:
                element = None

            try:
                element = element or [range(*r)]
            except:
                msg = "RangeSet argument must be a range, RangeSet or an Iterable, not {}"
                raise ValueError(msg.format(type(r)))

            self.ranges.extend(element)

    def __iter__(self):
        return chain.from_iterable(r for r in self.ranges)

    def __contains__(self, elem):
        return any(elem in r for r in self.ranges)

    def __len__(self):
        return sum(len(r) for r in self.ranges)

Response:
from itertools import chain
from typing import Container, Iterable, Sized

class RangeSet(Sized, Iterable, Container):
    def __init__(self, *ranges):
        self.ranges = []

        for r in ranges:
            if isinstance(r, range):
                self.ranges.append(r)
                continue

            try:
                element = list(r.ranges)
            except AttributeError:
                element = None

            try:
                element = element or [range(*r)]
            except:
                msg = "RangeSet argument must be a range, RangeSet or an Iterable, not {}"
                raise ValueError(msg.format(type(r)))

            self.ranges.extend(element)

    def __iter__(self):
        return chain.from_iterable(r for r in self.ranges)

    def __contains__(self, elem):
        return any(elem in r for r in self.ranges)

    def __len__(self):
        return sum(len(r) for r in self.ranges)

Prompt:
Use duck typing when creating a RangeSet

from itertools import chain
from typing import Sized, Iterable, Container, Set

class RangeSet(Sized, Iterable, Container):
    def __init__(self, *ranges):
        self.ranges = []

        for r in ranges:
            if isinstance(r, range):
                r = [r]
            elif isinstance(r, RangeSet):
                r = list(r.ranges)
            elif isinstance(r, Iterable) and not isinstance(r, Set):
                r = [range(*r)]
            else:
                msg = "RangeSet argument must be a range, RangeSet or an Iterable, not {}"
                raise ValueError(msg.format(type(r)))

            self.ranges.extend(r)

    def __iter__(self):
        return chain.from_iterable(r for r in self.ranges)

    def __contains__(self, elem):
        return any(elem in r for r in self.ranges)

    def __len__(self):
        return sum(len(r) for r in self.ranges)


#!/usr/bin/pyton

#    Copyright 2011 Lockheed Martin

'''
Created on Mar 17, 2011

Base model class for learning registry data model

@author: jpoyau
'''

from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging

log = logging.getLogger(__name__)

SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']

class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):

    PUBLISH='publish'
    ACCESS = 'access'
    BROKER = 'broker'
    DISTRIBUTE = 'distribute'
    ADMINISTRATIVE='administrative'

    def __init__(self, data=None):
        super(NodeServiceModel,self).__init__(data)

Add 'distribute' to the node services

Add 'distribute' to the node services

Response:
#!/usr/bin/pyton

#    Copyright 2011 Lockheed Martin

'''
Created on Mar 17, 2011

Base model class for learning registry data model

@author: jpoyau
'''

from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging

log = logging.getLogger(__name__)

SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']

class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):

    PUBLISH='publish'
    ACCESS = 'access'
    BROKER = 'broker'
    DISTRIBUTE = 'distribute'
    ADMINISTRATIVE='administrative'

    def __init__(self, data=None):
        super(NodeServiceModel,self).__init__(data)

Prompt:
Add 'distribute' to the node services

#!/usr/bin/pyton

#    Copyright 2011 Lockheed Martin

'''
Created on Mar 17, 2011

Base model class for learning registry data model

@author: jpoyau
'''

from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging

log = logging.getLogger(__name__)

SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']

class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):

    PUBLISH='publish'
    ACCESS = 'access'
    BROKER = 'broker'
    ADMINISTRATIVE='administrative'

    def __init__(self, data=None):
        super(NodeServiceModel,self).__init__(data)


import os

DATADIR = os.path.abspath('docs/data')
FILES = ['test_uk.shp', 'test_uk.shx', 'test_uk.dbf', 'test_uk.prj']

def create_zipfile(zipfilename):
    import zipfile
    with zipfile.ZipFile(zipfilename, 'w') as zip:
        for filename in FILES:
            zip.write(os.path.join(DATADIR, filename), filename)

def create_tarfile(tarfilename):
    import tarfile
    with tarfile.open(tarfilename, 'w') as tar:
        for filename in FILES:
            tar.add(os.path.join(DATADIR, filename), arcname='testing/%s' % filename)

def create_jsonfile(jsonfilename):
    import json
    import fiona
    from fiona.crs import from_string
    from fiona.tool import crs_uri
    with fiona.collection(os.path.join(DATADIR, FILES[0]), 'r') as source:
        features = [feat for feat in source]
        crs = ' '.join('+%s=%s' % (k,v) for k,v in source.crs.items())
    my_layer = {'type': 'FeatureCollection',
                'features': features,
                'crs': { 'type': 'name',
                         'properties': {
                         'name':crs_uri(from_string(crs))}}}
    with open(jsonfilename, 'w') as f:
        f.write(json.dumps(my_layer))

def setup():
    """Setup function for nosetests to create test files if they do not exist
    """
    zipfile = os.path.join(DATADIR, 'test_uk.zip')
    tarfile = os.path.join(DATADIR, 'test_uk.tar')
    jsonfile = os.path.join(DATADIR, 'test_uk.json')
    if not os.path.exists(zipfile):
        create_zipfile(zipfile)
    if not os.path.exists(tarfile):
        create_tarfile(tarfile)
    if not os.path.exists(jsonfile):
        create_jsonfile(jsonfile)

Response:
import os

DATADIR = os.path.abspath('docs/data')
FILES = ['test_uk.shp', 'test_uk.shx', 'test_uk.dbf', 'test_uk.prj']

def create_zipfile(zipfilename):
    import zipfile
    with zipfile.ZipFile(zipfilename, 'w') as zip:
        for filename in FILES:
            zip.write(os.path.join(DATADIR, filename), filename)

def create_tarfile(tarfilename):
    import tarfile
    with tarfile.open(tarfilename, 'w') as tar:
        for filename in FILES:
            tar.add(os.path.join(DATADIR, filename), arcname='testing/%s' % filename)

def create_jsonfile(jsonfilename):
    import json
    import fiona
    from fiona.crs import from_string
    from fiona.tool import crs_uri
    with fiona.collection(os.path.join(DATADIR, FILES[0]), 'r') as source:
        features = [feat for feat in source]
        crs = ' '.join('+%s=%s' % (k,v) for k,v in source.crs.items())
    my_layer = {'type': 'FeatureCollection',
                'features': features,
                'crs': { 'type': 'name',
                         'properties': {
                         'name':crs_uri(from_string(crs))}}}
    with open(jsonfilename, 'w') as f:
        f.write(json.dumps(my_layer))

def setup():
    """Setup function for nosetests to create test files if they do not exist
    """
    zipfile = os.path.join(DATADIR, 'test_uk.zip')
    tarfile = os.path.join(DATADIR, 'test_uk.tar')
    jsonfile = os.path.join(DATADIR, 'test_uk.json')
    if not os.path.exists(zipfile):
        create_zipfile(zipfile)
    if not os.path.exists(tarfile):
        create_tarfile(tarfile)
    if not os.path.exists(jsonfile):
        create_jsonfile(jsonfile)

Prompt:
Create derived test data files if they do not exist when running nosetests

#


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

version = '3.1.0a1'

Prepare next development cycle 3.1.0a1

Prepare next development cycle 3.1.0a1

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

version = '3.1.0a1'

Prompt:
Prepare next development cycle 3.1.0a1

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


'''
Return data to the host operating system's syslog facility

Required python modules: syslog, json

The syslog returner simply reuses the operating system's syslog
facility to log return data
'''

# Import python libs
import syslog
import json
try:
    import syslog
    HAS_SYSLOG = True
except ImportError:
    HAS_SYSLOG = False

def __virtual__():
    if not HAS_SYSLOG:
        return False
    return 'syslog'

def returner(ret):
    '''
    Return data to the local syslog
    '''
    syslog.syslog(syslog.LOG_INFO, 'salt-minion: {0}'.format(json.dumps(ret)))

Response:
'''
Return data to the host operating system's syslog facility

Required python modules: syslog, json

The syslog returner simply reuses the operating system's syslog
facility to log return data
'''

# Import python libs
import syslog
import json
try:
    import syslog
    HAS_SYSLOG = True
except ImportError:
    HAS_SYSLOG = False

def __virtual__():
    if not HAS_SYSLOG:
        return False
    return 'syslog'

def returner(ret):
    '''
    Return data to the local syslog
    '''
    syslog.syslog(syslog.LOG_INFO, 'salt-minion: {0}'.format(json.dumps(ret)))

Prompt:
Check for syslog. Doesn't exist on Windows

'''
Return data to the host operating system's syslog facility

Required python modules: syslog, json

The syslog returner simply reuses the operating system's syslog
facility to log return data
'''

# Import python libs
import syslog
import json

def __virtual__():
    return 'syslog'

def returner(ret):
    '''
    Return data to the local syslog
    '''
    syslog.syslog(syslog.LOG_INFO, 'salt-minion: {0}'.format(json.dumps(ret)))


import pytest   # noqa
import os
import sys
import glob
import importlib

def test_examples():

    examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                '../../examples/*/*.py')

    # Filter out __init__.py
    examples = [f for f in glob.glob(examples_pat)
                if not any([x in f for x in ['__init__.py',
                                             'molecular',
                                             'custom_table_caching']])]
    for e in examples:
        example_dir = os.path.dirname(e)
        sys.path.insert(0, example_dir)
        (module_name, _) = os.path.splitext(os.path.basename(e))
        m = importlib.import_module(module_name)

        if hasattr(m, 'main'):
            m.main(debug=False)

Replace deprecated imp with importlib

Replace deprecated imp with importlib

Response:
import pytest   # noqa
import os
import sys
import glob
import importlib

def test_examples():

    examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                '../../examples/*/*.py')

    # Filter out __init__.py
    examples = [f for f in glob.glob(examples_pat)
                if not any([x in f for x in ['__init__.py',
                                             'molecular',
                                             'custom_table_caching']])]
    for e in examples:
        example_dir = os.path.dirname(e)
        sys.path.insert(0, example_dir)
        (module_name, _) = os.path.splitext(os.path.basename(e))
        m = importlib.import_module(module_name)

        if hasattr(m, 'main'):
            m.main(debug=False)

Prompt:
Replace deprecated imp with importlib

import pytest   # noqa
import os
import sys
import glob
import imp

def test_examples():

    examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                '../../examples/*/*.py')

    # Filter out __init__.py
    examples = [f for f in glob.glob(examples_pat)
                if not any([x in f for x in ['__init__.py',
                                             'molecular',
                                             'custom_table_caching']])]
    for e in examples:
        example_dir = os.path.dirname(e)
        sys.path.insert(0, example_dir)
        (module_name, _) = os.path.splitext(os.path.basename(e))
        (module_file, module_path, desc) = \
            imp.find_module(module_name, [example_dir])

        m = imp.load_module(module_name, module_file, module_path, desc)

        if hasattr(m, 'main'):
            m.main(debug=False)


import numpy as np
from typhon.spareice import Array, GroupedArrays
import xarray as xr

class TestArray:
    """Testing the array methods."""
    pass

class TestGroupedArrays:
    """Testing the GroupedArrays methods."""

    def test_dict(self):
        # TODO: Implement test for export to / import from python dictionary
        # TODO: objects
        pass

    def test_equal(self):
        a = GroupedArrays()
        a["group1/group2/data"] = np.arange(1, 100).astype(float)
        a["group1/data"] = np.arange(1, 10).astype(float)
        a["data"] = np.arange(-30, 10).astype(float)

        # Check whether it does find equality:
        assert a == a

        # Check whether it does find inequality because the variables have
        # different lengths:
        assert a != a[:5]

        # Check whether it does find inequality because a variable's content is
        # different but has the same length:
        b = a.copy()
        b["data"] = np.arange(-20, 20).astype(float)
        assert a != b

        # Check whether it does find inequality (if one variable does not exist
        # in the other group):
        del b["data"]
        assert a != b

    def test_xarray(self):
        # TODO: Implement test for export to / import from xarray.Dataset
        pass

Implement test class for Array and GroupedArrays

Response:
import numpy as np
from typhon.spareice import Array, GroupedArrays
import xarray as xr

class TestArray:
    """Testing the array methods."""
    pass

class TestGroupedArrays:
    """Testing the GroupedArrays methods."""

    def test_dict(self):
        # TODO: Implement test for export to / import from python dictionary
        # TODO: objects
        pass

    def test_equal(self):
        a = GroupedArrays()
        a["group1/group2/data"] = np.arange(1, 100).astype(float)
        a["group1/data"] = np.arange(1, 10).astype(float)
        a["data"] = np.arange(-30, 10).astype(float)

        # Check whether it does find equality:
        assert a == a

        # Check whether it does find inequality because the variables have
        # different lengths:
        assert a != a[:5]

        # Check whether it does find inequality because a variable's content is
        # different but has the same length:
        b = a.copy()
        b["data"] = np.arange(-20, 20).astype(float)
        assert a != b

        # Check whether it does find inequality (if one variable does not exist
        # in the other group):
        del b["data"]
        assert a != b

    def test_xarray(self):
        # TODO: Implement test for export to / import from xarray.Dataset
        pass

Prompt: Implement test class for Array and GroupedArrays


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

from sethji.model.sync import SyncAws
from sethji.views.account import requires_login
from flask import Blueprint, redirect, url_for, flash

mod = Blueprint('sync', __name__, url_prefix='/sync')

@mod.route("/", methods=["POST"])
@requires_login
def sync():
    sync_aws = SyncAws()
    sync_aws.background_sync()
    flash(u'AWS Sync Initiated')
    return redirect(url_for('home'))

def is_sync_in_progress():
    sync_aws = SyncAws()
    return sync_aws.is_sync_in_progress()

Revert "Redirect to same page"

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

from sethji.model.sync import SyncAws
from sethji.views.account import requires_login
from flask import Blueprint, redirect, url_for, flash

mod = Blueprint('sync', __name__, url_prefix='/sync')

@mod.route("/", methods=["POST"])
@requires_login
def sync():
    sync_aws = SyncAws()
    sync_aws.background_sync()
    flash(u'AWS Sync Initiated')
    return redirect(url_for('home'))

def is_sync_in_progress():
    sync_aws = SyncAws()
    return sync_aws.is_sync_in_progress()

Prompt:
Revert "Redirect to same page"

This reverts commit 1f49ee31c21e1bebefb3be9ecc9e4df7c115a5ef.

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

from sethji.model.sync import SyncAws
from sethji.views.account import requires_login
from flask import Blueprint, redirect, url_for, flash, request

mod = Blueprint('sync', __name__, url_prefix='/sync')

@mod.route("/", methods=["POST"])
@requires_login
def sync():
    sync_aws = SyncAws()
    sync_aws.background_sync()
    flash(u'AWS Sync Initiated')
    return redirect(request.path)

def is_sync_in_progress():
    sync_aws = SyncAws()
    return sync_aws.is_sync_in_progress()


#!/usr/bin/python

import optparse
import sys
import unittest2

USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.

SDK_PATH    Path to the SDK installation
TEST_PATH   Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""

def main(sdk_path, test_path, third_party_path=None):
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()
  if third_party_path:
    sys.path.insert(0, third_party_path)
  suite = unittest2.loader.TestLoader().discover(test_path,
                                                 pattern='*_test.py')
  result = unittest2.TextTestRunner(verbosity=2).run(suite)
  if len(result.errors) > 0 or len(result.failures) > 0:
    sys.exit(1)

if __name__ == '__main__':
  sys.dont_write_bytecode = True
  parser = optparse.OptionParser(USAGE)
  options, args = parser.parse_args()
  if len(args) < 2:
    print 'Error: At least 2 arguments required.'
    parser.print_help()
    sys.exit(1)
  SDK_PATH = args[0]
  TEST_PATH = args[1]
  THIRD_PARTY_PATH = args[2] if len(args) > 2 else None
  main(SDK_PATH, TEST_PATH, THIRD_PARTY_PATH)

Response:
#!/usr/bin/python

import optparse
import sys
import unittest2

USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.

SDK_PATH    Path to the SDK installation
TEST_PATH   Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""

def main(sdk_path, test_path, third_party_path=None):
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()
  if third_party_path:
    sys.path.insert(0, third_party_path)
  suite = unittest2.loader.TestLoader().discover(test_path,
                                                 pattern='*_test.py')
  result = unittest2.TextTestRunner(verbosity=2).run(suite)
  if len(result.errors) > 0 or len(result.failures) > 0:
    sys.exit(1)

if __name__ == '__main__':
  sys.dont_write_bytecode = True
  parser = optparse.OptionParser(USAGE)
  options, args = parser.parse_args()
  if len(args) < 2:
    print 'Error: At least 2 arguments required.'
    parser.print_help()
    sys.exit(1)
  SDK_PATH = args[0]
  TEST_PATH = args[1]
  THIRD_PARTY_PATH = args[2] if len(args) > 2 else None
  main(SDK_PATH, TEST_PATH, THIRD_PARTY_PATH)

Prompt:
Make sure the tests exit with status 1 when there are errors or failures
#!/usr/bin/python

import optparse
import sys
import unittest2

USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.

SDK_PATH    Path to the SDK installation
TEST_PATH   Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""

def main(sdk_path, test_path, third_party_path=None):
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()
  if third_party_path:
    sys.path.insert(0, third_party_path)
  suite = unittest2.loader.TestLoader().discover(test_path,
                                                 pattern='*_test.py')
  unittest2.TextTestRunner(verbosity=2).run(suite)

if __name__ == '__main__':
  sys.dont_write_bytecode = True
  parser = optparse.OptionParser(USAGE)
  options, args = parser.parse_args()
  if len(args) < 2:
    print 'Error: At least 2 arguments required.'
    parser.print_help()
    sys.exit(1)
  SDK_PATH = args[0]
  TEST_PATH = args[1]
  THIRD_PARTY_PATH = args[2] if len(args) > 2 else None
  main(SDK_PATH, TEST_PATH, THIRD_PARTY_PATH)


from unittest import TestCase
from requests.exceptions import ConnectionError
from mock import NonCallableMock, patch

from modules.web_caller import get_google, GOOGLE_URL

MOCK_GOOGLE_URL = 'http://not-going-to-work!!!'

class TestWebCaller(TestCase):
    """
    Tests for the `web_caller` module.
    """

    @patch('modules.web_caller.requests.get')
    def test_get_google(self, get):
        """
        Calling `get_google` works as expected.
        """

        # Create a mock response
        mock_response = NonCallableMock(
            status_code=200,
        )
        # Assign the mock response as the requests.get return value
        get.return_value = mock_response

        # Call the function
        response = get_google()

        # Check that requests.get was called with the expected URL
        get.assert_called_once_with(GOOGLE_URL)

        # Check that the mock response is returned
        self.assertIs(mock_response, response)

        # Check that the mocked response.status_code is as expected
        self.assertEqual(200, response.status_code)

    @patch('modules.web_caller.GOOGLE_URL', MOCK_GOOGLE_URL)
    def test_get_google_with_exception(self):
        """
        Call the `get_google` function while using `patch` to create an
        unreachable URL.

        Assert that the error happened and capture it using assertRaises.
        """

        # Call the function via assertRaises and confirm the exception is
        # raised by making the call
        self.assertRaises(ConnectionError, get_google)

    @patch('modules.web_caller.GOOGLE_URL', MOCK_GOOGLE_URL)
    def test_get_google_with_exception_context_manager(self):
        """
        Call the `get_google` function while using `patch` to create an
        unreachable URL.

        Assert that the error happened and capture it using the assertRaises
        context manager.
        """

        # Establish an assertRaises context manager
        with self.assertRaises(ConnectionError):
            # Call the function
            get_google()

Response:
from unittest import TestCase
from requests.exceptions import ConnectionError
from mock import NonCallableMock, patch

from modules.web_caller import get_google, GOOGLE_URL

MOCK_GOOGLE_URL = 'http://not-going-to-work!!!'

class TestWebCaller(TestCase):
    """
    Tests for the `web_caller` module.
    """

    @patch('modules.web_caller.requests.get')
    def test_get_google(self, get):
        """
        Calling `get_google` works as expected.
        """

        # Create a mock response
        mock_response = NonCallableMock(
            status_code=200,
        )
        # Assign the mock response as the requests.get return value
        get.return_value = mock_response

        # Call the function
        response = get_google()

        # Check that requests.get was called with the expected URL
        get.assert_called_once_with(GOOGLE_URL)

        # Check that the mock response is returned
        self.assertIs(mock_response, response)

        # Check that the mocked response.status_code is as expected
        self.assertEqual(200, response.status_code)

    @patch('modules.web_caller.GOOGLE_URL', MOCK_GOOGLE_URL)
    def test_get_google_with_exception(self):
        """
        Call the `get_google` function while using `patch` to create an
        unreachable URL.

        Assert that the error happened and capture it using assertRaises.
        """

        # Call the function via assertRaises and confirm the exception is
        # raised by making the call
        self.assertRaises(ConnectionError, get_google)

    @patch('modules.web_caller.GOOGLE_URL', MOCK_GOOGLE_URL)
    def test_get_google_with_exception_context_manager(self):
        """
        Call the `get_google` function while using `patch` to create an
        unreachable URL.

        Assert that the error happened and capture it using the assertRaises
        context manager.
        """

        # Establish an assertRaises context manager
        with self.assertRaises(ConnectionError):
            # Call the function
            get_google()

Prompt:
Add test examples to assert against exceptions

from unittest import TestCase
from mock import NonCallableMock, patch

from modules.web_caller import get_google, GOOGLE_URL

class TestWebCaller(TestCase):
    """
    Tests for the `web_caller` module.
    """

    @patch('modules.web_caller.requests.get')
    def test_get_google(self, get):
        """
        Calling `get_google` works as expected.
        """

        # Create a mock response
        mock_response = NonCallableMock(
            status_code=200,
        )
        # Assign the mock response as the requests.get return value
        get.return_value = mock_response

        # Call the function
        response = get_google()

        # Check that requests.get was called with the expected URL
        get.assert_called_once_with(GOOGLE_URL)

        # Check that the mock response is returned
        self.assertIs(mock_response, response)

        # Check that the mocked response.status_code is as expected
        self.assertEqual(200, response.status_code)


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

from django.db import models, migrations

def add_echonest_forward(apps, schema_editor):
    """Create echonest user."""
    User = apps.get_model("users", "User")
    User.objects.update_or_create(email='echonest')

def add_echonest_backward(apps, schema_editor):
    """Delete echonest user."""
    User = apps.get_model("users", "User")
    User.objects.filter(email='echonest').delete()

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(add_echonest_forward, add_echonest_backward)
    ]

Add migration to create echonest user

Add migration to create echonest user

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

from django.db import models, migrations

def add_echonest_forward(apps, schema_editor):
    """Create echonest user."""
    User = apps.get_model("users", "User")
    User.objects.update_or_create(email='echonest')

def add_echonest_backward(apps, schema_editor):
    """Delete echonest user."""
    User = apps.get_model("users", "User")
    User.objects.filter(email='echonest').delete()

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(add_echonest_forward, add_echonest_backward)
    ]

Prompt: Add migration to create echonest user


import json
import logging

from werkzeug.utils import import_string

logger = logging.getLogger(__name__)

def get_task(request):
    return json.dumps({})

def configure(self_settings):
    """
    Getting plugin's default settings, overwriting them with settings
    from local_settings.py, returns dict of settings
    """
    settings = {}
    try:
        local_settings = import_string('vulyk.local_settings')
        for attr in dir(self_settings):
            settings[attr] = getattr(self_settings, attr)
        for attr in dir(local_settings):
            if attr in dir(self_settings):
                settings[attr] = getattr(local_settings, attr)
    except Exception as e:
        logger.warning(e)

    return settings

Fix return format of plugin's settings

Fix return format of plugin's settings

Response:
import json
import logging

from werkzeug.utils import import_string

logger = logging.getLogger(__name__)

def get_task(request):
    return json.dumps({})

def configure(self_settings):
    """
    Getting plugin's default settings, overwriting them with settings
    from local_settings.py, returns dict of settings
    """
    settings = {}
    try:
        local_settings = import_string('vulyk.local_settings')
        for attr in dir(self_settings):
            settings[attr] = getattr(self_settings, attr)
        for attr in dir(local_settings):
            if attr in dir(self_settings):
                settings[attr] = getattr(local_settings, attr)
    except Exception as e:
        logger.warning(e)

    return settings

Prompt:
Fix return format of plugin's settings

import json
import logging

from werkzeug.utils import import_string

logger = logging.getLogger(__name__)

def get_task(request):
    return json.dumps({})

def configure(self_settings):
    """
    Getting plugin's default settings, overwriting them with settings
    from local_settings.py, returns list of settings
    """
    try:
        local_settings = import_string('vulyk.local_settings')
        for attr in dir(local_settings):
            if attr in dir(self_settings):
                self_settings[attr] = getattr(local_settings, attr)
    except Exception as e:
        logger.warning(e)

    return self_settings


import pandas as pd
import numpy as np
import operator,os

def extract( file_name ):
    with open(file_name) as f:
        for i,line in enumerate(f,1):
            if "SCN" in line:
                return i

def main(lta_file):
    os.system('ltahdr -i ' + lta_file + '>  lta_header')
    dictionary = {}
    skipped_rows = extract(lta_header)-1

    header = pd.read_csv(lta_header,skiprows=skipped_rows,delimiter=r"\s+")
    flux = list(set(header["OBJECT"]))

    header['Nrecs'] = header['Nrecs'].astype(float)

    for i in flux :
        temp = header.loc[header.OBJECT==i,'Nrecs'].values
        temp = np.mean(temp)
        dictionary[i]=temp

    source = max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
    return source

Add file to extract source name from LTA header

Response:
import pandas as pd
import numpy as np
import operator,os

def extract( file_name ):
    with open(file_name) as f:
        for i,line in enumerate(f,1):
            if "SCN" in line:
                return i

def main(lta_file):
    os.system('ltahdr -i ' + lta_file + '>  lta_header')
    dictionary = {}
    skipped_rows = extract(lta_header)-1

    header = pd.read_csv(lta_header,skiprows=skipped_rows,delimiter=r"\s+")
    flux = list(set(header["OBJECT"]))

    header['Nrecs'] = header['Nrecs'].astype(float)

    for i in flux :
        temp = header.loc[header.OBJECT==i,'Nrecs'].values
        temp = np.mean(temp)
        dictionary[i]=temp

    source = max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
    return source

Prompt: Add file to extract source name from LTA header


# -*- coding: utf-8 -*-
#
# © 2014 Ian Eure
# Author: Ian Eure
#

from setuptools import setup, find_packages
# Dumb bug https://groups.google.com/forum/#!msg/nose-users/fnJ-kAUbYHQ/ngz3qjdnrioJ
import multiprocessing

setup(name="yar",
      version="0.0.2",
      packages=find_packages(),
      tests_require=['nose'],
      install_requires=["pyserial==2.7"],
      test_suite="nose.collector",
      entry_points = {
          'console_scripts': [
              'yar = yar.cli:main'
          ]
      })

Work around a dumb nose bug

Work around a dumb nose bug

Response:
# -*- coding: utf-8 -*-
#
# © 2014 Ian Eure
# Author: Ian Eure
#

from setuptools import setup, find_packages
# Dumb bug https://groups.google.com/forum/#!msg/nose-users/fnJ-kAUbYHQ/ngz3qjdnrioJ
import multiprocessing

setup(name="yar",
      version="0.0.2",
      packages=find_packages(),
      tests_require=['nose'],
      install_requires=["pyserial==2.7"],
      test_suite="nose.collector",
      entry_points = {
          'console_scripts': [
              'yar = yar.cli:main'
          ]
      })

Prompt:
Work around a dumb nose bug

# -*- coding: utf-8 -*-
#
# © 2014 Ian Eure
# Author: Ian Eure
#

from setuptools import setup, find_packages

setup(name="yar",
      version="0.0.2",
      packages=find_packages(),
      tests_require=['nose'],
      install_requires=["pyserial==2.7"],
      test_suite="nose.collector",
      entry_points = {
          'console_scripts': [
              'yar = yar.cli:main'
          ]
      })


from django.test import TestCase

from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter

def test_filter(c):
  obj = c()
  obj.filter_queryset('a', 'b', 'c')
  obj.get_fields('a')

def PasswordRecoveryFiltersTestCase(TestCase):
  def test_filters():
    """Assert filters do not throw error when instantiated"""
    # Nothing to assert here, we just instantiate them and
    # make sure it throws no error
    test_filter(RecoveryTokenFilter)
    test_filter(RecoverPasswordFilter)

Fix PasswordRecovery test case name

Fix PasswordRecovery test case name

Response:
from django.test import TestCase

from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter

def test_filter(c):
  obj = c()
  obj.filter_queryset('a', 'b', 'c')
  obj.get_fields('a')

def PasswordRecoveryFiltersTestCase(TestCase):
  def test_filters():
    """Assert filters do not throw error when instantiated"""
    # Nothing to assert here, we just instantiate them and
    # make sure it throws no error
    test_filter(RecoveryTokenFilter)
    test_filter(RecoverPasswordFilter)

Prompt:
Fix PasswordRecovery test case name

from django.test import TestCase

from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter

def test_filter(c):
  obj = c()
  obj.filter_queryset('a', 'b', 'c')
  obj.get_fields('a')

def TestPasswordRecoveryFilters(TestCase):
  def test_filters():
    """Assert filters do not throw error when instantiated"""
    # Nothing to assert here, we just instantiate them and
    # make sure it throws no error
    test_filter(RecoveryTokenFilter)
    test_filter(RecoverPasswordFilter)


"""

Revision ID: 0364_drop_old_column
Revises: 0363_cancelled_by_api_key
Create Date: 2022-01-25 18:05:27.750234

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = '0364_drop_old_column'
down_revision = '0363_cancelled_by_api_key'

def upgrade():
    # move data over
    op.execute("UPDATE broadcast_message SET created_by_api_key_id=api_key_id WHERE created_by_api_key_id IS NULL")
    op.create_check_constraint(
        "ck_broadcast_message_created_by_not_null",
        "broadcast_message",
        "created_by_id is not null or created_by_api_key_id is not null"
    )
    op.drop_column('broadcast_message', 'api_key_id')

def downgrade():
    op.add_column('broadcast_message', sa.Column('api_key_id', postgresql.UUID(), autoincrement=False, nullable=True))
    op.execute("UPDATE broadcast_message SET api_key_id=created_by_api_key_id")  # move data over
    op.drop_constraint(
        "ck_broadcast_message_created_by_not_null",
        "broadcast_message"
    )

Drop api_key_id column from broadcast_message table

This column has been superseded by a new column named
created_by_api_key_id.

Also create constraint checking that we know who created broadcast

Also move data so that constraint is met before instatiating it.

Response:
"""

Revision ID: 0364_drop_old_column
Revises: 0363_cancelled_by_api_key
Create Date: 2022-01-25 18:05:27.750234

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = '0364_drop_old_column'
down_revision = '0363_cancelled_by_api_key'

def upgrade():
    # move data over
    op.execute("UPDATE broadcast_message SET created_by_api_key_id=api_key_id WHERE created_by_api_key_id IS NULL")
    op.create_check_constraint(
        "ck_broadcast_message_created_by_not_null",
        "broadcast_message",
        "created_by_id is not null or created_by_api_key_id is not null"
    )
    op.drop_column('broadcast_message', 'api_key_id')

def downgrade():
    op.add_column('broadcast_message', sa.Column('api_key_id', postgresql.UUID(), autoincrement=False, nullable=True))
    op.execute("UPDATE broadcast_message SET api_key_id=created_by_api_key_id")  # move data over
    op.drop_constraint(
        "ck_broadcast_message_created_by_not_null",
        "broadcast_message"
    )

Prompt:
Drop api_key_id column from broadcast_message table

This column has been superseded by a new column named
created_by_api_key_id.

Also create constraint checking that we know who created broadcast

Also move data so that constraint is met before instatiating it.


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

"""Module containing mysqlclient installation and cleanup functions."""

def YumInstall(vm):
  """Installs the mysql package on the VM."""
  del vm
  raise NotImplementedError('mysqlclient56 not implemented for yum')

def AptInstall(vm):
  """Installs the mysql package on the VM."""
  vm.RemoteCommand(
      'sudo add-apt-repository '
      "'deb https://mirror.ubuntu.serverforge.org trusty universe'")
  vm.RemoteCommand('sudo apt-get update')
  vm.RemoteCommand('sudo apt-get -y install mysql-client-5.6')

Install mysqlclient from HTTPs repo.

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

"""Module containing mysqlclient installation and cleanup functions."""

def YumInstall(vm):
  """Installs the mysql package on the VM."""
  del vm
  raise NotImplementedError('mysqlclient56 not implemented for yum')

def AptInstall(vm):
  """Installs the mysql package on the VM."""
  vm.RemoteCommand(
      'sudo add-apt-repository '
      "'deb https://mirror.ubuntu.serverforge.org trusty universe'")
  vm.RemoteCommand('sudo apt-get update')
  vm.RemoteCommand('sudo apt-get -y install mysql-client-5.6')

Prompt:
Install mysqlclient from HTTPs repo.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=263786009

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

"""Module containing mysqlclient installation and cleanup functions."""

def YumInstall(vm):
  """Installs the mysql package on the VM."""
  del vm
  raise NotImplementedError('mysqlclient56 not implemented for yum')

def AptInstall(vm):
  """Installs the mysql package on the VM."""
  vm.RemoteCommand('sudo add-apt-repository '
                   "'deb http://archive.ubuntu.com/ubuntu trusty universe'")
  vm.RemoteCommand('sudo apt-get update')
  vm.RemoteCommand('sudo apt-get -y install mysql-client-5.6')


# mod_info.py
#
# Display information about a Protracker module.
#
# Written & released by Keir Fraser <keir.xen@gmail.com>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.

import struct, sys

with open(sys.argv[1], "rb") as f:
    dat = f.read()
dlen = len(dat)

tname, = struct.unpack("20s", dat[:20])
print("Name: '%s'" % tname.decode('utf-8'))
dat = dat[20:]
samples_len = 0
for i in range(31):
    name, wordlen, finetune, volume, repstart, replen = struct.unpack(
        ">22sH2B2H", dat[:30])
    dat = dat[30:]
    if wordlen == 0:
        continue
    samples_len += wordlen*2
print("Sample Data: %u" % samples_len)

songlen, pad = struct.unpack("2B", dat[:2])
dat = dat[2:]
#assert pad == 127
assert songlen <= 128
print("Song Length: %u" % songlen)

patterns = list(struct.unpack("128B", dat[:128]))
dat = dat[128:]
patterns = patterns[:songlen]
nr_patterns = max(patterns)+1
print("Nr Patterns: %u (%u bytes)" % (nr_patterns, nr_patterns*1024))

mksig, = struct.unpack("4s", dat[:4])
dat = dat[4:]
assert mksig == b'M.K.'

totlen = 1084 + nr_patterns*1024 + samples_len
print("Total Bytes: %u (0x%x)" % (totlen, totlen))
assert totlen <= dlen

Include a helpful MOD analyser script

scripts: Include a helpful MOD analyser script

Response:
# mod_info.py
#
# Display information about a Protracker module.
#
# Written & released by Keir Fraser <keir.xen@gmail.com>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.

import struct, sys

with open(sys.argv[1], "rb") as f:
    dat = f.read()
dlen = len(dat)

tname, = struct.unpack("20s", dat[:20])
print("Name: '%s'" % tname.decode('utf-8'))
dat = dat[20:]
samples_len = 0
for i in range(31):
    name, wordlen, finetune, volume, repstart, replen = struct.unpack(
        ">22sH2B2H", dat[:30])
    dat = dat[30:]
    if wordlen == 0:
        continue
    samples_len += wordlen*2
print("Sample Data: %u" % samples_len)

songlen, pad = struct.unpack("2B", dat[:2])
dat = dat[2:]
#assert pad == 127
assert songlen <= 128
print("Song Length: %u" % songlen)

patterns = list(struct.unpack("128B", dat[:128]))
dat = dat[128:]
patterns = patterns[:songlen]
nr_patterns = max(patterns)+1
print("Nr Patterns: %u (%u bytes)" % (nr_patterns, nr_patterns*1024))

mksig, = struct.unpack("4s", dat[:4])
dat = dat[4:]
assert mksig == b'M.K.'

totlen = 1084 + nr_patterns*1024 + samples_len
print("Total Bytes: %u (0x%x)" % (totlen, totlen))
assert totlen <= dlen

Prompt: scripts: Include a helpful MOD analyser script


from setuptools import setup

REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'

setup(
    author='Serenata de Amor',
    author_email='op.serenatadeamor@gmail.com',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Utilities',
    ],
    description='Toolbox for Serenata de Amor project',
    zip_safe=False,
    install_requires=[
        'aiofiles',
        'aiohttp',
        'boto3',
        'beautifulsoup4>=4.4',
        'lxml>=3.6',
        'pandas>=0.18',
        'tqdm'
    ],
    keywords='serenata de amor, data science, brazil, corruption',
    license='MIT',
    long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
    name='serenata-toolbox',
    packages=[
        'serenata_toolbox.federal_senate',
        'serenata_toolbox.chamber_of_deputies',
        'serenata_toolbox.datasets'
    ],
    url=REPO_URL,
    version='12.3.1'
)

Change version from 12.3.0 to 12.3.1

Change version from 12.3.0 to 12.3.1

Response:
from setuptools import setup

REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'

setup(
    author='Serenata de Amor',
    author_email='op.serenatadeamor@gmail.com',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Utilities',
    ],
    description='Toolbox for Serenata de Amor project',
    zip_safe=False,
    install_requires=[
        'aiofiles',
        'aiohttp',
        'boto3',
        'beautifulsoup4>=4.4',
        'lxml>=3.6',
        'pandas>=0.18',
        'tqdm'
    ],
    keywords='serenata de amor, data science, brazil, corruption',
    license='MIT',
    long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
    name='serenata-toolbox',
    packages=[
        'serenata_toolbox.federal_senate',
        'serenata_toolbox.chamber_of_deputies',
        'serenata_toolbox.datasets'
    ],
    url=REPO_URL,
    version='12.3.1'
)

Prompt:
Change version from 12.3.0 to 12.3.1

from setuptools import setup

REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'

setup(
    author='Serenata de Amor',
    author_email='op.serenatadeamor@gmail.com',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Utilities',
    ],
    description='Toolbox for Serenata de Amor project',
    zip_safe=False,
    install_requires=[
        'aiofiles',
        'aiohttp',
        'boto3',
        'beautifulsoup4>=4.4',
        'lxml>=3.6',
        'pandas>=0.18',
        'tqdm'
    ],
    keywords='serenata de amor, data science, brazil, corruption',
    license='MIT',
    long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
    name='serenata-toolbox',
    packages=[
        'serenata_toolbox.federal_senate',
        'serenata_toolbox.chamber_of_deputies',
        'serenata_toolbox.datasets'
    ],
    url=REPO_URL,
    version='12.3.0'
)


# encoding: utf8
from __future__ import unicode_literals
from ...fr import French

def test_load_french():
    nlp = French()
    doc = nlp(u'Parlez-vous français?')
    assert doc[0].text == u'Parlez'
    assert doc[1].text == u'-'
    assert doc[2].text == u'vouz'
    assert doc[3].text == u'français'
    assert doc[4].text == u'?'

Add test for french tokenizer

Add test for french tokenizer

Response:
# encoding: utf8
from __future__ import unicode_literals
from ...fr import French

def test_load_french():
    nlp = French()
    doc = nlp(u'Parlez-vous français?')
    assert doc[0].text == u'Parlez'
    assert doc[1].text == u'-'
    assert doc[2].text == u'vouz'
    assert doc[3].text == u'français'
    assert doc[4].text == u'?'

Prompt:
Add test for french tokenizer

# encoding: utf8
from __future__ import unicode_literals
from ...fr import French

def test_load_french():
    nlp = French()
    doc = nlp(u'Parlez-vous français?')


# -*- coding: utf-8 -*-
import os

from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except Exception:
        return ""

setup(
    name="todoist-python",
    version="8.1.2",
    packages=["todoist", "todoist.managers"],
    author="Doist Team",
    author_email="info@todoist.com",
    license="BSD",
    description="todoist-python - The official Todoist Python API library",
    long_description=read("README.md"),
    install_requires=["requests", "typing"],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Programming Language :: Python",
    ),
)

Update the PyPI version to 8.1.2.

Update the PyPI version to 8.1.2.

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

from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except Exception:
        return ""

setup(
    name="todoist-python",
    version="8.1.2",
    packages=["todoist", "todoist.managers"],
    author="Doist Team",
    author_email="info@todoist.com",
    license="BSD",
    description="todoist-python - The official Todoist Python API library",
    long_description=read("README.md"),
    install_requires=["requests", "typing"],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Programming Language :: Python",
    ),
)

Prompt:
Update the PyPI version to 8.1.2.

# -*- coding: utf-8 -*-
import os

from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except Exception:
        return ""

setup(
    name="todoist-python",
    version="8.1.1",
    packages=["todoist", "todoist.managers"],
    author="Doist Team",
    author_email="info@todoist.com",
    license="BSD",
    description="todoist-python - The official Todoist Python API library",
    long_description=read("README.md"),
    install_requires=["requests", "typing"],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Programming Language :: Python",
    ),
)


from .test_happy_path import TestHappyPath

class TestbackwardsNavigationAfterSubmission(TestHappyPath):

    def test_backwards_navigation(self):
        self.test_happy_path()

        resp = self.client.get('/submission', follow_redirects=False)
        self.assertEquals(resp.status_code, 302)
        self.assertRegexpMatches(resp.headers['Location'], '\/thank-you$')

        resp = self.client.get('/questionnaire', follow_redirects=False)
        self.assertEquals(resp.status_code, 302)
        self.assertRegexpMatches(resp.headers['Location'], '\/thank-you$')

        resp = self.client.get('/landing-page', follow_redirects=False)
        self.assertEquals(resp.status_code, 302)
        self.assertRegexpMatches(resp.headers['Location'], '\/thank-you$')

Add test for navigating backwards, after submission - failing

Response:
from .test_happy_path import TestHappyPath

class TestbackwardsNavigationAfterSubmission(TestHappyPath):

    def test_backwards_navigation(self):
        self.test_happy_path()

        resp = self.client.get('/submission', follow_redirects=False)
        self.assertEquals(resp.status_code, 302)
        self.assertRegexpMatches(resp.headers['Location'], '\/thank-you$')

        resp = self.client.get('/questionnaire', follow_redirects=False)
        self.assertEquals(resp.status_code, 302)
        self.assertRegexpMatches(resp.headers['Location'], '\/thank-you$')

        resp = self.client.get('/landing-page', follow_redirects=False)
        self.assertEquals(resp.status_code, 302)
        self.assertRegexpMatches(resp.headers['Location'], '\/thank-you$')

Prompt: Add test for navigating backwards, after submission - failing