import os
import requests
import tinycss2
from tinycss2 import color3
from flask import Flask, Response, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def merry_christmas():
  return 'Merry Christmas!'

@app.route('/sms', methods=['POST'])
def sms():
    body = request.values.get('Body', None)

    if body is None:
      return Response(mimetype='text/plain')

    sms = body.lower()
    print sms

    rgba = tinycss2.color3.parse_color(sms)

    if rgba is None:
      return Response("Sorry, I don't recognize that color.", mimetype='text/plain')

    if len(rgba) == 4:
      red = int(round(255*rgba[0]))
      green = int(round(255*rgba[1]))
      blue = int(round(255*rgba[2]))
      rgb_string = '[{0:03d},{1:03d},{2:03d}]'.format(red, green, blue)
      payload = {'access_token': os.environ['SPARK_ACCESS_TOKEN'], 'command': rgb_string}
      r = requests.post("https://api.spark.io/v1/devices/{0}/color".format(os.environ['SPARK_CORE_ID']), data=payload)
      return Response(mimetype='text/plain')

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

Add application code with SMS route to accept SMS and route to Spark Core via their API

Response:
<INSERT> import os
import requests
import tinycss2
from tinycss2 import color3
from flask import Flask, Response, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def merry_christmas():
 <INSERT_END> <INSERT> return 'Merry Christmas!'

@app.route('/sms', methods=['POST'])
def sms():
    body = request.values.get('Body', None)

    if body is None:
      return Response(mimetype='text/plain')

    sms = body.lower()
    print sms

    rgba = tinycss2.color3.parse_color(sms)

    if rgba is None:
      return Response("Sorry, I don't recognize that color.", mimetype='text/plain')

    if len(rgba) == 4:
      red = int(round(255*rgba[0]))
      green = int(round(255*rgba[1]))
      blue = int(round(255*rgba[2]))
      rgb_string = '[{0:03d},{1:03d},{2:03d}]'.format(red, green, blue)
      payload = {'access_token': os.environ['SPARK_ACCESS_TOKEN'], 'command': rgb_string}
      r = requests.post("https://api.spark.io/v1/devices/{0}/color".format(os.environ['SPARK_CORE_ID']), data=payload)
      return Response(mimetype='text/plain')

if __name__ == '__main__':
  app.run()
 <INSERT_END> <|endoftext|> import os
import requests
import tinycss2
from tinycss2 import color3
from flask import Flask, Response, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def merry_christmas():
  return 'Merry Christmas!'

@app.route('/sms', methods=['POST'])
def sms():
    body = request.values.get('Body', None)

    if body is None:
      return Response(mimetype='text/plain')

    sms = body.lower()
    print sms

    rgba = tinycss2.color3.parse_color(sms)

    if rgba is None:
      return Response("Sorry, I don't recognize that color.", mimetype='text/plain')

    if len(rgba) == 4:
      red = int(round(255*rgba[0]))
      green = int(round(255*rgba[1]))
      blue = int(round(255*rgba[2]))
      rgb_string = '[{0:03d},{1:03d},{2:03d}]'.format(red, green, blue)
      payload = {'access_token': os.environ['SPARK_ACCESS_TOKEN'], 'command': rgb_string}
      r = requests.post("https://api.spark.io/v1/devices/{0}/color".format(os.environ['SPARK_CORE_ID']), data=payload)
      return Response(mimetype='text/plain')

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

Prompt: Add application code with SMS route to accept SMS and route to Spark Core via their API


# Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf

def calDistance(point1, point2):
    return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])

def calHeading(point1, point2):
    return sf.calHeading([point1.longitude, point1.latitude],
                    [point2.longitude, point2.latitude])

def calHC(point1, point2, point3):
    return sf.calHC([point1.longitude, point1.latitude],
                    [point2.longitude, point2.latitude],
                    [point3.longitude, point3.latitude])

def calSpeed(point1, point2):
    distanceDelta = calDistance(point1, point2)
    timeDelta = point2.ts - point1.ts
    # print "Distance delta = %s and time delta = %s" % (distanceDelta, timeDelta)
    # assert(timeDelta != 0)
    if (timeDelta == 0):
        logging.debug("timeDelta = 0, distanceDelta = %s, returning speed = 0")
        assert(distanceDelta < 0.01)
        return 0

    return distanceDelta/timeDelta

Response:
<REPLACE_OLD> point2.mTime <REPLACE_NEW> point2.ts <REPLACE_END> <REPLACE_OLD> point1.mTime
 <REPLACE_NEW> point1.ts
 <REPLACE_END> <DELETE> # TODO: Once we perform the conversions from ms to secs as part of the
    # usercache -> timeseries switch, we need to remove this division by 1000
    <DELETE_END> <REPLACE_OLD> distanceDelta/(float(timeDelta)/1000)
 <REPLACE_NEW> distanceDelta/timeDelta
 <REPLACE_END> <|endoftext|> # Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf

def calDistance(point1, point2):
    return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])

def calHeading(point1, point2):
    return sf.calHeading([point1.longitude, point1.latitude],
                    [point2.longitude, point2.latitude])

def calHC(point1, point2, point3):
    return sf.calHC([point1.longitude, point1.latitude],
                    [point2.longitude, point2.latitude],
                    [point3.longitude, point3.latitude])

def calSpeed(point1, point2):
    distanceDelta = calDistance(point1, point2)
    timeDelta = point2.ts - point1.ts
    # print "Distance delta = %s and time delta = %s" % (distanceDelta, timeDelta)
    # assert(timeDelta != 0)
    if (timeDelta == 0):
        logging.debug("timeDelta = 0, distanceDelta = %s, returning speed = 0")
        assert(distanceDelta < 0.01)
        return 0

    return distanceDelta/timeDelta

Prompt:
Change the feature calculation to match the new unified format

- the timestamps are now in seconds, so no need to divide them
- the field is called ts, not mTime

# Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf

def calDistance(point1, point2):
    return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])

def calHeading(point1, point2):
    return sf.calHeading([point1.longitude, point1.latitude],
                    [point2.longitude, point2.latitude])

def calHC(point1, point2, point3):
    return sf.calHC([point1.longitude, point1.latitude],
                    [point2.longitude, point2.latitude],
                    [point3.longitude, point3.latitude])

def calSpeed(point1, point2):
    distanceDelta = calDistance(point1, point2)
    timeDelta = point2.mTime - point1.mTime
    # print "Distance delta = %s and time delta = %s" % (distanceDelta, timeDelta)
    # assert(timeDelta != 0)
    if (timeDelta == 0):
        logging.debug("timeDelta = 0, distanceDelta = %s, returning speed = 0")
        assert(distanceDelta < 0.01)
        return 0

    # TODO: Once we perform the conversions from ms to secs as part of the
    # usercache -> timeseries switch, we need to remove this division by 1000
    return distanceDelta/(float(timeDelta)/1000)


import requests

class myElsClient:
    """A class that implements a Python interface to api.elsevier.com"""

    # local variables
    __base_url = "https://api.elsevier.com/"

    # constructors
    def __init__(self, apiKey):
        """Instantiates a client with a given API Key."""
        self.apiKey = apiKey

    # configuration functions
    def setInstToken(self, instToken):
        """Sets an institutional token for customer authentication"""
        self.instToken = instToken

    # utility access functions
    def getBaseURL(self):
        """Returns the base URL currently configured for Elsevier's APIs"""
        return self.__base_url

    # request/response execution functions
    def execRequest(self,pathStr,queryStr):
        """Constructs and sends the actual request; returns response."""
        headers = {
            "X-ELS-APIKey" : self.apiKey
            }
        r = requests.get(
            self.__base_url + pathStr + queryStr,
            headers = headers
            )
        if r.status_code == 200:
            return r
        else:
            print "error"

Add basic HTTP error handling.

Add basic HTTP error handling.

Response:
<REPLACE_OLD> send <REPLACE_NEW> sends <REPLACE_END> <REPLACE_OLD> request"""
 <REPLACE_NEW> request; returns response."""
 <REPLACE_END> <INSERT> if r.status_code == 200:
            <INSERT_END> <INSERT>        else:
            print "error"
 <INSERT_END> <|endoftext|> import requests

class myElsClient:
    """A class that implements a Python interface to api.elsevier.com"""

    # local variables
    __base_url = "https://api.elsevier.com/"

    # constructors
    def __init__(self, apiKey):
        """Instantiates a client with a given API Key."""
        self.apiKey = apiKey

    # configuration functions
    def setInstToken(self, instToken):
        """Sets an institutional token for customer authentication"""
        self.instToken = instToken

    # utility access functions
    def getBaseURL(self):
        """Returns the base URL currently configured for Elsevier's APIs"""
        return self.__base_url

    # request/response execution functions
    def execRequest(self,pathStr,queryStr):
        """Constructs and sends the actual request; returns response."""
        headers = {
            "X-ELS-APIKey" : self.apiKey
            }
        r = requests.get(
            self.__base_url + pathStr + queryStr,
            headers = headers
            )
        if r.status_code == 200:
            return r
        else:
            print "error"

Prompt:
Add basic HTTP error handling.

import requests

class myElsClient:
    """A class that implements a Python interface to api.elsevier.com"""

    # local variables
    __base_url = "https://api.elsevier.com/"

    # constructors
    def __init__(self, apiKey):
        """Instantiates a client with a given API Key."""
        self.apiKey = apiKey

    # configuration functions
    def setInstToken(self, instToken):
        """Sets an institutional token for customer authentication"""
        self.instToken = instToken

    # utility access functions
    def getBaseURL(self):
        """Returns the base URL currently configured for Elsevier's APIs"""
        return self.__base_url

    # request/response execution functions
    def execRequest(self,pathStr,queryStr):
        """Constructs and send the actual request"""
        headers = {
            "X-ELS-APIKey" : self.apiKey
            }
        r = requests.get(
            self.__base_url + pathStr + queryStr,
            headers = headers
            )
        return r


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

import logging

from service_registry_cli.utils import BaseCommand, get_client

class RemoveCommand(BaseCommand):
    """
    Remove a configuration value.
    """
    log = logging.getLogger(__name__)

    def get_parser(self, prog_name):
        parser = super(RemoveCommand, self).get_parser(prog_name=prog_name)
        parser.add_argument('--id', dest='id')
        return parser

    def take_action(self, parsed_args):
        client = get_client(parsed_args)
        configuration_id = parsed_args.id
        client.configuration.remove(configuration_id=configuration_id)
        self.app.stdout.write('Configuration value "%s" has been removed\n' %
                              (configuration_id))

Add a command for removing a configuration value.

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

import logging

from service_registry_cli.utils import BaseCommand, get_client

class RemoveCommand(BaseCommand):
    """
    Remove a configuration value.
    """
    log = logging.getLogger(__name__)

    def get_parser(self, prog_name):
        parser = super(RemoveCommand, self).get_parser(prog_name=prog_name)
        parser.add_argument('--id', dest='id')
        return parser

    def take_action(self, parsed_args):
        client = get_client(parsed_args)
        configuration_id = parsed_args.id
        client.configuration.remove(configuration_id=configuration_id)
        self.app.stdout.write('Configuration value "%s" has been removed\n' %
                              (configuration_id))
 <REPLACE_END> <|endoftext|> # Copyright 2012 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from service_registry_cli.utils import BaseCommand, get_client

class RemoveCommand(BaseCommand):
    """
    Remove a configuration value.
    """
    log = logging.getLogger(__name__)

    def get_parser(self, prog_name):
        parser = super(RemoveCommand, self).get_parser(prog_name=prog_name)
        parser.add_argument('--id', dest='id')
        return parser

    def take_action(self, parsed_args):
        client = get_client(parsed_args)
        configuration_id = parsed_args.id
        client.configuration.remove(configuration_id=configuration_id)
        self.app.stdout.write('Configuration value "%s" has been removed\n' %
                              (configuration_id))

Prompt: Add a command for removing a configuration value.


from django import forms

from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet

class VendOutletForm(forms.ModelForm):

    deleted_at = VendDateTimeField(required=False)

    def __init__(self, data=None, *args, **kwargs):
        if data:
            uid = data.pop('id', None)
            if uid is not None:
                data['uid'] = uid

            tax_inc = data.pop('display_prices', None)
            if tax_inc is not None:
                if tax_inc == 'inclusive':
                    data['display_prices_tax_inclusive'] = True
                elif tax_inc == 'exclusive':
                    data['display_prices_tax_inclusive'] = False

            deleted_at = data.get('deleted_at')
            if deleted_at is not None and deleted_at == 'null':
                data['deleted_at'] = None

            if 'instance' not in kwargs or kwargs['instance'] is None:
                # Note: currently assumes instance is always passed as a kwarg
                # - need to check but this is probably bad
                try:
                    kwargs['instance'] = VendOutlet.objects.get(uid=uid)
                except VendOutlet.DoesNotExist:
                    pass

        super(VendOutletForm, self).__init__(data, *args, **kwargs)

    class Meta:
        model = VendOutlet
        fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
                  'display_prices_tax_inclusive', 'deleted_at']

Response:
<INSERT>     if 'instance' not in kwargs or kwargs['instance'] is None:
                # Note: currently assumes instance is always passed as a kwarg
                # - need to check but this is probably bad
                try:
                    kwargs['instance'] = VendOutlet.objects.get(uid=uid)
                except VendOutlet.DoesNotExist:
                    pass

        <INSERT_END> <|endoftext|> from django import forms

from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet

class VendOutletForm(forms.ModelForm):

    deleted_at = VendDateTimeField(required=False)

    def __init__(self, data=None, *args, **kwargs):
        if data:
            uid = data.pop('id', None)
            if uid is not None:
                data['uid'] = uid

            tax_inc = data.pop('display_prices', None)
            if tax_inc is not None:
                if tax_inc == 'inclusive':
                    data['display_prices_tax_inclusive'] = True
                elif tax_inc == 'exclusive':
                    data['display_prices_tax_inclusive'] = False

            deleted_at = data.get('deleted_at')
            if deleted_at is not None and deleted_at == 'null':
                data['deleted_at'] = None

            if 'instance' not in kwargs or kwargs['instance'] is None:
                # Note: currently assumes instance is always passed as a kwarg
                # - need to check but this is probably bad
                try:
                    kwargs['instance'] = VendOutlet.objects.get(uid=uid)
                except VendOutlet.DoesNotExist:
                    pass

        super(VendOutletForm, self).__init__(data, *args, **kwargs)

    class Meta:
        model = VendOutlet
        fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
                  'display_prices_tax_inclusive', 'deleted_at']

Prompt:
Make form update existing instance if uid matches

from django import forms

from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet

class VendOutletForm(forms.ModelForm):

    deleted_at = VendDateTimeField(required=False)

    def __init__(self, data=None, *args, **kwargs):
        if data:
            uid = data.pop('id', None)
            if uid is not None:
                data['uid'] = uid

            tax_inc = data.pop('display_prices', None)
            if tax_inc is not None:
                if tax_inc == 'inclusive':
                    data['display_prices_tax_inclusive'] = True
                elif tax_inc == 'exclusive':
                    data['display_prices_tax_inclusive'] = False

            deleted_at = data.get('deleted_at')
            if deleted_at is not None and deleted_at == 'null':
                data['deleted_at'] = None

        super(VendOutletForm, self).__init__(data, *args, **kwargs)

    class Meta:
        model = VendOutlet
        fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
                  'display_prices_tax_inclusive', 'deleted_at']


import asyncio
import json

import aiohttp

import SLA_bot.config as cf

class AlertFeed:
    source_url = 'http://pso2emq.flyergo.eu/api/v2/'

    async def download(url):
        try:
            async with aiohttp.get(url) as response:
                return await response.json()
        except json.decoder.JSONDecodeError:
            pass

    def parse_data(data):
        latest_alert = data[0]['text']
        lines = latest_alert.splitlines()
        code_color = 'fix' if len(lines) >= 10 else ''
        header = '-' * len(lines[0])
        lines.insert(1, header)
        text = '\n'.join(lines)
        return '```{}\n{}\n```'.format(code_color, text)

    async def fetch():
        header = cf.get('PSO2 Feed', 'header')
        raw_data = await AlertFeed.download(AlertFeed.source_url)
        return '** **\n' + header + '\n' + AlertFeed.parse_data(raw_data)

Response:
<INSERT> code_color = 'fix' if len(lines) >= 10 else ''
        <INSERT_END> <REPLACE_OLD> '```fix\n{}\n```'.format(text)
 <REPLACE_NEW> '```{}\n{}\n```'.format(code_color, text)
 <REPLACE_END> <|endoftext|> import asyncio
import json

import aiohttp

import SLA_bot.config as cf

class AlertFeed:
    source_url = 'http://pso2emq.flyergo.eu/api/v2/'

    async def download(url):
        try:
            async with aiohttp.get(url) as response:
                return await response.json()
        except json.decoder.JSONDecodeError:
            pass

    def parse_data(data):
        latest_alert = data[0]['text']
        lines = latest_alert.splitlines()
        code_color = 'fix' if len(lines) >= 10 else ''
        header = '-' * len(lines[0])
        lines.insert(1, header)
        text = '\n'.join(lines)
        return '```{}\n{}\n```'.format(code_color, text)

    async def fetch():
        header = cf.get('PSO2 Feed', 'header')
        raw_data = await AlertFeed.download(AlertFeed.source_url)
        return '** **\n' + header + '\n' + AlertFeed.parse_data(raw_data)

Prompt:
Remove text coloring in AlertFeed if it seems like scheduled text

import asyncio
import json

import aiohttp

import SLA_bot.config as cf

class AlertFeed:
    source_url = 'http://pso2emq.flyergo.eu/api/v2/'

    async def download(url):
        try:
            async with aiohttp.get(url) as response:
                return await response.json()
        except json.decoder.JSONDecodeError:
            pass

    def parse_data(data):
        latest_alert = data[0]['text']
        lines = latest_alert.splitlines()
        header = '-' * len(lines[0])
        lines.insert(1, header)
        text = '\n'.join(lines)
        return '```fix\n{}\n```'.format(text)

    async def fetch():
        header = cf.get('PSO2 Feed', 'header')
        raw_data = await AlertFeed.download(AlertFeed.source_url)
        return '** **\n' + header + '\n' + AlertFeed.parse_data(raw_data)


import collections
import math
import unittest

import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser

class MyrialTestCase(unittest.TestCase):

    def setUp(self):
        self.db = raco.fakedb.FakeDatabase()
        self.parser = parser.Parser()
        self.processor = interpreter.StatementProcessor(self.db)

    def execute_query(self, query, test_logical=False):
        '''Run a test query against the fake database'''
        statements = self.parser.parse(query)
        self.processor.evaluate(statements)

        if test_logical:
            plan = self.processor.get_logical_plan()
        else:
            plan = self.processor.get_physical_plan()
        self.db.evaluate(plan)

        return self.db.get_temp_table('__OUTPUT0__')

    def run_test(self, query, expected, test_logical=False):
        '''Execute a test query with an expected output'''
        actual = self.execute_query(query, test_logical)
        self.assertEquals(actual, expected)

Response:
<REPLACE_OLD> parser
from raco.myrialang import compile_to_json

class <REPLACE_NEW> parser

class <REPLACE_END> <REPLACE_OLD>     json = compile_to_json(query, '', [('A', plan)])

        self.db.evaluate(plan)

 <REPLACE_NEW> self.db.evaluate(plan)

 <REPLACE_END> <|endoftext|>
import collections
import math
import unittest

import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser

class MyrialTestCase(unittest.TestCase):

    def setUp(self):
        self.db = raco.fakedb.FakeDatabase()
        self.parser = parser.Parser()
        self.processor = interpreter.StatementProcessor(self.db)

    def execute_query(self, query, test_logical=False):
        '''Run a test query against the fake database'''
        statements = self.parser.parse(query)
        self.processor.evaluate(statements)

        if test_logical:
            plan = self.processor.get_logical_plan()
        else:
            plan = self.processor.get_physical_plan()
        self.db.evaluate(plan)

        return self.db.get_temp_table('__OUTPUT0__')

    def run_test(self, query, expected, test_logical=False):
        '''Execute a test query with an expected output'''
        actual = self.execute_query(query, test_logical)
        self.assertEquals(actual, expected)

Prompt:
Revert "Add compile_to_json invocation in Myrial test fixture"

This reverts commit ceb848021d5323b5bad8518ac7ed850a51fc89ca.

import collections
import math
import unittest

import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json

class MyrialTestCase(unittest.TestCase):

    def setUp(self):
        self.db = raco.fakedb.FakeDatabase()
        self.parser = parser.Parser()
        self.processor = interpreter.StatementProcessor(self.db)

    def execute_query(self, query, test_logical=False):
        '''Run a test query against the fake database'''
        statements = self.parser.parse(query)
        self.processor.evaluate(statements)

        if test_logical:
            plan = self.processor.get_logical_plan()
        else:
            plan = self.processor.get_physical_plan()
            json = compile_to_json(query, '', [('A', plan)])

        self.db.evaluate(plan)

        return self.db.get_temp_table('__OUTPUT0__')

    def run_test(self, query, expected, test_logical=False):
        '''Execute a test query with an expected output'''
        actual = self.execute_query(query, test_logical)
        self.assertEquals(actual, expected)


"""
The `safeopt` package provides...

Main classes
============

These classes provide the main functionality for Safe Bayesian optimization.

.. autosummary::
   SafeOpt
   SafeOptSwarm

Utilities
=========

The following are utilities to make testing and working with the library more pleasant.

.. autosummary::
   sample_gp_function
   linearly_spaced_combinations
   plot_2d_gp
   plot_3d_gp
   plot_contour_gp
"""

from __future__ import absolute_import

from .utilities import *
from .gp_opt import *

__all__ = [s for s in dir() if not s.startswith('_')]

Add short comment to docs

Add short comment to docs

Response:
<REPLACE_OLD> classes
============
.. <REPLACE_NEW> classes
============

These classes provide the main functionality for Safe Bayesian optimization.

.. <REPLACE_END> <REPLACE_OLD> SafeOptSwarm

Utilities
=========
.. <REPLACE_NEW> SafeOptSwarm

Utilities
=========

The following are utilities to make testing and working with the library more pleasant.

.. <REPLACE_END> <|endoftext|> """
The `safeopt` package provides...

Main classes
============

These classes provide the main functionality for Safe Bayesian optimization.

.. autosummary::
   SafeOpt
   SafeOptSwarm

Utilities
=========

The following are utilities to make testing and working with the library more pleasant.

.. autosummary::
   sample_gp_function
   linearly_spaced_combinations
   plot_2d_gp
   plot_3d_gp
   plot_contour_gp
"""

from __future__ import absolute_import

from .utilities import *
from .gp_opt import *

__all__ = [s for s in dir() if not s.startswith('_')]

Prompt:
Add short comment to docs

"""
The `safeopt` package provides...

Main classes
============
.. autosummary::
   SafeOpt
   SafeOptSwarm

Utilities
=========
.. autosummary::
   sample_gp_function
   linearly_spaced_combinations
   plot_2d_gp
   plot_3d_gp
   plot_contour_gp
"""

from __future__ import absolute_import

from .utilities import *
from .gp_opt import *

__all__ = [s for s in dir() if not s.startswith('_')]


import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup

class NBSetupTestCase(unittest.TestCase):
    def setUp(self):
        self.prefix = tempfile.mkdtemp()
        self.params = {
            'prefix': self.prefix,
            'static': os.path.join(os.path.dirname(__file__), 'support'),
        }

    def test_initialize(self):
        assert NBSetup('name').path == jupyter_config_dir()
        # assert NBSetup('name', prefix="/tmp").path == "/tmp/etc/jupyter"

    def test_install(self):
        nb_setup = NBSetup('name', **self.params)
        nb_setup.install()

        assert os.path.exists(
            os.path.join(self.prefix, 'share', 'jupyter', 'nbextensions', 'name'))

    def test_enable(self):
        nb_setup = NBSetup('name', **self.params)
        nb_setup.enable()

        for f in ['notebook.json', 'tree.json', 'edit.json']:
            assert os.path.exists(
                os.path.join(self.prefix, 'etc', 'jupyter', 'nbconfig', f)
            )

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

Response:
<INSERT> # <INSERT_END> <|endoftext|> import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup

class NBSetupTestCase(unittest.TestCase):
    def setUp(self):
        self.prefix = tempfile.mkdtemp()
        self.params = {
            'prefix': self.prefix,
            'static': os.path.join(os.path.dirname(__file__), 'support'),
        }

    def test_initialize(self):
        assert NBSetup('name').path == jupyter_config_dir()
        # assert NBSetup('name', prefix="/tmp").path == "/tmp/etc/jupyter"

    def test_install(self):
        nb_setup = NBSetup('name', **self.params)
        nb_setup.install()

        assert os.path.exists(
            os.path.join(self.prefix, 'share', 'jupyter', 'nbextensions', 'name'))

    def test_enable(self):
        nb_setup = NBSetup('name', **self.params)
        nb_setup.enable()

        for f in ['notebook.json', 'tree.json', 'edit.json']:
            assert os.path.exists(
                os.path.join(self.prefix, 'etc', 'jupyter', 'nbconfig', f)
            )

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

Prompt:
Comment out test that doesn't pass on Windows

It appears to be assuming unix paths, so I'm going on the assumption
that it's not a valid test case on Windows.

import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup

class NBSetupTestCase(unittest.TestCase):
    def setUp(self):
        self.prefix = tempfile.mkdtemp()
        self.params = {
            'prefix': self.prefix,
            'static': os.path.join(os.path.dirname(__file__), 'support'),
        }

    def test_initialize(self):
        assert NBSetup('name').path == jupyter_config_dir()
        assert NBSetup('name', prefix="/tmp").path == "/tmp/etc/jupyter"

    def test_install(self):
        nb_setup = NBSetup('name', **self.params)
        nb_setup.install()

        assert os.path.exists(
            os.path.join(self.prefix, 'share', 'jupyter', 'nbextensions', 'name'))

    def test_enable(self):
        nb_setup = NBSetup('name', **self.params)
        nb_setup.enable()

        for f in ['notebook.json', 'tree.json', 'edit.json']:
            assert os.path.exists(
                os.path.join(self.prefix, 'etc', 'jupyter', 'nbconfig', f)
            )

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


from heutagogy import app
import heutagogy.persistence

from flask import request, jsonify, Response
import json
import datetime
import sqlite3

heutagogy.persistence.initialize()

@app.route('/')
def index():
    return 'Hello, world!'

@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
    r = request.get_json(force=True)

    bookmark = dict()
    try:
        bookmark['url'] = r['url']
    except:
        return jsonify(message='url field is mandatory'), 400

    bookmark['title'] = r['title'] if 'title' in r else bookmark['url']
    bookmark['timestamp'] = r['timestamp'] if 'timestamp' in r else datetime.datetime.utcnow().isoformat(' ')

    result = heutagogy.persistence.save_bookmark(bookmark)
    return jsonify(**result), 201

@app.route('/api/v1/bookmarks', methods=['GET'])
def bookmarks_get():
    result = heutagogy.persistence.get_bookmarks()
    return Response(json.dumps(result), mimetype='application/json')

Response:
<REPLACE_OLD> request.get_json()

 <REPLACE_NEW> request.get_json(force=True)

 <REPLACE_END> <|endoftext|> from heutagogy import app
import heutagogy.persistence

from flask import request, jsonify, Response
import json
import datetime
import sqlite3

heutagogy.persistence.initialize()

@app.route('/')
def index():
    return 'Hello, world!'

@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
    r = request.get_json(force=True)

    bookmark = dict()
    try:
        bookmark['url'] = r['url']
    except:
        return jsonify(message='url field is mandatory'), 400

    bookmark['title'] = r['title'] if 'title' in r else bookmark['url']
    bookmark['timestamp'] = r['timestamp'] if 'timestamp' in r else datetime.datetime.utcnow().isoformat(' ')

    result = heutagogy.persistence.save_bookmark(bookmark)
    return jsonify(**result), 201

@app.route('/api/v1/bookmarks', methods=['GET'])
def bookmarks_get():
    result = heutagogy.persistence.get_bookmarks()
    return Response(json.dumps(result), mimetype='application/json')

Prompt:
Fix reading json from client (ignore mimetype).

• http://stackoverflow.com/a/14112400/2517622

from heutagogy import app
import heutagogy.persistence

from flask import request, jsonify, Response
import json
import datetime
import sqlite3

heutagogy.persistence.initialize()

@app.route('/')
def index():
    return 'Hello, world!'

@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
    r = request.get_json()

    bookmark = dict()
    try:
        bookmark['url'] = r['url']
    except:
        return jsonify(message='url field is mandatory'), 400

    bookmark['title'] = r['title'] if 'title' in r else bookmark['url']
    bookmark['timestamp'] = r['timestamp'] if 'timestamp' in r else datetime.datetime.utcnow().isoformat(' ')

    result = heutagogy.persistence.save_bookmark(bookmark)
    return jsonify(**result), 201

@app.route('/api/v1/bookmarks', methods=['GET'])
def bookmarks_get():
    result = heutagogy.persistence.get_bookmarks()
    return Response(json.dumps(result), mimetype='application/json')


import gc
import resource

import pytest

from .models import TestModel as DirtyMixinModel

pytestmark = pytest.mark.django_db

def test_rss_usage():
    DirtyMixinModel()
    gc.collect()
    rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    for _ in range(1000):
        DirtyMixinModel()
    gc.collect()
    rss_2 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    assert rss_2 == rss_1, 'There is a memory leak!'

Response:
<INSERT> gc
import <INSERT_END> <INSERT>    gc.collect()
 <INSERT_END> <INSERT> gc.collect()
    <INSERT_END> <|endoftext|> import gc
import resource

import pytest

from .models import TestModel as DirtyMixinModel

pytestmark = pytest.mark.django_db

def test_rss_usage():
    DirtyMixinModel()
    gc.collect()
    rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    for _ in range(1000):
        DirtyMixinModel()
    gc.collect()
    rss_2 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    assert rss_2 == rss_1, 'There is a memory leak!'

Prompt:
Call gc.collect() before measuring memory usage.

import resource

import pytest

from .models import TestModel as DirtyMixinModel

pytestmark = pytest.mark.django_db

def test_rss_usage():
    DirtyMixinModel()
    rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    for _ in range(1000):
        DirtyMixinModel()
    rss_2 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    assert rss_2 == rss_1, 'There is a memory leak!'


import pytest
import requests
from time import sleep

COMPONENT_INDEX_URL = "http://identidock:5000"

COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster'

def test_get_mainpage():
	print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server')
	sleep(1)
	page = requests.get(COMPONENT_INDEX_URL)
	assert page.status_code == 200
	assert 'Joe Bloggs' in str(page.text)

def test_post_mainpage():
	page = requests.post(COMPONENT_INDEX_URL, data=dict(name="Moby Dock"))
	assert page.status_code == 200
	assert 'Moby Dock' in str(page.text)

def test_mainpage_html_escaping():
	page = requests.post(COMPONENT_INDEX_URL, data=dict(name='"><b>TEST</b><!--'))
	assert page.status_code == 200
	assert '<b>' not in str(page.text)

def test_get_identicon_with_valid_name_and_invalid_post_method_should_return_405():
	name_hash = 'ABCDEF123456789'

	page = requests.post('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	assert page.status_code == 405

def test_get_identicon_with_valid_name_and_cache_miss():
	name_hash = 'ABCDEF123456789'
	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

def test_get_identicon_with_valid_name_and_cache_hit():
	name_hash = 'ABCDEF123456789'
	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

def test_get_identicon_with_insecure_and_unescaped_invalid_name_hash():
	invalid_name_hash = '<b>;i_am_invalid|name <{"'

	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, invalid_name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

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

Response:
<REPLACE_OLD> sys

print(sys.path)
 <REPLACE_NEW> pytest
import requests
from time import sleep

COMPONENT_INDEX_URL = "http://identidock:5000"

COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster'

def test_get_mainpage():
	print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server')
	sleep(1)
	page = requests.get(COMPONENT_INDEX_URL)
	assert page.status_code == 200
	assert 'Joe Bloggs' in str(page.text)

def test_post_mainpage():
	page = requests.post(COMPONENT_INDEX_URL, data=dict(name="Moby Dock"))
	assert page.status_code == 200
	assert 'Moby Dock' in str(page.text)

def test_mainpage_html_escaping():
	page = requests.post(COMPONENT_INDEX_URL, data=dict(name='"><b>TEST</b><!--'))
	assert page.status_code == 200
	assert '<b>' not in str(page.text)

def test_get_identicon_with_valid_name_and_invalid_post_method_should_return_405():
	name_hash = 'ABCDEF123456789'

	page = requests.post('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	assert page.status_code == 405

def test_get_identicon_with_valid_name_and_cache_miss():
	name_hash = 'ABCDEF123456789'
	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

def test_get_identicon_with_valid_name_and_cache_hit():
	name_hash = 'ABCDEF123456789'
	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

def test_get_identicon_with_insecure_and_unescaped_invalid_name_hash():
	invalid_name_hash = '<b>;i_am_invalid|name <{"'

	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, invalid_name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

if __name__ == '__main__':
	# unittest.main()
	pytest.main()
 <REPLACE_END> <|endoftext|> import pytest
import requests
from time import sleep

COMPONENT_INDEX_URL = "http://identidock:5000"

COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster'

def test_get_mainpage():
	print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server')
	sleep(1)
	page = requests.get(COMPONENT_INDEX_URL)
	assert page.status_code == 200
	assert 'Joe Bloggs' in str(page.text)

def test_post_mainpage():
	page = requests.post(COMPONENT_INDEX_URL, data=dict(name="Moby Dock"))
	assert page.status_code == 200
	assert 'Moby Dock' in str(page.text)

def test_mainpage_html_escaping():
	page = requests.post(COMPONENT_INDEX_URL, data=dict(name='"><b>TEST</b><!--'))
	assert page.status_code == 200
	assert '<b>' not in str(page.text)

def test_get_identicon_with_valid_name_and_invalid_post_method_should_return_405():
	name_hash = 'ABCDEF123456789'

	page = requests.post('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	assert page.status_code == 405

def test_get_identicon_with_valid_name_and_cache_miss():
	name_hash = 'ABCDEF123456789'
	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

def test_get_identicon_with_valid_name_and_cache_hit():
	name_hash = 'ABCDEF123456789'
	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

def test_get_identicon_with_insecure_and_unescaped_invalid_name_hash():
	invalid_name_hash = '<b>;i_am_invalid|name <{"'

	page = requests.get('{0}/{1}'.format(COMPONENT_MONSTER_BASE_URL, invalid_name_hash))

	# print('page.content : {0}'.format(page.content))
	assert page.status_code == 200

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

Prompt:
Add component test functions using pytest

import sys

print(sys.path)


import os
from setuptools import setup

def getPackages(base):
    packages = []

    def visit(arg, directory, files):
        if '__init__.py' in files:
            packages.append(directory.replace('/', '.'))

    os.path.walk(base, visit, None)

    return packages

setup(
    name='tryfer',
    version='0.1',
    description='Twisted Zipkin Tracing Library',
    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.7',
        'Framework :: Twisted'
    ],
    maintainer='David Reid',
    maintainer_email='david.reid@rackspace.com',
    license='APL2',
    url='https://github.com/racker/tryfer',
    long_description=open('README.rst').read(),
    packages=getPackages('tryfer'),
    install_requires=[
        'Twisted >= 12.0.0',
        'thrift == 0.8.0',
        'scrivener == 0.2'
    ],
)

Add maintainer and long description.

Add maintainer and long description.

Response:
<INSERT> maintainer='David Reid',
    maintainer_email='david.reid@rackspace.com',
    <INSERT_END> <REPLACE_OLD> url='https://github.com/racker/tryfer',

 <REPLACE_NEW> url='https://github.com/racker/tryfer',
    long_description=open('README.rst').read(),
 <REPLACE_END> <|endoftext|> import os
from setuptools import setup

def getPackages(base):
    packages = []

    def visit(arg, directory, files):
        if '__init__.py' in files:
            packages.append(directory.replace('/', '.'))

    os.path.walk(base, visit, None)

    return packages

setup(
    name='tryfer',
    version='0.1',
    description='Twisted Zipkin Tracing Library',
    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.7',
        'Framework :: Twisted'
    ],
    maintainer='David Reid',
    maintainer_email='david.reid@rackspace.com',
    license='APL2',
    url='https://github.com/racker/tryfer',
    long_description=open('README.rst').read(),
    packages=getPackages('tryfer'),
    install_requires=[
        'Twisted >= 12.0.0',
        'thrift == 0.8.0',
        'scrivener == 0.2'
    ],
)

Prompt:
Add maintainer and long description.

import os
from setuptools import setup

def getPackages(base):
    packages = []

    def visit(arg, directory, files):
        if '__init__.py' in files:
            packages.append(directory.replace('/', '.'))

    os.path.walk(base, visit, None)

    return packages

setup(
    name='tryfer',
    version='0.1',
    description='Twisted Zipkin Tracing Library',
    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.7',
        'Framework :: Twisted'
    ],
    license='APL2',
    url='https://github.com/racker/tryfer',

    packages=getPackages('tryfer'),
    install_requires=[
        'Twisted >= 12.0.0',
        'thrift == 0.8.0',
        'scrivener == 0.2'
    ],
)


from flask import Flask
from flask import request
from flask import jsonify

from y_text_recommender_system.recommender import recommend

app = Flask(__name__)

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, payload=None):
        Exception.__init__(self)
        self.message = message
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/recommender/', methods=['POST'])
def recommender():
    content = request.get_json()
    if content is not None:
        doc = content.get('doc', {})
        docs = content.get('docs', [])
        if doc == {}:
            msg = 'The parameter `doc` is missing or empty'
            raise InvalidUsage(msg)
        if len(docs) == 0:
            msg = 'The parameter `docs` is missing or empty'
            raise InvalidUsage(msg)
        result = recommend(doc, docs)
        return jsonify(result)
    else:
        msg = 'You need to send the parameters: doc and docs'
        raise InvalidUsage(msg)

Remove GET options in url

Remove GET options in url

Response:
<REPLACE_OLD> methods=['GET', 'POST'])
def <REPLACE_NEW> methods=['POST'])
def <REPLACE_END> <|endoftext|> from flask import Flask
from flask import request
from flask import jsonify

from y_text_recommender_system.recommender import recommend

app = Flask(__name__)

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, payload=None):
        Exception.__init__(self)
        self.message = message
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/recommender/', methods=['POST'])
def recommender():
    content = request.get_json()
    if content is not None:
        doc = content.get('doc', {})
        docs = content.get('docs', [])
        if doc == {}:
            msg = 'The parameter `doc` is missing or empty'
            raise InvalidUsage(msg)
        if len(docs) == 0:
            msg = 'The parameter `docs` is missing or empty'
            raise InvalidUsage(msg)
        result = recommend(doc, docs)
        return jsonify(result)
    else:
        msg = 'You need to send the parameters: doc and docs'
        raise InvalidUsage(msg)

Prompt:
Remove GET options in url

from flask import Flask
from flask import request
from flask import jsonify

from y_text_recommender_system.recommender import recommend

app = Flask(__name__)

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, payload=None):
        Exception.__init__(self)
        self.message = message
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/recommender/', methods=['GET', 'POST'])
def recommender():
    content = request.get_json()
    if content is not None:
        doc = content.get('doc', {})
        docs = content.get('docs', [])
        if doc == {}:
            msg = 'The parameter `doc` is missing or empty'
            raise InvalidUsage(msg)
        if len(docs) == 0:
            msg = 'The parameter `docs` is missing or empty'
            raise InvalidUsage(msg)
        result = recommend(doc, docs)
        return jsonify(result)
    else:
        msg = 'You need to send the parameters: doc and docs'
        raise InvalidUsage(msg)


# Dutch Language Test
from seleniumbase.translate.dutch import Testgeval

class MijnTestklasse(Testgeval):

    def test_voorbeeld_1(self):
        self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
        self.controleren_element('a[title*="hoofdpagina gaan"]')
        self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
        self.typ("#searchInput", "Stroopwafel")
        self.klik("#searchButton")
        self.controleren_tekst("Stroopwafel", "#firstHeading")
        self.controleren_element('img[src*="Stroopwafels"]')
        self.typ("#searchInput", "Rijksmuseum Amsterdam")
        self.klik("#searchButton")
        self.controleren_tekst("Rijksmuseum", "#firstHeading")
        self.controleren_element('img[src*="Rijksmuseum"]')
        self.terug()
        self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
        self.vooruit()
        self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())

Update the Dutch example test

Update the Dutch example test

Response:
<REPLACE_OLD> self.controleren_element('img[alt="Stroopwafels"]')
 <REPLACE_NEW> self.controleren_element('img[src*="Stroopwafels"]')
 <REPLACE_END> <REPLACE_OLD> self.controleren_element('img[alt="Het Rijksmuseum"]')
 <REPLACE_NEW> self.controleren_element('img[src*="Rijksmuseum"]')
 <REPLACE_END> <|endoftext|> # Dutch Language Test
from seleniumbase.translate.dutch import Testgeval

class MijnTestklasse(Testgeval):

    def test_voorbeeld_1(self):
        self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
        self.controleren_element('a[title*="hoofdpagina gaan"]')
        self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
        self.typ("#searchInput", "Stroopwafel")
        self.klik("#searchButton")
        self.controleren_tekst("Stroopwafel", "#firstHeading")
        self.controleren_element('img[src*="Stroopwafels"]')
        self.typ("#searchInput", "Rijksmuseum Amsterdam")
        self.klik("#searchButton")
        self.controleren_tekst("Rijksmuseum", "#firstHeading")
        self.controleren_element('img[src*="Rijksmuseum"]')
        self.terug()
        self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
        self.vooruit()
        self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())

Prompt:
Update the Dutch example test

# Dutch Language Test
from seleniumbase.translate.dutch import Testgeval

class MijnTestklasse(Testgeval):

    def test_voorbeeld_1(self):
        self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
        self.controleren_element('a[title*="hoofdpagina gaan"]')
        self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
        self.typ("#searchInput", "Stroopwafel")
        self.klik("#searchButton")
        self.controleren_tekst("Stroopwafel", "#firstHeading")
        self.controleren_element('img[alt="Stroopwafels"]')
        self.typ("#searchInput", "Rijksmuseum Amsterdam")
        self.klik("#searchButton")
        self.controleren_tekst("Rijksmuseum", "#firstHeading")
        self.controleren_element('img[alt="Het Rijksmuseum"]')
        self.terug()
        self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
        self.vooruit()
        self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())


# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license.  See the LICENSE.txt file for details.
import sys  # pragma: no cover

from haas.main import main  # pragma: no cover

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

Response:
<REPLACE_OLD> .main <REPLACE_NEW> haas.main <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license.  See the LICENSE.txt file for details.
import sys  # pragma: no cover

from haas.main import main  # pragma: no cover

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

Prompt:
Use absolute import for main entry point.

# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license.  See the LICENSE.txt file for details.
import sys  # pragma: no cover

from .main import main  # pragma: no cover

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


from setuptools import setup

setup(
    name='cmsplugin-biography',
    version='0.0.1',
    packages=['cmsplugin_biography', 'cmsplugin_biography.migrations', ],
    install_requires=[
        'django-cms',
        'djangocms-text-ckeditor==1.0.9',
        'easy-thumbnails==1.2',
    ],
    author='Kevin Richardson',
    author_email='kevin@magically.us',
    description='A Django CMS plugin that manages and displays biographical information',
    long_description=open('README.rst').read(),
    license='MIT',
    url='http://github.com/kfr2/cmsplugin-biography',
    include_package_data=True,
    zip_safe=False
)

Mark package as not zip_safe

Response:
<REPLACE_OLD> include_package_data=True
)
 <REPLACE_NEW> include_package_data=True,
    zip_safe=False
)
 <REPLACE_END> <|endoftext|> from setuptools import setup

setup(
    name='cmsplugin-biography',
    version='0.0.1',
    packages=['cmsplugin_biography', 'cmsplugin_biography.migrations', ],
    install_requires=[
        'django-cms',
        'djangocms-text-ckeditor==1.0.9',
        'easy-thumbnails==1.2',
    ],
    author='Kevin Richardson',
    author_email='kevin@magically.us',
    description='A Django CMS plugin that manages and displays biographical information',
    long_description=open('README.rst').read(),
    license='MIT',
    url='http://github.com/kfr2/cmsplugin-biography',
    include_package_data=True,
    zip_safe=False
)

Prompt:
Mark package as not zip_safe

This package needs access to its templates to function. Thus, the
zip_safe flag has been set to False to tell setuptools to not
install the package's egg as a zip file.

See http://pythonhosted.org/distribute/setuptools.html#setting-the-zip-safe-flag
for further information.

from setuptools import setup

setup(
    name='cmsplugin-biography',
    version='0.0.1',
    packages=['cmsplugin_biography', 'cmsplugin_biography.migrations', ],
    install_requires=[
        'django-cms',
        'djangocms-text-ckeditor==1.0.9',
        'easy-thumbnails==1.2',
    ],
    author='Kevin Richardson',
    author_email='kevin@magically.us',
    description='A Django CMS plugin that manages and displays biographical information',
    long_description=open('README.rst').read(),
    license='MIT',
    url='http://github.com/kfr2/cmsplugin-biography',
    include_package_data=True
)


from setuptools import setup, Extension
import numpy as np
import os

extension_name = '_pyaccess'
extension_version = '.1'

include_dirs = [
    'ann_1.1.2/include',
    'sparsehash-2.0.2/src',
    np.get_include(),
    '.'
]
library_dirs = [
    'ann_1.1.2/lib',
    'contraction_hierarchies'
]
packages = ['pyaccess']
libraries = [ 'ANN', 'ch', 'gomp']
source_files = [
    'pyaccess/accessibility.cpp',
    'pyaccess/graphalg.cpp',
    'pyaccess/nearestneighbor.cpp',
    'pyaccess/pyaccesswrap.cpp'
]
extra_compile_args = [
    '-shared',
    '-DMACOSX',
    '-DLINUX',
    '-w',
    '-std=gnu++0x',
    '-O3',
    '-fopenmp',
    '-fpic',
    '-g',
    '-Wno-deprecated',
]
py_modules=['pyaccess/pyaccess', 'pyaccess/urbanaccess']

setup(
    packages=packages,
    py_modules=py_modules,
    name='pyaccess',
    version=extension_version,
    ext_modules=[
        Extension(
            extension_name,
            source_files,
            include_dirs=include_dirs,
            library_dirs=library_dirs,
            libraries=libraries,
            extra_compile_args=extra_compile_args
        )
    ]
)

Use pyaccess as the package name.

Use pyaccess as the package name.

Response:
<REPLACE_OLD> '-Wno-deprecated',
    # '-ferror-limit=1'
]
py_modules=['pyaccess/pyaccess', <REPLACE_NEW> '-Wno-deprecated',
]
py_modules=['pyaccess/pyaccess', <REPLACE_END> <REPLACE_OLD> name=extension_name,
 <REPLACE_NEW> name='pyaccess',
 <REPLACE_END> <|endoftext|> from setuptools import setup, Extension
import numpy as np
import os

extension_name = '_pyaccess'
extension_version = '.1'

include_dirs = [
    'ann_1.1.2/include',
    'sparsehash-2.0.2/src',
    np.get_include(),
    '.'
]
library_dirs = [
    'ann_1.1.2/lib',
    'contraction_hierarchies'
]
packages = ['pyaccess']
libraries = [ 'ANN', 'ch', 'gomp']
source_files = [
    'pyaccess/accessibility.cpp',
    'pyaccess/graphalg.cpp',
    'pyaccess/nearestneighbor.cpp',
    'pyaccess/pyaccesswrap.cpp'
]
extra_compile_args = [
    '-shared',
    '-DMACOSX',
    '-DLINUX',
    '-w',
    '-std=gnu++0x',
    '-O3',
    '-fopenmp',
    '-fpic',
    '-g',
    '-Wno-deprecated',
]
py_modules=['pyaccess/pyaccess', 'pyaccess/urbanaccess']

setup(
    packages=packages,
    py_modules=py_modules,
    name='pyaccess',
    version=extension_version,
    ext_modules=[
        Extension(
            extension_name,
            source_files,
            include_dirs=include_dirs,
            library_dirs=library_dirs,
            libraries=libraries,
            extra_compile_args=extra_compile_args
        )
    ]
)

Prompt:
Use pyaccess as the package name.

from setuptools import setup, Extension
import numpy as np
import os

extension_name = '_pyaccess'
extension_version = '.1'

include_dirs = [
    'ann_1.1.2/include',
    'sparsehash-2.0.2/src',
    np.get_include(),
    '.'
]
library_dirs = [
    'ann_1.1.2/lib',
    'contraction_hierarchies'
]
packages = ['pyaccess']
libraries = [ 'ANN', 'ch', 'gomp']
source_files = [
    'pyaccess/accessibility.cpp',
    'pyaccess/graphalg.cpp',
    'pyaccess/nearestneighbor.cpp',
    'pyaccess/pyaccesswrap.cpp'
]
extra_compile_args = [
    '-shared',
    '-DMACOSX',
    '-DLINUX',
    '-w',
    '-std=gnu++0x',
    '-O3',
    '-fopenmp',
    '-fpic',
    '-g',
    '-Wno-deprecated',
    # '-ferror-limit=1'
]
py_modules=['pyaccess/pyaccess', 'pyaccess/urbanaccess']

setup(
    packages=packages,
    py_modules=py_modules,
    name=extension_name,
    version=extension_version,
    ext_modules=[
        Extension(
            extension_name,
            source_files,
            include_dirs=include_dirs,
            library_dirs=library_dirs,
            libraries=libraries,
            extra_compile_args=extra_compile_args
        )
    ]
)


#!/usr/bin/env python
"""Distutils installer for extras."""

from setuptools import setup
import os.path

import extras
testtools_cmd = extras.try_import('testtools.TestCommand')

def get_version():
    """Return the version of extras that we are building."""
    version = '.'.join(
        str(component) for component in extras.__version__[0:3])
    return version

def get_long_description():
    readme_path = os.path.join(
        os.path.dirname(__file__), 'README.rst')
    return open(readme_path).read()

cmdclass = {}

if testtools_cmd is not None:
    cmdclass['test'] = testtools_cmd

setup(name='extras',
      author='Testing cabal',
      author_email='testtools-dev@lists.launchpad.net',
      url='https://github.com/testing-cabal/extras',
      description=('Useful extra bits for Python - things that shold be '
        'in the standard library'),
      long_description=get_long_description(),
      version=get_version(),
      classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        ],
      packages=[
        'extras',
        'extras.tests',
        ],
      cmdclass=cmdclass)

Response:
<REPLACE_OLD> classifiers=["License <REPLACE_NEW> classifiers=[
        "Intended Audience :: Developers",
        "License <REPLACE_END> <REPLACE_OLD> License"],
 <REPLACE_NEW> License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        ],
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""Distutils installer for extras."""

from setuptools import setup
import os.path

import extras
testtools_cmd = extras.try_import('testtools.TestCommand')

def get_version():
    """Return the version of extras that we are building."""
    version = '.'.join(
        str(component) for component in extras.__version__[0:3])
    return version

def get_long_description():
    readme_path = os.path.join(
        os.path.dirname(__file__), 'README.rst')
    return open(readme_path).read()

cmdclass = {}

if testtools_cmd is not None:
    cmdclass['test'] = testtools_cmd

setup(name='extras',
      author='Testing cabal',
      author_email='testtools-dev@lists.launchpad.net',
      url='https://github.com/testing-cabal/extras',
      description=('Useful extra bits for Python - things that shold be '
        'in the standard library'),
      long_description=get_long_description(),
      version=get_version(),
      classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        ],
      packages=[
        'extras',
        'extras.tests',
        ],
      cmdclass=cmdclass)

Prompt:
Add trove classifiers specifying Python 3 support.

#!/usr/bin/env python
"""Distutils installer for extras."""

from setuptools import setup
import os.path

import extras
testtools_cmd = extras.try_import('testtools.TestCommand')

def get_version():
    """Return the version of extras that we are building."""
    version = '.'.join(
        str(component) for component in extras.__version__[0:3])
    return version

def get_long_description():
    readme_path = os.path.join(
        os.path.dirname(__file__), 'README.rst')
    return open(readme_path).read()

cmdclass = {}

if testtools_cmd is not None:
    cmdclass['test'] = testtools_cmd

setup(name='extras',
      author='Testing cabal',
      author_email='testtools-dev@lists.launchpad.net',
      url='https://github.com/testing-cabal/extras',
      description=('Useful extra bits for Python - things that shold be '
        'in the standard library'),
      long_description=get_long_description(),
      version=get_version(),
      classifiers=["License :: OSI Approved :: MIT License"],
      packages=[
        'extras',
        'extras.tests',
        ],
      cmdclass=cmdclass)


import sys

class SempaiLoader(object):
    def __init__(self, *args):
        print args

    def find_module(self, fullname, path=None):
        print 'finding', fullname, path
        if fullname == 'simple':
            return self
        return None

sys.path_hooks.append(SempaiLoader)
sys.path.insert(0, 'simple')

Add very simple module finder

Add very simple module finder

Response:
<INSERT> import sys

class SempaiLoader(object):
 <INSERT_END> <INSERT>   def __init__(self, *args):
        print args

    def find_module(self, fullname, path=None):
        print 'finding', fullname, path
        if fullname == 'simple':
            return self
        return None

sys.path_hooks.append(SempaiLoader)
sys.path.insert(0, 'simple')
 <INSERT_END> <|endoftext|> import sys

class SempaiLoader(object):
    def __init__(self, *args):
        print args

    def find_module(self, fullname, path=None):
        print 'finding', fullname, path
        if fullname == 'simple':
            return self
        return None

sys.path_hooks.append(SempaiLoader)
sys.path.insert(0, 'simple')

Prompt: Add very simple module finder


# Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# 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 setuptools
import ryu.hooks

ryu.hooks.save_orig()
setuptools.setup(name='ryu',
                 setup_requires=['pbr'],
                 pbr=True)

Response:
<REPLACE_OLD> License.

# a bug workaround.  http://bugs.python.org/issue15881
try:
    import multiprocessing
except ImportError:
    pass

import <REPLACE_NEW> License.

import <REPLACE_END> <|endoftext|> # Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# 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 setuptools
import ryu.hooks

ryu.hooks.save_orig()
setuptools.setup(name='ryu',
                 setup_requires=['pbr'],
                 pbr=True)

Prompt:
Remove workaround for issue with older python versions.

# Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# 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.

# a bug workaround.  http://bugs.python.org/issue15881
try:
    import multiprocessing
except ImportError:
    pass

import setuptools
import ryu.hooks

ryu.hooks.save_orig()
setuptools.setup(name='ryu',
                 setup_requires=['pbr'],
                 pbr=True)


from setuptools import setup, find_packages

setup(
    name='gdcdatamodel',
    packages=find_packages(),
    install_requires=[
        'pytz==2016.4',
        'graphviz==0.4.2',
        'jsonschema==2.5.1',
        'psqlgraph',
        'gdcdictionary',
        'cdisutils',
        'python-dateutil==2.4.2',
    ],
    package_data={
        "gdcdatamodel": [
            "xml_mappings/*.yaml",
        ]
    },
    dependency_links=[
        'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
        'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
        'git+https://github.com/NCI-GDC/gdcdictionary.git@1.12.1-final#egg=gdcdictionary',
    ],
    entry_points={
        'console_scripts': [
            'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
        ]
    },
)

Response:
<REPLACE_OLD> 'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
 <REPLACE_NEW> 'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
 <REPLACE_END> <REPLACE_OLD> 'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
 <REPLACE_NEW> 'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
 <REPLACE_END> <REPLACE_OLD> 'git+https://github.com/NCI-GDC/gdcdictionary.git@1.12#egg=gdcdictionary',
 <REPLACE_NEW> 'git+https://github.com/NCI-GDC/gdcdictionary.git@1.12.1-final#egg=gdcdictionary',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='gdcdatamodel',
    packages=find_packages(),
    install_requires=[
        'pytz==2016.4',
        'graphviz==0.4.2',
        'jsonschema==2.5.1',
        'psqlgraph',
        'gdcdictionary',
        'cdisutils',
        'python-dateutil==2.4.2',
    ],
    package_data={
        "gdcdatamodel": [
            "xml_mappings/*.yaml",
        ]
    },
    dependency_links=[
        'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
        'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
        'git+https://github.com/NCI-GDC/gdcdictionary.git@1.12.1-final#egg=gdcdictionary',
    ],
    entry_points={
        'console_scripts': [
            'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
        ]
    },
)

Prompt:
chore(pins): Update pins to match horton dictionary/api

- Update pins to match horton dictionary/api

from setuptools import setup, find_packages

setup(
    name='gdcdatamodel',
    packages=find_packages(),
    install_requires=[
        'pytz==2016.4',
        'graphviz==0.4.2',
        'jsonschema==2.5.1',
        'psqlgraph',
        'gdcdictionary',
        'cdisutils',
        'python-dateutil==2.4.2',
    ],
    package_data={
        "gdcdatamodel": [
            "xml_mappings/*.yaml",
        ]
    },
    dependency_links=[
        'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
        'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
        'git+https://github.com/NCI-GDC/gdcdictionary.git@1.12#egg=gdcdictionary',
    ],
    entry_points={
        'console_scripts': [
            'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
        ]
    },
)


Fix DeprecationWarning in Django 1.5

Fix DeprecationWarning in Django 1.5

Response:
<DELETE> try:
    from django.conf.urls.defaults import patterns, url
except ImportError:
    <DELETE_END> <|endoftext|> from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
        name="nesting_server_data"),
)

Prompt:
Fix DeprecationWarning in Django 1.5

try:
    from django.conf.urls.defaults import patterns, url
except ImportError:
    from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
        name="nesting_server_data"),
)


# python fenix_download login_file <url> -e <file_extension> (DEFAULT = pdf) -d <download_directory>
#
#

from fenix import Fenix
import argparse

if __name__ == '__main__':
    # TODO: argparse
    parser = argparse.ArgumentParser(description='Download files from Fenix Edu pages')
    parser.add_argument('login', type=str, help='path to fenix login credentials file (check login.json for format)')
    parser.add_argument('url', type=str, help='url from where to download the files from')
    parser.add('-e', '--extension', type=str, default='pdf', help='file extensions to download, without the leading "." (* for all, default is "pdf")')
    parser.add('-d', '--directory', type=str, default='download', help='download directory')

Add inital structure for fenix downloader

Response:
<INSERT> # python fenix_download login_file <url> -e <file_extension> (DEFAULT = pdf) -d <download_directory>
#
#

from fenix import Fenix
import argparse

if __name__ == '__main__':
 <INSERT_END> <INSERT>   # TODO: argparse
    parser = argparse.ArgumentParser(description='Download files from Fenix Edu pages')
    parser.add_argument('login', type=str, help='path to fenix login credentials file (check login.json for format)')
    parser.add_argument('url', type=str, help='url from where to download the files from')
    parser.add('-e', '--extension', type=str, default='pdf', help='file extensions to download, without the leading "." (* for all, default is "pdf")')
    parser.add('-d', '--directory', type=str, default='download', help='download directory') <INSERT_END> <|endoftext|> # python fenix_download login_file <url> -e <file_extension> (DEFAULT = pdf) -d <download_directory>
#
#

from fenix import Fenix
import argparse

if __name__ == '__main__':
    # TODO: argparse
    parser = argparse.ArgumentParser(description='Download files from Fenix Edu pages')
    parser.add_argument('login', type=str, help='path to fenix login credentials file (check login.json for format)')
    parser.add_argument('url', type=str, help='url from where to download the files from')
    parser.add('-e', '--extension', type=str, default='pdf', help='file extensions to download, without the leading "." (* for all, default is "pdf")')
    parser.add('-d', '--directory', type=str, default='download', help='download directory')

Prompt: Add inital structure for fenix downloader


"""
WSGI config for suorganizer project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "suorganizer.settings")

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Use WhiteNoise for static content.

Response:
<REPLACE_OLD> get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", <REPLACE_NEW> get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", <REPLACE_END> <REPLACE_OLD> get_wsgi_application()
 <REPLACE_NEW> get_wsgi_application()
application = DjangoWhiteNoise(application)
 <REPLACE_END> <|endoftext|> """
WSGI config for suorganizer project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "suorganizer.settings")

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Prompt:
Ch29: Use WhiteNoise for static content.

"""
WSGI config for suorganizer project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "suorganizer.settings")

application = get_wsgi_application()


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

'''
Checks notebook execution result.
Equal to this command + error management:
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output executed_notebook.ipynb demo.ipynb

For jupyter configuration information, run: jupyter --path
'''

# Dependencies: nbformat, nbconvert, jupyter-client, ipykernel
import io
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors import CellExecutionError

notebook_filename = 'demo.ipynb'
run_path = '.'
notebook_filename_out = 'executed_notebook.ipynb'

with io.open(notebook_filename) as f:
    nb = nbformat.read(f, as_version=4)

ep = ExecutePreprocessor(timeout=600, kernel_name='python')
try:
    out = ep.preprocess(nb, {'metadata': {'path': run_path}})
except CellExecutionError:
    out = None
    msg = 'Error executing the notebook "%s".\n\n' % notebook_filename
    msg += 'See notebook "%s" for the traceback.' % notebook_filename_out
    print(msg)
    raise
finally:
    with io.open(notebook_filename_out, mode='wt') as f:  # io.open avoids UnicodeEncodeError
        nbformat.write(nb, f)

Add script to automate notebooks testing

Response:
<INSERT> # -*- coding: utf-8 -*-

'''
Checks notebook execution result.
Equal to this command + error management:
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output executed_notebook.ipynb demo.ipynb

For jupyter configuration information, run: jupyter --path
'''

# Dependencies: nbformat, nbconvert, jupyter-client, ipykernel
import io
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors import CellExecutionError

notebook_filename = 'demo.ipynb'
run_path = '.'
notebook_filename_out = 'executed_notebook.ipynb'

with io.open(notebook_filename) as f:
 <INSERT_END> <INSERT>   nb = nbformat.read(f, as_version=4)

ep = ExecutePreprocessor(timeout=600, kernel_name='python')
try:
    out = ep.preprocess(nb, {'metadata': {'path': run_path}})
except CellExecutionError:
    out = None
    msg = 'Error executing the notebook "%s".\n\n' % notebook_filename
    msg += 'See notebook "%s" for the traceback.' % notebook_filename_out
    print(msg)
    raise
finally:
    with io.open(notebook_filename_out, mode='wt') as f:  # io.open avoids UnicodeEncodeError
        nbformat.write(nb, f)
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

'''
Checks notebook execution result.
Equal to this command + error management:
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output executed_notebook.ipynb demo.ipynb

For jupyter configuration information, run: jupyter --path
'''

# Dependencies: nbformat, nbconvert, jupyter-client, ipykernel
import io
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors import CellExecutionError

notebook_filename = 'demo.ipynb'
run_path = '.'
notebook_filename_out = 'executed_notebook.ipynb'

with io.open(notebook_filename) as f:
    nb = nbformat.read(f, as_version=4)

ep = ExecutePreprocessor(timeout=600, kernel_name='python')
try:
    out = ep.preprocess(nb, {'metadata': {'path': run_path}})
except CellExecutionError:
    out = None
    msg = 'Error executing the notebook "%s".\n\n' % notebook_filename
    msg += 'See notebook "%s" for the traceback.' % notebook_filename_out
    print(msg)
    raise
finally:
    with io.open(notebook_filename_out, mode='wt') as f:  # io.open avoids UnicodeEncodeError
        nbformat.write(nb, f)

Prompt: Add script to automate notebooks testing


#!/usr/bin/env python3
def shift(string, key, decipher=False):
    return ''.join(
        chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
            % 26+1) for c in string)

if __name__ == '__main__':
    assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
    assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
    assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)

Response:
<REPLACE_OLD> chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
 <REPLACE_NEW> chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
 <REPLACE_END> <REPLACE_OLD> if c.isalpha() else c <REPLACE_NEW>     % 26+1) <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
def shift(string, key, decipher=False):
    return ''.join(
        chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
            % 26+1) for c in string)

if __name__ == '__main__':
    assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
    assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
    assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)

Prompt:
Use bitwise operators on ordinals to reduce code size

The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.

#!/usr/bin/env python3
def shift(string, key, decipher=False):
    return ''.join(
        chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
        if c.isalpha() else c for c in string)

if __name__ == '__main__':
    assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
    assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
    assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)


# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys

from twisted.internet import reactor

from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
    parser.add_argument('-c', '--config',
                        help='the config file to read from',
                        type=str, required=True)
    parser.add_argument('-l', '--loglevel',
                        help='the logging level (default INFO)',
                        type=str, default='INFO')
    cmdArgs = parser.parse_args()

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    # Set up logging for stdout on the root 'desertbot' logger
    # Modules can then just add more handlers to the root logger to capture all logs to files in various ways
    rootLogger = logging.getLogger('desertbot')
    numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None)
    if isinstance(numericLevel, int):
        rootLogger.setLevel(numericLevel)
    else:
        raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel))

    logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')

    streamHandler = logging.StreamHandler(stream=sys.stdout)
    streamHandler.setFormatter(logFormatter)

    rootLogger.addHandler(streamHandler)

    config = Config(cmdArgs.config)
    try:
        config.loadConfig()
    except ConfigError:
        rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
    else:
        factory = DesertBotFactory(config)
        reactor.run()

Make the logging level configurable

Make the logging level configurable

Response:
<INSERT> parser.add_argument('-l', '--loglevel',
                        help='the logging level (default INFO)',
                        type=str, default='INFO')
    <INSERT_END> <REPLACE_OLD> rootLogger.setLevel(logging.INFO)  # TODO change this from config value once it's loaded

 <REPLACE_NEW> numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None)
    if isinstance(numericLevel, int):
        rootLogger.setLevel(numericLevel)
    else:
        raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel))

 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys

from twisted.internet import reactor

from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
    parser.add_argument('-c', '--config',
                        help='the config file to read from',
                        type=str, required=True)
    parser.add_argument('-l', '--loglevel',
                        help='the logging level (default INFO)',
                        type=str, default='INFO')
    cmdArgs = parser.parse_args()

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    # Set up logging for stdout on the root 'desertbot' logger
    # Modules can then just add more handlers to the root logger to capture all logs to files in various ways
    rootLogger = logging.getLogger('desertbot')
    numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None)
    if isinstance(numericLevel, int):
        rootLogger.setLevel(numericLevel)
    else:
        raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel))

    logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')

    streamHandler = logging.StreamHandler(stream=sys.stdout)
    streamHandler.setFormatter(logFormatter)

    rootLogger.addHandler(streamHandler)

    config = Config(cmdArgs.config)
    try:
        config.loadConfig()
    except ConfigError:
        rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
    else:
        factory = DesertBotFactory(config)
        reactor.run()

Prompt:
Make the logging level configurable

# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys

from twisted.internet import reactor

from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
    parser.add_argument('-c', '--config',
                        help='the config file to read from',
                        type=str, required=True)
    cmdArgs = parser.parse_args()

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    # Set up logging for stdout on the root 'desertbot' logger
    # Modules can then just add more handlers to the root logger to capture all logs to files in various ways
    rootLogger = logging.getLogger('desertbot')
    rootLogger.setLevel(logging.INFO)  # TODO change this from config value once it's loaded

    logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')

    streamHandler = logging.StreamHandler(stream=sys.stdout)
    streamHandler.setFormatter(logFormatter)

    rootLogger.addHandler(streamHandler)

    config = Config(cmdArgs.config)
    try:
        config.loadConfig()
    except ConfigError:
        rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
    else:
        factory = DesertBotFactory(config)
        reactor.run()


import csv
from django.http import HttpResponse
from servicerating.models import Response

def report_responses(request):

    qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact_id = servicerating_extra.contact_id WHERE servicerating_extra.key = 'clinic_code'")

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="servicerating_incl_clinic_code.csv"'

    writer = csv.writer(response)

    writer.writerow(["Rating ID", "Contact ID", "Key", "Value", "Created At", "Updated At", "Clinic Code"])
    for obj in qs:
        writer.writerow([obj.id, obj.contact_id, obj.key, obj.value, obj.created_at,
                        obj.updated_at, obj.clinic_code])

    return response

Response:
<REPLACE_OLD> writer.writerow(["Contact", <REPLACE_NEW> writer.writerow(["Rating ID", "Contact ID", <REPLACE_END> <REPLACE_OLD> writer.writerow([obj.contact, <REPLACE_NEW> writer.writerow([obj.id, obj.contact_id, <REPLACE_END> <|endoftext|> import csv
from django.http import HttpResponse
from servicerating.models import Response

def report_responses(request):

    qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact_id = servicerating_extra.contact_id WHERE servicerating_extra.key = 'clinic_code'")

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="servicerating_incl_clinic_code.csv"'

    writer = csv.writer(response)

    writer.writerow(["Rating ID", "Contact ID", "Key", "Value", "Created At", "Updated At", "Clinic Code"])
    for obj in qs:
        writer.writerow([obj.id, obj.contact_id, obj.key, obj.value, obj.created_at,
                        obj.updated_at, obj.clinic_code])

    return response

Prompt:
Remove FK's from CSV export for massive speed boost

import csv
from django.http import HttpResponse
from servicerating.models import Response

def report_responses(request):

    qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact_id = servicerating_extra.contact_id WHERE servicerating_extra.key = 'clinic_code'")

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="servicerating_incl_clinic_code.csv"'

    writer = csv.writer(response)

    writer.writerow(["Contact", "Key", "Value", "Created At", "Updated At", "Clinic Code"])
    for obj in qs:
        writer.writerow([obj.contact, obj.key, obj.value, obj.created_at,
                        obj.updated_at, obj.clinic_code])

    return response


import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet

from utilities.logger import logger

class AlertPluginSet(PluginSet):

    def send_message_to_plugin(self, plugin_class, message, metadata=None):
        if 'utctimestamp' in message and 'summary' in message:
            message_log_str = u'{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
            logger.info(message_log_str)

        return plugin_class.onMessage(message), metadata

Response:
<REPLACE_OLD> '{0} <REPLACE_NEW> u'{0} <REPLACE_END> <|endoftext|> import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet

from utilities.logger import logger

class AlertPluginSet(PluginSet):

    def send_message_to_plugin(self, plugin_class, message, metadata=None):
        if 'utctimestamp' in message and 'summary' in message:
            message_log_str = u'{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
            logger.info(message_log_str)

        return plugin_class.onMessage(message), metadata

Prompt:
Convert debug message into unicode string

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet

from utilities.logger import logger

class AlertPluginSet(PluginSet):

    def send_message_to_plugin(self, plugin_class, message, metadata=None):
        if 'utctimestamp' in message and 'summary' in message:
            message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
            logger.info(message_log_str)

        return plugin_class.onMessage(message), metadata


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

def merge_sort(lyst):
    buf = [None for x in range(len(lyst))]
    _merge_sort(lyst, buf, 0, len(lyst)-1)

def _merge_sort(lyst, buf, low, high):
    if low < high:
        middle = (low + high) // 2
        _merge_sort(lyst, buf, low, middle)
        _merge_sort(lyst, buf, middle+1, high)
        merge(lyst, buf, low, middle, high)

def merge(lyst, buf, low, middle, high):
    i1 = low
    i2 = middle + 1

    for i in range(low, high+1):
        if i1 > middle:
            buf[i] = lyst[i2]
            i2 += 1
        elif i2 > high:
            buf[i] = lyst[i1]
            i1 += 1
        elif lyst[i1] < lyst[i2]:
            buf[i] = lyst[i]
            i1 += 1
        else:
            buf[i] = lyst[i2]
            i2 += 1
    for i in range(low, high+1):
        lyst[i] = buf[i]

Response:
<REPLACE_OLD> [len(lyst)]
 <REPLACE_NEW> [None for x in range(len(lyst))]
 <REPLACE_END> <REPLACE_OLD> high):
 <REPLACE_NEW> high+1):
 <REPLACE_END> <REPLACE_OLD> high):
 <REPLACE_NEW> high+1):
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: UTF-8 -*-

def merge_sort(lyst):
    buf = [None for x in range(len(lyst))]
    _merge_sort(lyst, buf, 0, len(lyst)-1)

def _merge_sort(lyst, buf, low, high):
    if low < high:
        middle = (low + high) // 2
        _merge_sort(lyst, buf, low, middle)
        _merge_sort(lyst, buf, middle+1, high)
        merge(lyst, buf, low, middle, high)

def merge(lyst, buf, low, middle, high):
    i1 = low
    i2 = middle + 1

    for i in range(low, high+1):
        if i1 > middle:
            buf[i] = lyst[i2]
            i2 += 1
        elif i2 > high:
            buf[i] = lyst[i1]
            i1 += 1
        elif lyst[i1] < lyst[i2]:
            buf[i] = lyst[i]
            i1 += 1
        else:
            buf[i] = lyst[i2]
            i2 += 1
    for i in range(low, high+1):
        lyst[i] = buf[i]

Prompt:
Fix initial buf variable to act as an array

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

def merge_sort(lyst):
    buf = [len(lyst)]
    _merge_sort(lyst, buf, 0, len(lyst)-1)

def _merge_sort(lyst, buf, low, high):
    if low < high:
        middle = (low + high) // 2
        _merge_sort(lyst, buf, low, middle)
        _merge_sort(lyst, buf, middle+1, high)
        merge(lyst, buf, low, middle, high)

def merge(lyst, buf, low, middle, high):
    i1 = low
    i2 = middle + 1

    for i in range(low, high):
        if i1 > middle:
            buf[i] = lyst[i2]
            i2 += 1
        elif i2 > high:
            buf[i] = lyst[i1]
            i1 += 1
        elif lyst[i1] < lyst[i2]:
            buf[i] = lyst[i]
            i1 += 1
        else:
            buf[i] = lyst[i2]
            i2 += 1
    for i in range(low, high):
        lyst[i] = buf[i]


import tornado.testing

from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session

class BaseTest(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        return NodeWebAPI()

    def get_http_port(self):
        return 8000

    def setUp(self):
        super(BaseTest, self).setUp()
        setup_all()
        create_all()

    def tearDown(self):
        super(BaseTest, self).tearDown()
        session.rollback()
        drop_all()

Response:
<REPLACE_OLD> #drop_all()
 <REPLACE_NEW> drop_all()
 <REPLACE_END> <|endoftext|> import tornado.testing

from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session

class BaseTest(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        return NodeWebAPI()

    def get_http_port(self):
        return 8000

    def setUp(self):
        super(BaseTest, self).setUp()
        setup_all()
        create_all()

    def tearDown(self):
        super(BaseTest, self).tearDown()
        session.rollback()
        drop_all()

Prompt:
Drop all tables after tests - looks like we're back in business.

import tornado.testing

from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session

class BaseTest(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        return NodeWebAPI()

    def get_http_port(self):
        return 8000

    def setUp(self):
        super(BaseTest, self).setUp()
        setup_all()
        create_all()

    def tearDown(self):
        super(BaseTest, self).tearDown()
        session.rollback()
        #drop_all()