import tensorflow as tf

def add_output_images(images, logits, labels):
    cast_labels = tf.cast(labels, tf.uint8) * 128
    cast_labels = cast_labels[...,None]
    tf.summary.image('input_labels', cast_labels, max_outputs=3)

    classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
    output_image_gb = images[...,0]
    output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
    output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
    tf.summary.image('output_mixed', output_image, max_outputs=3)

    output_image_binary = tf.argmax(logits, 3)
    output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
    tf.summary.image('output_labels', output_image_binary, max_outputs=3)

    output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
    output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
    tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)

    return

Response:
<INSERT> output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
    output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
    tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)

    <INSERT_END> <|endoftext|> import tensorflow as tf

def add_output_images(images, logits, labels):
    cast_labels = tf.cast(labels, tf.uint8) * 128
    cast_labels = cast_labels[...,None]
    tf.summary.image('input_labels', cast_labels, max_outputs=3)

    classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
    output_image_gb = images[...,0]
    output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
    output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
    tf.summary.image('output_mixed', output_image, max_outputs=3)

    output_image_binary = tf.argmax(logits, 3)
    output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
    tf.summary.image('output_labels', output_image_binary, max_outputs=3)

    output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
    output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
    tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)

    return

Prompt:
Add output with images mixed with binary version of output labels

import tensorflow as tf

def add_output_images(images, logits, labels):
    cast_labels = tf.cast(labels, tf.uint8) * 128
    cast_labels = cast_labels[...,None]
    tf.summary.image('input_labels', cast_labels, max_outputs=3)

    classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
    output_image_gb = images[...,0]
    output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
    output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
    tf.summary.image('output_mixed', output_image, max_outputs=3)

    output_image_binary = tf.argmax(logits, 3)
    output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
    tf.summary.image('output_labels', output_image_binary, max_outputs=3)

    return


import redis
import re
from common import get_db
from datetime import datetime

MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'

def listen(args):

  global MSGPATTERN

  rserver = redis.Redis('localhost')
  pubsub = rserver.pubsub()
  pubsub.subscribe(CHANNEL)

  db = get_db(args.mongohost)

  for packet in pubsub.listen():
    try:
      if packet['type'] != 'message': continue
      match = MSGPATTERN.match(packet['data'])
      component = match.group(1)
      level = int(match.group(2))
      message = match.group(3)
      db.insert(dict(
        tstamp=datetime.utcnow(),comp=component,lvl=level,msg=message))
    except Exception, e:
      print e, packet

Response:
<REPLACE_OLD> tstamp=datetime.now(),comp=component,lvl=level,msg=message))
 <REPLACE_NEW> tstamp=datetime.utcnow(),comp=component,lvl=level,msg=message))
 <REPLACE_END> <|endoftext|>
import redis
import re
from common import get_db
from datetime import datetime

MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'

def listen(args):

  global MSGPATTERN

  rserver = redis.Redis('localhost')
  pubsub = rserver.pubsub()
  pubsub.subscribe(CHANNEL)

  db = get_db(args.mongohost)

  for packet in pubsub.listen():
    try:
      if packet['type'] != 'message': continue
      match = MSGPATTERN.match(packet['data'])
      component = match.group(1)
      level = int(match.group(2))
      message = match.group(3)
      db.insert(dict(
        tstamp=datetime.utcnow(),comp=component,lvl=level,msg=message))
    except Exception, e:
      print e, packet

Prompt:
Make sure timestamp of log message is UTC when it goes into DB

import redis
import re
from common import get_db
from datetime import datetime

MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'

def listen(args):

  global MSGPATTERN

  rserver = redis.Redis('localhost')
  pubsub = rserver.pubsub()
  pubsub.subscribe(CHANNEL)

  db = get_db(args.mongohost)

  for packet in pubsub.listen():
    try:
      if packet['type'] != 'message': continue
      match = MSGPATTERN.match(packet['data'])
      component = match.group(1)
      level = int(match.group(2))
      message = match.group(3)
      db.insert(dict(
        tstamp=datetime.now(),comp=component,lvl=level,msg=message))
    except Exception, e:
      print e, packet


import tempfile
from numpy.testing import assert_allclose
from os import path
from distarray.local import LocalArray, save, load, save_hdf5
from distarray.testing import comm_null_passes, MpiTestCase

class TestFlatFileIO(MpiTestCase):

    @comm_null_passes
    def test_flat_file_read_write(self):
        larr0 = LocalArray((7,), comm=self.comm)
        output_dir = tempfile.gettempdir()
        filename = 'outfile'
        output_path = path.join(output_dir, filename)
        save(output_path, larr0)
        larr1 = load(output_path, comm=self.comm)
        self.assertTrue(isinstance(larr1, LocalArray))
        assert_allclose(larr0, larr1)

class TestHDF5FileIO(MpiTestCase):

    @comm_null_passes
    def test_hdf5_file_write(self):
        import h5py

        dataset = "data"
        larr0 = LocalArray((51,), comm=self.comm)
        output_dir = tempfile.gettempdir()
        filename = 'outfile'
        output_path = path.join(output_dir, filename)
        save_hdf5(output_path, larr0, dataset=dataset)

        self.assertTrue(path.exists(output_path))
        fp = h5py.File(output_path, 'r')
        self.assertTrue("data" in fp)

        fp.close()

Move h5py import into HDF test.

Move h5py import into HDF test.

Response:
<REPLACE_OLD> tempfile
import h5py
from <REPLACE_NEW> tempfile
from <REPLACE_END> <INSERT> import h5py

        <INSERT_END> <|endoftext|> import tempfile
from numpy.testing import assert_allclose
from os import path
from distarray.local import LocalArray, save, load, save_hdf5
from distarray.testing import comm_null_passes, MpiTestCase

class TestFlatFileIO(MpiTestCase):

    @comm_null_passes
    def test_flat_file_read_write(self):
        larr0 = LocalArray((7,), comm=self.comm)
        output_dir = tempfile.gettempdir()
        filename = 'outfile'
        output_path = path.join(output_dir, filename)
        save(output_path, larr0)
        larr1 = load(output_path, comm=self.comm)
        self.assertTrue(isinstance(larr1, LocalArray))
        assert_allclose(larr0, larr1)

class TestHDF5FileIO(MpiTestCase):

    @comm_null_passes
    def test_hdf5_file_write(self):
        import h5py

        dataset = "data"
        larr0 = LocalArray((51,), comm=self.comm)
        output_dir = tempfile.gettempdir()
        filename = 'outfile'
        output_path = path.join(output_dir, filename)
        save_hdf5(output_path, larr0, dataset=dataset)

        self.assertTrue(path.exists(output_path))
        fp = h5py.File(output_path, 'r')
        self.assertTrue("data" in fp)

        fp.close()

Prompt:
Move h5py import into HDF test.
import tempfile
import h5py
from numpy.testing import assert_allclose
from os import path
from distarray.local import LocalArray, save, load, save_hdf5
from distarray.testing import comm_null_passes, MpiTestCase

class TestFlatFileIO(MpiTestCase):

    @comm_null_passes
    def test_flat_file_read_write(self):
        larr0 = LocalArray((7,), comm=self.comm)
        output_dir = tempfile.gettempdir()
        filename = 'outfile'
        output_path = path.join(output_dir, filename)
        save(output_path, larr0)
        larr1 = load(output_path, comm=self.comm)
        self.assertTrue(isinstance(larr1, LocalArray))
        assert_allclose(larr0, larr1)

class TestHDF5FileIO(MpiTestCase):

    @comm_null_passes
    def test_hdf5_file_write(self):
        dataset = "data"
        larr0 = LocalArray((51,), comm=self.comm)
        output_dir = tempfile.gettempdir()
        filename = 'outfile'
        output_path = path.join(output_dir, filename)
        save_hdf5(output_path, larr0, dataset=dataset)

        self.assertTrue(path.exists(output_path))
        fp = h5py.File(output_path, 'r')
        self.assertTrue("data" in fp)

        fp.close()


#
#    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.

from heat.engine.resources.openstack.nova import server

class ServerUpdateAllowed(server.Server):
    '''Prevent any properties changes from replacing an existing server.

    '''

    update_allowed_properties = server.Server.properties_schema.keys()

    def needs_replace_with_prop_diff(self, changed_properties_set,
                                     after_props, before_props):
        return False

def resource_mapping():
    return {'OS::Nova::Server': ServerUpdateAllowed}

Response:
<REPLACE_OLD> server.Server.properties_schema.keys()

def <REPLACE_NEW> server.Server.properties_schema.keys()

    def needs_replace_with_prop_diff(self, changed_properties_set,
                                     after_props, before_props):
        return False

def <REPLACE_END> <|endoftext|> #
#    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.

from heat.engine.resources.openstack.nova import server

class ServerUpdateAllowed(server.Server):
    '''Prevent any properties changes from replacing an existing server.

    '''

    update_allowed_properties = server.Server.properties_schema.keys()

    def needs_replace_with_prop_diff(self, changed_properties_set,
                                     after_props, before_props):
        return False

def resource_mapping():
    return {'OS::Nova::Server': ServerUpdateAllowed}

Prompt:
Fix no-replace-server to accurately preview update

This override of OS::Nova::Server needs to reflect the fact
that it never replaces on update or the update --dry-run output
ends up being wrong.

Closes-Bug: 1561076
Change-Id: I9256872b877fbe7f91befb52995c62de006210ef

#
#    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.

from heat.engine.resources.openstack.nova import server

class ServerUpdateAllowed(server.Server):
    '''Prevent any properties changes from replacing an existing server.

    '''

    update_allowed_properties = server.Server.properties_schema.keys()

def resource_mapping():
    return {'OS::Nova::Server': ServerUpdateAllowed}


from __future__ import unicode_literals

# Make classes previously residing here available in the old location for
# backwards compatibility with extensions targeting Mopidy < 0.18.
from mopidy.backend.dummy import *  # noqa

Make old DummyBackend imports work

backend: Make old DummyBackend imports work

Response:
<INSERT> from __future__ import unicode_literals

# Make classes previously residing here available in the old location for
# backwards compatibility with extensions targeting Mopidy < 0.18.
from mopidy.backend.dummy import * <INSERT_END> <INSERT> # noqa
 <INSERT_END> <|endoftext|> from __future__ import unicode_literals

# Make classes previously residing here available in the old location for
# backwards compatibility with extensions targeting Mopidy < 0.18.
from mopidy.backend.dummy import *  # noqa

Prompt: backend: Make old DummyBackend imports work


class Kiosk():
    def __init__(self, location, visit_cost, diabetes_threshold,
            cardio_threshold):
        self.location = location
        self.visit_cost = visit_cost
        self.diabetes_threshold = diabetes_threshold
        self.cardio_threshold = cardio_threshold
        #Initial cost to create kiosk: $5000. We are measuring in rupees
        self.money = -309900
        print 'initializing Kiosk'

    #patient shold be Person
    def visit(self, patient):
        if not patient.location == self.location:
            print 'patient not in correct location'
            return False
        if not patient.money>self.visit_cost:
            print 'patient cannot afford treatment'
        patient.money -= visit_cost
        kiosk.money += visit_cost

        #If we diagnose diabetes
        if patient.diabetes<diabetes_threshold:
            #For now, we ignore the details and just improve the patient's
            #health.
            patient.diabetes = diabetes_threshold

        #If we diagnose cardiovascular problems
        if patient.cardio<cardio_threshold:
            #For now, we ignore the details and just improve the patient's
            #health.
            patient.cardio = cardio_threshold

        #The visit was successful
        return True

Clean up and finish Kiosk class

Response:
<INSERT> location, <INSERT_END> <REPLACE_OLD> location):
 <REPLACE_NEW> diabetes_threshold,
            cardio_threshold):
        self.location = location
 <REPLACE_END> <REPLACE_OLD> self.location = location
 <REPLACE_NEW> self.diabetes_threshold = diabetes_threshold
        self.cardio_threshold = cardio_threshold
        #Initial cost to create kiosk: $5000. We are measuring in rupees
        self.money = -309900
 <REPLACE_END> <REPLACE_OLD> treatment'

    #patient should be Person
    def visit(self, patient):
 <REPLACE_NEW> treatment'
 <REPLACE_END> <REPLACE_OLD> #improve patient.diabetes
        #improve patient.cardio
 <REPLACE_NEW> kiosk.money += visit_cost

        #If we diagnose diabetes
        if patient.diabetes<diabetes_threshold:
            #For now, we ignore the details and just improve the patient's
            #health.
            patient.diabetes = diabetes_threshold

        #If we diagnose cardiovascular problems
        if patient.cardio<cardio_threshold:
            #For now, we ignore the details and just improve the patient's
            #health.
            patient.cardio = cardio_threshold

        #The visit was successful
 <REPLACE_END> <REPLACE_OLD> True

    #Patient should be from class Person
    def filter(self, patient):
        if not patient.location == self.location:
            print "patient not at proper location"
            return False
        if not patient.money>self.visit_cost:
            print "patient cannot afford treatment"
            return False
        visit(self,patient)
 <REPLACE_NEW> True
 <REPLACE_END> <|endoftext|> class Kiosk():
    def __init__(self, location, visit_cost, diabetes_threshold,
            cardio_threshold):
        self.location = location
        self.visit_cost = visit_cost
        self.diabetes_threshold = diabetes_threshold
        self.cardio_threshold = cardio_threshold
        #Initial cost to create kiosk: $5000. We are measuring in rupees
        self.money = -309900
        print 'initializing Kiosk'

    #patient shold be Person
    def visit(self, patient):
        if not patient.location == self.location:
            print 'patient not in correct location'
            return False
        if not patient.money>self.visit_cost:
            print 'patient cannot afford treatment'
        patient.money -= visit_cost
        kiosk.money += visit_cost

        #If we diagnose diabetes
        if patient.diabetes<diabetes_threshold:
            #For now, we ignore the details and just improve the patient's
            #health.
            patient.diabetes = diabetes_threshold

        #If we diagnose cardiovascular problems
        if patient.cardio<cardio_threshold:
            #For now, we ignore the details and just improve the patient's
            #health.
            patient.cardio = cardio_threshold

        #The visit was successful
        return True

Prompt:
Clean up and finish Kiosk class

There was some redundancy because I merged it poorly

class Kiosk():
    def __init__(self, visit_cost, location):
        self.visit_cost = visit_cost
        self.location = location
        print 'initializing Kiosk'

    #patient shold be Person
    def visit(self, patient):
        if not patient.location == self.location:
            print 'patient not in correct location'
            return False
        if not patient.money>self.visit_cost:
            print 'patient cannot afford treatment'

    #patient should be Person
    def visit(self, patient):
        patient.money -= visit_cost
        #improve patient.diabetes
        #improve patient.cardio
        return True

    #Patient should be from class Person
    def filter(self, patient):
        if not patient.location == self.location:
            print "patient not at proper location"
            return False
        if not patient.money>self.visit_cost:
            print "patient cannot afford treatment"
            return False
        visit(self,patient)


Update python script for pep8 style

Update python script for pep8 style

Response:
<REPLACE_OLD> datetime

def <REPLACE_NEW> datetime

def <REPLACE_END> <REPLACE_OLD> True

def <REPLACE_NEW> True

def <REPLACE_END> <REPLACE_OLD> False

def <REPLACE_NEW> False

def <REPLACE_END> <REPLACE_OLD> 123

def <REPLACE_NEW> 123

def <REPLACE_END> <REPLACE_OLD> 1.0

def <REPLACE_NEW> 1.0

def <REPLACE_END> <REPLACE_OLD> "ABC"

def <REPLACE_NEW> "ABC"

def <REPLACE_END> <REPLACE_OLD> bytearray('abcdefg')

def <REPLACE_NEW> bytearray('abcdefg')

def <REPLACE_END> <REPLACE_OLD> 3}]

def <REPLACE_NEW> 3}]

def <REPLACE_END> <REPLACE_OLD> "str"}

def <REPLACE_NEW> "str"}

def <REPLACE_END> <REPLACE_OLD> 123}}

def <REPLACE_NEW> 123}}

def <REPLACE_END> <REPLACE_OLD> None

def <REPLACE_NEW> None

def <REPLACE_END> <|endoftext|> #!/usr/bin/env python
import datetime

def return_true():
    return True

def return_false():
    return False

def return_int():
    return 123

def return_float():
    return 1.0

def return_string():
    return "ABC"

def return_bytearray():
    return bytearray('abcdefg')

def return_array():
    return [1, 2, {"key": 3}]

def return_map():
    return {"key1": 123, "key2": "str"}

def return_nested_map():
    return {"key1": {"key2": 123}}

def return_none():
    return None

def return_timestamp():
    return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)

Prompt:
Update python script for pep8 style

#!/usr/bin/env python
import datetime

def return_true():
    return True

def return_false():
    return False

def return_int():
    return 123

def return_float():
    return 1.0

def return_string():
    return "ABC"

def return_bytearray():
    return bytearray('abcdefg')

def return_array():
    return [1, 2, {"key": 3}]

def return_map():
    return {"key1": 123, "key2": "str"}

def return_nested_map():
    return {"key1": {"key2": 123}}

def return_none():
    return None

def return_timestamp():
    return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)


#! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap

import os
import shutil

def ApplyPatches(filein, fileout):
        # Generate short name such as wrans/answers2003-03-31.html
        (rest, name) = os.path.split(filein)
        (rest, dir) = os.path.split(rest)
        fileshort = os.path.join(dir, name)

        # Look for a patch file from our collection (which is
        # in the pyscraper/patches folder in Public Whip CVS)
        patchfile = os.path.join("patches", fileshort + ".patch")
        if not os.path.isfile(patchfile):
                return False

        while True:
                # Apply the patch
                shutil.copyfile(filein, fileout)

                # delete temporary file that might have been created by a previous patch failure
                filoutorg = fileout + ".orig"
                if os.path.isfile(filoutorg):
                    os.remove(filoutorg)
                status = os.system("patch --quiet %s <%s" % (fileout, patchfile))

                if status == 0:
                        return True

                raise Exception, "Error running 'patch' on file %s" % fileshort

                #print "blanking out %s" % fileshort
                #os.rename(patchfile, patchfile + ".old~")
                #blankfile = open(patchfile, "w")
                #blankfile.close()

Remove code which blanks patch files

Remove code which blanks patch files

Response:
<REPLACE_OLD> print <REPLACE_NEW> raise Exception, <REPLACE_END> <REPLACE_OLD> %s, blanking it out" <REPLACE_NEW> %s" % fileshort

                #print "blanking out %s" <REPLACE_END> <REPLACE_OLD> os.rename(patchfile, <REPLACE_NEW> #os.rename(patchfile, <REPLACE_END> <REPLACE_OLD> blankfile <REPLACE_NEW> #blankfile <REPLACE_END> <REPLACE_OLD> blankfile.close()
 <REPLACE_NEW> #blankfile.close()
 <REPLACE_END> <|endoftext|> #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap

import os
import shutil

def ApplyPatches(filein, fileout):
        # Generate short name such as wrans/answers2003-03-31.html
        (rest, name) = os.path.split(filein)
        (rest, dir) = os.path.split(rest)
        fileshort = os.path.join(dir, name)

        # Look for a patch file from our collection (which is
        # in the pyscraper/patches folder in Public Whip CVS)
        patchfile = os.path.join("patches", fileshort + ".patch")
        if not os.path.isfile(patchfile):
                return False

        while True:
                # Apply the patch
                shutil.copyfile(filein, fileout)

                # delete temporary file that might have been created by a previous patch failure
                filoutorg = fileout + ".orig"
                if os.path.isfile(filoutorg):
                    os.remove(filoutorg)
                status = os.system("patch --quiet %s <%s" % (fileout, patchfile))

                if status == 0:
                        return True

                raise Exception, "Error running 'patch' on file %s" % fileshort

                #print "blanking out %s" % fileshort
                #os.rename(patchfile, patchfile + ".old~")
                #blankfile = open(patchfile, "w")
                #blankfile.close()

Prompt:
Remove code which blanks patch files

#! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap

import os
import shutil

def ApplyPatches(filein, fileout):
        # Generate short name such as wrans/answers2003-03-31.html
        (rest, name) = os.path.split(filein)
        (rest, dir) = os.path.split(rest)
        fileshort = os.path.join(dir, name)

        # Look for a patch file from our collection (which is
        # in the pyscraper/patches folder in Public Whip CVS)
        patchfile = os.path.join("patches", fileshort + ".patch")
        if not os.path.isfile(patchfile):
                return False

        while True:
                # Apply the patch
                shutil.copyfile(filein, fileout)

                # delete temporary file that might have been created by a previous patch failure
                filoutorg = fileout + ".orig"
                if os.path.isfile(filoutorg):
                    os.remove(filoutorg)
                status = os.system("patch --quiet %s <%s" % (fileout, patchfile))

                if status == 0:
                        return True

                print "Error running 'patch' on file %s, blanking it out" % fileshort
                os.rename(patchfile, patchfile + ".old~")
                blankfile = open(patchfile, "w")
                blankfile.close()


# Set up a null roothandler for our logging system

import logging
from logging import NullHandler
logging.getLogger(__name__).addHandler(NullHandler())

Response:
<REPLACE_OLD> logging
try:  # Python 2.7+
    from <REPLACE_NEW> logging
from <REPLACE_END> <REPLACE_OLD> NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

logging.getLogger(__name__).addHandler(NullHandler())
 <REPLACE_NEW> NullHandler
logging.getLogger(__name__).addHandler(NullHandler())
 <REPLACE_END> <|endoftext|> # Set up a null roothandler for our logging system

import logging
from logging import NullHandler
logging.getLogger(__name__).addHandler(NullHandler())

Prompt:
Remove the NullHandler patch because we don't support any python versions that need it

# Set up a null roothandler for our logging system

import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

logging.getLogger(__name__).addHandler(NullHandler())


import matplotlib
from matplotlib import pyplot as plt

from ..utils.decorators import wraps

MPL_VERSION = matplotlib.__version__

ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/"

IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
                       ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))

def ignore_matplotlibrc(func):
    # This is a decorator for tests that use matplotlib but not pytest-mpl
    # (which already handles rcParams)
    @wraps(func)
    def wrapper(*args, **kwargs):
        with plt.style.context({}, after_reset=True):
            return func(*args, **kwargs)
    return wrapper

Add back mirror for image tests

Add back mirror for image tests

Response:
<REPLACE_OLD> ROOT.format(server='data.astropy.org', <REPLACE_NEW> (ROOT.format(server='data.astropy.org', <REPLACE_END> <REPLACE_OLD> '.x')

def <REPLACE_NEW> '.x') + ',' +
                       ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))

def <REPLACE_END> <|endoftext|> import matplotlib
from matplotlib import pyplot as plt

from ..utils.decorators import wraps

MPL_VERSION = matplotlib.__version__

ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/"

IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
                       ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))

def ignore_matplotlibrc(func):
    # This is a decorator for tests that use matplotlib but not pytest-mpl
    # (which already handles rcParams)
    @wraps(func)
    def wrapper(*args, **kwargs):
        with plt.style.context({}, after_reset=True):
            return func(*args, **kwargs)
    return wrapper

Prompt:
Add back mirror for image tests
import matplotlib
from matplotlib import pyplot as plt

from ..utils.decorators import wraps

MPL_VERSION = matplotlib.__version__

ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/"

IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x')

def ignore_matplotlibrc(func):
    # This is a decorator for tests that use matplotlib but not pytest-mpl
    # (which already handles rcParams)
    @wraps(func)
    def wrapper(*args, **kwargs):
        with plt.style.context({}, after_reset=True):
            return func(*args, **kwargs)
    return wrapper


from pyramid.settings import asbool

from .client import ElasticClient

def client_from_config(settings, prefix='elastic.'):
    """
    Instantiate and configure an Elasticsearch from settings.

    In typical Pyramid usage, you shouldn't use this directly: instead, just
    include ``pyramid_es`` and use the :py:func:`get_client` function to get
    access to the shared :py:class:`.client.ElasticClient` instance.
    """
    return ElasticClient(
        servers=settings.get(prefix + 'servers', ['localhost:9200']),
        timeout=settings.get(prefix + 'timeout', 1.0),
        index=settings[prefix + 'index'],
        use_transaction=asbool(settings.get(prefix + 'use_transaction', True)),
        disable_indexing=settings.get(prefix + 'disable_indexing', False))

def includeme(config):
    registry = config.registry
    settings = registry.settings

    client = client_from_config(settings)
    if asbool(settings.get('elastic.ensure_index_on_start')):
        client.ensure_index()

    registry.pyramid_es_client = client

def get_client(request):
    """
    Get the registered Elasticsearch client. The supplied argument can be
    either a ``Request`` instance or a ``Registry``.
    """
    registry = getattr(request, 'registry', None)
    if registry is None:
        registry = request
    return registry.pyramid_es_client

Response:
<INSERT> if asbool(settings.get('elastic.ensure_index_on_start')):
        <INSERT_END> <|endoftext|> from pyramid.settings import asbool

from .client import ElasticClient

def client_from_config(settings, prefix='elastic.'):
    """
    Instantiate and configure an Elasticsearch from settings.

    In typical Pyramid usage, you shouldn't use this directly: instead, just
    include ``pyramid_es`` and use the :py:func:`get_client` function to get
    access to the shared :py:class:`.client.ElasticClient` instance.
    """
    return ElasticClient(
        servers=settings.get(prefix + 'servers', ['localhost:9200']),
        timeout=settings.get(prefix + 'timeout', 1.0),
        index=settings[prefix + 'index'],
        use_transaction=asbool(settings.get(prefix + 'use_transaction', True)),
        disable_indexing=settings.get(prefix + 'disable_indexing', False))

def includeme(config):
    registry = config.registry
    settings = registry.settings

    client = client_from_config(settings)
    if asbool(settings.get('elastic.ensure_index_on_start')):
        client.ensure_index()

    registry.pyramid_es_client = client

def get_client(request):
    """
    Get the registered Elasticsearch client. The supplied argument can be
    either a ``Request`` instance or a ``Registry``.
    """
    registry = getattr(request, 'registry', None)
    if registry is None:
        registry = request
    return registry.pyramid_es_client

Prompt:
Add a settings key to ensure index at start

from pyramid.settings import asbool

from .client import ElasticClient

def client_from_config(settings, prefix='elastic.'):
    """
    Instantiate and configure an Elasticsearch from settings.

    In typical Pyramid usage, you shouldn't use this directly: instead, just
    include ``pyramid_es`` and use the :py:func:`get_client` function to get
    access to the shared :py:class:`.client.ElasticClient` instance.
    """
    return ElasticClient(
        servers=settings.get(prefix + 'servers', ['localhost:9200']),
        timeout=settings.get(prefix + 'timeout', 1.0),
        index=settings[prefix + 'index'],
        use_transaction=asbool(settings.get(prefix + 'use_transaction', True)),
        disable_indexing=settings.get(prefix + 'disable_indexing', False))

def includeme(config):
    registry = config.registry
    settings = registry.settings

    client = client_from_config(settings)
    client.ensure_index()

    registry.pyramid_es_client = client

def get_client(request):
    """
    Get the registered Elasticsearch client. The supplied argument can be
    either a ``Request`` instance or a ``Registry``.
    """
    registry = getattr(request, 'registry', None)
    if registry is None:
        registry = request
    return registry.pyramid_es_client


import json
from provpy import *

# Define your namespaces (see provpyexample_PROVURIRef_PROVNamespace.py)
FOAF = PROVNamespace("http://xmlns.com/foaf/0.1/")
ex = PROVNamespace("http://www.example.com/")
dcterms = PROVNamespace("http://purl.org/dc/terms/")
xsd = PROVNamespace('http://www.w3.org/2001/XMLSchema-datatypes#')
prov = PROVNamespace("http://www.w3.org/ns/prov-dm/")

# create a provenance container
examplegraph = PROVContainer()

# Set the default namespace name
examplegraph.set_default_namespace("http://www.example.com/")

#add the other namespaces into the container
examplegraph.add_namespace("dcterms","http://purl.org/dc/terms/")
examplegraph.add_namespace("foaf","http://xmlns.com/foaf/0.1/")

# add entities, first define the attributes in a dictionary
attrdict = {"type": "File",
            ex["path"]: "/shared/crime.txt",
            ex["creator"]: "Alice"}
# then create the entity
# If you give the id as a string, it will be treated as a localname
# under the default namespace
e0 = Entity(id="e0",attributes=attrdict)
# you can then add the entity into the provenance container
examplegraph.add(e0)

# define the attributes for the next entity
lit0 = PROVLiteral("2011-11-16T16:06:00",xsd["dateTime"])
attrdict ={prov["type"]: ex["File"],
           ex["path"]: "/shared/crime.txt",
           dcterms["creator"]: FOAF['Alice'],
           ex["content"]: "",
           dcterms["create"]: lit0}
# create the entity, note this time we give the id as a PROVURIRef
e1 = Entity(FOAF['Foo'],attributes=attrdict)
examplegraph.add(e1)

# add activities
# You can give the attributes during the creation if there are not many
a0 = Activity(id=None,starttime=datetime.datetime(2008, 7, 6, 5, 4, 3),attributes={prov["recipeLink"]: ex["create-file"]})
examplegraph.add(a0)

# You can have the JSON of the container with the to_provJSON() function
# as container is also a provenance record
print json.dumps(examplegraph.to_provJSON(),indent=4)

Add an example file demonstrating defining, adding and serializing prov elements in a prov container

Response:
<REPLACE_OLD>  <REPLACE_NEW> import json
from provpy import *

# Define your namespaces (see provpyexample_PROVURIRef_PROVNamespace.py)
FOAF = PROVNamespace("http://xmlns.com/foaf/0.1/")
ex = PROVNamespace("http://www.example.com/")
dcterms = PROVNamespace("http://purl.org/dc/terms/")
xsd = PROVNamespace('http://www.w3.org/2001/XMLSchema-datatypes#')
prov = PROVNamespace("http://www.w3.org/ns/prov-dm/")

# create a provenance container
examplegraph = PROVContainer()

# Set the default namespace name
examplegraph.set_default_namespace("http://www.example.com/")

#add the other namespaces into the container
examplegraph.add_namespace("dcterms","http://purl.org/dc/terms/")
examplegraph.add_namespace("foaf","http://xmlns.com/foaf/0.1/")

# add entities, first define the attributes in a dictionary
attrdict = {"type": "File",
            ex["path"]: "/shared/crime.txt",
            ex["creator"]: "Alice"}
# then create the entity
# If you give the id as a string, it will be treated as a localname
# under the default namespace
e0 = Entity(id="e0",attributes=attrdict)
# you can then add the entity into the provenance container
examplegraph.add(e0)

# define the attributes for the next entity
lit0 = PROVLiteral("2011-11-16T16:06:00",xsd["dateTime"])
attrdict ={prov["type"]: ex["File"],
           ex["path"]: "/shared/crime.txt",
           dcterms["creator"]: FOAF['Alice'],
           ex["content"]: "",
           dcterms["create"]: lit0}
# create the entity, note this time we give the id as a PROVURIRef
e1 = Entity(FOAF['Foo'],attributes=attrdict)
examplegraph.add(e1)

# add activities
# You can give the attributes during the creation if there are not many
a0 = Activity(id=None,starttime=datetime.datetime(2008, 7, 6, 5, 4, 3),attributes={prov["recipeLink"]: ex["create-file"]})
examplegraph.add(a0)

# You can have the JSON of the container with the to_provJSON() function
# as container is also a provenance record
print json.dumps(examplegraph.to_provJSON(),indent=4) <REPLACE_END> <|endoftext|> import json
from provpy import *

# Define your namespaces (see provpyexample_PROVURIRef_PROVNamespace.py)
FOAF = PROVNamespace("http://xmlns.com/foaf/0.1/")
ex = PROVNamespace("http://www.example.com/")
dcterms = PROVNamespace("http://purl.org/dc/terms/")
xsd = PROVNamespace('http://www.w3.org/2001/XMLSchema-datatypes#')
prov = PROVNamespace("http://www.w3.org/ns/prov-dm/")

# create a provenance container
examplegraph = PROVContainer()

# Set the default namespace name
examplegraph.set_default_namespace("http://www.example.com/")

#add the other namespaces into the container
examplegraph.add_namespace("dcterms","http://purl.org/dc/terms/")
examplegraph.add_namespace("foaf","http://xmlns.com/foaf/0.1/")

# add entities, first define the attributes in a dictionary
attrdict = {"type": "File",
            ex["path"]: "/shared/crime.txt",
            ex["creator"]: "Alice"}
# then create the entity
# If you give the id as a string, it will be treated as a localname
# under the default namespace
e0 = Entity(id="e0",attributes=attrdict)
# you can then add the entity into the provenance container
examplegraph.add(e0)

# define the attributes for the next entity
lit0 = PROVLiteral("2011-11-16T16:06:00",xsd["dateTime"])
attrdict ={prov["type"]: ex["File"],
           ex["path"]: "/shared/crime.txt",
           dcterms["creator"]: FOAF['Alice'],
           ex["content"]: "",
           dcterms["create"]: lit0}
# create the entity, note this time we give the id as a PROVURIRef
e1 = Entity(FOAF['Foo'],attributes=attrdict)
examplegraph.add(e1)

# add activities
# You can give the attributes during the creation if there are not many
a0 = Activity(id=None,starttime=datetime.datetime(2008, 7, 6, 5, 4, 3),attributes={prov["recipeLink"]: ex["create-file"]})
examplegraph.add(a0)

# You can have the JSON of the container with the to_provJSON() function
# as container is also a provenance record
print json.dumps(examplegraph.to_provJSON(),indent=4)

Prompt: Add an example file demonstrating defining, adding and serializing prov elements in a prov container


santaPosition = [0, 0]
roboSantaPosition = [0, 0]

uniquePositions = set()

input = open("data", "r").read()
for index, char in enumerate(input):
	position = []

	if index % 2 == 0:
		position = santaPosition
	else:
		position = roboSantaPosition

	if char is '^':
		position[0] += 1
	elif char is 'v':
		position[0] -= 1
	elif char is '>':
		position[1] += 1
	elif char is '<':
		position[1] -= 1

	uniquePositions.add(tuple(position))

print "Happy Houses:", len(uniquePositions)

Response:
<REPLACE_OLD> 1

	uniquePositions.add((position[0], position[1]))

print <REPLACE_NEW> 1

	uniquePositions.add(tuple(position))

print <REPLACE_END> <REPLACE_OLD> len(uniquePositions) <REPLACE_NEW> len(uniquePositions)
 <REPLACE_END> <|endoftext|> santaPosition = [0, 0]
roboSantaPosition = [0, 0]

uniquePositions = set()

input = open("data", "r").read()
for index, char in enumerate(input):
	position = []

	if index % 2 == 0:
		position = santaPosition
	else:
		position = roboSantaPosition

	if char is '^':
		position[0] += 1
	elif char is 'v':
		position[0] -= 1
	elif char is '>':
		position[1] += 1
	elif char is '<':
		position[1] -= 1

	uniquePositions.add(tuple(position))

print "Happy Houses:", len(uniquePositions)

Prompt:
Make tuple creation from position cleaner.

santaPosition = [0, 0]
roboSantaPosition = [0, 0]

uniquePositions = set()

input = open("data", "r").read()
for index, char in enumerate(input):
	position = []

	if index % 2 == 0:
		position = santaPosition
	else:
		position = roboSantaPosition

	if char is '^':
		position[0] += 1
	elif char is 'v':
		position[0] -= 1
	elif char is '>':
		position[1] += 1
	elif char is '<':
		position[1] -= 1

	uniquePositions.add((position[0], position[1]))

print "Happy Houses:", len(uniquePositions)


import json

from six.moves.urllib_parse import urlencode

from .oauth import OAuth2Test

class DatagouvfrOAuth2Test(OAuth2Test):
    backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
    user_data_url = 'https://www.data.gouv.fr/api/1/me/'
    expected_username = 'foobar'
    access_token_body = json.dumps({
        'access_token': 'foobar',
        'token_type': 'bearer',
        'first_name': 'foobar',
        'email': 'foobar@example.com'
    })
    request_token_body = urlencode({
        'oauth_token_secret': 'foobar-secret',
        'oauth_token': 'foobar',
        'oauth_callback_confirmed': 'true'
    })
    user_data_body = json.dumps({})

    def test_login(self):
        self.do_login()

    def test_partial_pipeline(self):
        self.do_partial_pipeline()

Fix tests for udata/datagouvfr backend

Fix tests for udata/datagouvfr backend

Response:
<REPLACE_OLD> 'bearer'
 <REPLACE_NEW> 'bearer',
        'first_name': 'foobar',
        'email': 'foobar@example.com'
 <REPLACE_END> <|endoftext|> import json

from six.moves.urllib_parse import urlencode

from .oauth import OAuth2Test

class DatagouvfrOAuth2Test(OAuth2Test):
    backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
    user_data_url = 'https://www.data.gouv.fr/api/1/me/'
    expected_username = 'foobar'
    access_token_body = json.dumps({
        'access_token': 'foobar',
        'token_type': 'bearer',
        'first_name': 'foobar',
        'email': 'foobar@example.com'
    })
    request_token_body = urlencode({
        'oauth_token_secret': 'foobar-secret',
        'oauth_token': 'foobar',
        'oauth_callback_confirmed': 'true'
    })
    user_data_body = json.dumps({})

    def test_login(self):
        self.do_login()

    def test_partial_pipeline(self):
        self.do_partial_pipeline()

Prompt:
Fix tests for udata/datagouvfr backend

import json

from six.moves.urllib_parse import urlencode

from .oauth import OAuth2Test

class DatagouvfrOAuth2Test(OAuth2Test):
    backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
    user_data_url = 'https://www.data.gouv.fr/api/1/me/'
    expected_username = 'foobar'
    access_token_body = json.dumps({
        'access_token': 'foobar',
        'token_type': 'bearer'
    })
    request_token_body = urlencode({
        'oauth_token_secret': 'foobar-secret',
        'oauth_token': 'foobar',
        'oauth_callback_confirmed': 'true'
    })
    user_data_body = json.dumps({})

    def test_login(self):
        self.do_login()

    def test_partial_pipeline(self):
        self.do_partial_pipeline()


# coding: utf8

import os
import sys
import unittest

from .common import *

# On Windows, Python 3.0 - 3.5 have issues handling unicode filenames.
# Starting with Python 3.6 the situation is saner thanks to PEP 529:
#
# https://www.python.org/dev/peps/pep-0529/

broken_unicode = (
    os.name == 'nt' and
    sys.version_info >= (3, 0) and
    sys.version_info < (3, 6))

class TestContainers(TestCase):

    @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken')
    def test_unicode_filename(self):

        container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')

Response:
<REPLACE_OLD> utf8

from <REPLACE_NEW> utf8

import os
import sys
import unittest

from <REPLACE_END> <REPLACE_OLD> *

class <REPLACE_NEW> *

# On Windows, Python 3.0 - 3.5 have issues handling unicode filenames.
# Starting with Python 3.6 the situation is saner thanks to PEP 529:
#
# https://www.python.org/dev/peps/pep-0529/

broken_unicode = (
    os.name == 'nt' and
    sys.version_info >= (3, 0) and
    sys.version_info < (3, 6))

class <REPLACE_END> <INSERT>    @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken')
 <INSERT_END> <|endoftext|> # coding: utf8

import os
import sys
import unittest

from .common import *

# On Windows, Python 3.0 - 3.5 have issues handling unicode filenames.
# Starting with Python 3.6 the situation is saner thanks to PEP 529:
#
# https://www.python.org/dev/peps/pep-0529/

broken_unicode = (
    os.name == 'nt' and
    sys.version_info >= (3, 0) and
    sys.version_info < (3, 6))

class TestContainers(TestCase):

    @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken')
    def test_unicode_filename(self):

        container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')

Prompt:
Disable unicode filename test on Windows with Python 3.0 - 3.5

Before PEP 529 landed in Python 3.6, unicode filename handling on
Windows is hit-and-miss, so don't break CI.

# coding: utf8

from .common import *

class TestContainers(TestCase):

    def test_unicode_filename(self):

        container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')


from django.http import HttpResponse
from django.shortcuts import render_to_response
from store.models import FandomHierarchy

def frontpage(request, filter=None):
	return render_to_response('index.html', {'filter': filter, 'nodes': FandomHierarchy.objects.all()})

Response:
<REPLACE_OLD> filter):
	return <REPLACE_NEW> filter=None):
	return <REPLACE_END> <|endoftext|> from django.http import HttpResponse
from django.shortcuts import render_to_response
from store.models import FandomHierarchy

def frontpage(request, filter=None):
	return render_to_response('index.html', {'filter': filter, 'nodes': FandomHierarchy.objects.all()})

Prompt:
Add default value for filter so things don't break

from django.http import HttpResponse
from django.shortcuts import render_to_response
from store.models import FandomHierarchy

def frontpage(request, filter):
	return render_to_response('index.html', {'filter': filter, 'nodes': FandomHierarchy.objects.all()})


# Basic example for testing purposes, taken from
# https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/

import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView

class MyBrowser(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QWebView.__init__(self)
        self.ui = BrowserDialog()
        self.ui.setupUi(self)
        self.ui.lineEdit.returnPressed.connect(self.loadURL)

    def loadURL(self):
        url = self.ui.lineEdit.text()
        self.ui.qwebview.load(QUrl(url))
        self.show()
        # self.ui.lineEdit.setText("")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyBrowser()
    myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb'))
    myapp.show()
    sys.exit(app.exec_())

Response:
<REPLACE_OLD> import <REPLACE_NEW> # Basic example for testing purposes, taken from
# https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/

import <REPLACE_END> <|endoftext|> # Basic example for testing purposes, taken from
# https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/

import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView

class MyBrowser(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QWebView.__init__(self)
        self.ui = BrowserDialog()
        self.ui.setupUi(self)
        self.ui.lineEdit.returnPressed.connect(self.loadURL)

    def loadURL(self):
        url = self.ui.lineEdit.text()
        self.ui.qwebview.load(QUrl(url))
        self.show()
        # self.ui.lineEdit.setText("")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyBrowser()
    myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb'))
    myapp.show()
    sys.exit(app.exec_())

Prompt:
Add a comment about where the basic example was taken
[skip CI]

import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView

class MyBrowser(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QWebView.__init__(self)
        self.ui = BrowserDialog()
        self.ui.setupUi(self)
        self.ui.lineEdit.returnPressed.connect(self.loadURL)

    def loadURL(self):
        url = self.ui.lineEdit.text()
        self.ui.qwebview.load(QUrl(url))
        self.show()
        # self.ui.lineEdit.setText("")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyBrowser()
    myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb'))
    myapp.show()
    sys.exit(app.exec_())


from setuptools import setup, find_packages

requires = [
    'configparser',
    'python-dateutil',
    'pytz',
    'requests',
    'simplejson'
]

setup(
    name='amaascore',
    version='0.1.8',
    description='Asset Management as a Service - Core SDK',
    license='Apache License 2.0',
    url='https://github.com/amaas-fintech/amaas-core-sdk-python',
    author='AMaaS',
    author_email='tech@amaas.com',
    classifiers=[
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
    packages=find_packages(exclude=['tests']),  # Very annoying that this doesnt work - I have to include a MANIFEST
    install_requires=requires,
)

Response:
<REPLACE_OLD> version='0.1.7',
 <REPLACE_NEW> version='0.1.8',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

requires = [
    'configparser',
    'python-dateutil',
    'pytz',
    'requests',
    'simplejson'
]

setup(
    name='amaascore',
    version='0.1.8',
    description='Asset Management as a Service - Core SDK',
    license='Apache License 2.0',
    url='https://github.com/amaas-fintech/amaas-core-sdk-python',
    author='AMaaS',
    author_email='tech@amaas.com',
    classifiers=[
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
    packages=find_packages(exclude=['tests']),  # Very annoying that this doesnt work - I have to include a MANIFEST
    install_requires=requires,
)

Prompt:
Increment version for deployment to PyPI

from setuptools import setup, find_packages

requires = [
    'configparser',
    'python-dateutil',
    'pytz',
    'requests',
    'simplejson'
]

setup(
    name='amaascore',
    version='0.1.7',
    description='Asset Management as a Service - Core SDK',
    license='Apache License 2.0',
    url='https://github.com/amaas-fintech/amaas-core-sdk-python',
    author='AMaaS',
    author_email='tech@amaas.com',
    classifiers=[
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
    packages=find_packages(exclude=['tests']),  # Very annoying that this doesnt work - I have to include a MANIFEST
    install_requires=requires,
)


# http://djangosnippets.org/snippets/2311/
# Ensure South will update our custom SQL during a call to `migrate`.

from south.signals import post_migrate

def run_initial_sql(sender, **kwargs):
    app_label = kwargs.get('app')
    import os
    from django.db import connection, transaction, models
    app_dir = os.path.normpath(os.path.join(os.path.dirname(
                    models.get_app(app_label).__file__), 'sql'))
    backend_name = connection.settings_dict['ENGINE'].split('.')[-1]
    sql_files = [os.path.join(app_dir, "%s.%s.sql" % (app_label, backend_name)),
                 os.path.join(app_dir, "%s.sql" % app_label)]
    cursor = connection.cursor()
    for sql_file in sql_files:
        try:
            if os.path.exists(sql_file):
                print "Loading initial SQL data from '%s'" % sql_file
                f = open(sql_file)
                sql = f.read()
                f.close()
                cursor.execute(sql)
        except Exception, e:
            import sys
            sys.stderr.write("Failed to install custom SQL file '%s': %s\n" %
                                (sql_file, e))
            import traceback
            traceback.print_exc()
            transaction.rollback_unless_managed()
        else:
            transaction.commit_unless_managed()
post_migrate.connect(run_initial_sql)

Enable auto-loading of raw SQL during South migration

Response:
<REPLACE_OLD>  <REPLACE_NEW> # http://djangosnippets.org/snippets/2311/
# Ensure South will update our custom SQL during a call to `migrate`.

from south.signals import post_migrate

def run_initial_sql(sender, **kwargs):
    app_label = kwargs.get('app')
    import os
    from django.db import connection, transaction, models
    app_dir = os.path.normpath(os.path.join(os.path.dirname(
                    models.get_app(app_label).__file__), 'sql'))
    backend_name = connection.settings_dict['ENGINE'].split('.')[-1]
    sql_files = [os.path.join(app_dir, "%s.%s.sql" % (app_label, backend_name)),
                 os.path.join(app_dir, "%s.sql" % app_label)]
    cursor = connection.cursor()
    for sql_file in sql_files:
        try:
            if os.path.exists(sql_file):
                print "Loading initial SQL data from '%s'" % sql_file
                f = open(sql_file)
                sql = f.read()
                f.close()
                cursor.execute(sql)
        except Exception, e:
            import sys
            sys.stderr.write("Failed to install custom SQL file '%s': %s\n" %
                                (sql_file, e))
            import traceback
            traceback.print_exc()
            transaction.rollback_unless_managed()
        else:
            transaction.commit_unless_managed()
post_migrate.connect(run_initial_sql)
 <REPLACE_END> <|endoftext|> # http://djangosnippets.org/snippets/2311/
# Ensure South will update our custom SQL during a call to `migrate`.

from south.signals import post_migrate

def run_initial_sql(sender, **kwargs):
    app_label = kwargs.get('app')
    import os
    from django.db import connection, transaction, models
    app_dir = os.path.normpath(os.path.join(os.path.dirname(
                    models.get_app(app_label).__file__), 'sql'))
    backend_name = connection.settings_dict['ENGINE'].split('.')[-1]
    sql_files = [os.path.join(app_dir, "%s.%s.sql" % (app_label, backend_name)),
                 os.path.join(app_dir, "%s.sql" % app_label)]
    cursor = connection.cursor()
    for sql_file in sql_files:
        try:
            if os.path.exists(sql_file):
                print "Loading initial SQL data from '%s'" % sql_file
                f = open(sql_file)
                sql = f.read()
                f.close()
                cursor.execute(sql)
        except Exception, e:
            import sys
            sys.stderr.write("Failed to install custom SQL file '%s': %s\n" %
                                (sql_file, e))
            import traceback
            traceback.print_exc()
            transaction.rollback_unless_managed()
        else:
            transaction.commit_unless_managed()
post_migrate.connect(run_initial_sql)

Prompt: Enable auto-loading of raw SQL during South migration


#!/usr/bin/env python

from __future__ import absolute_import, division, print_function

from setuptools import setup

setup(
    include_package_data=True,
    test_suite="nose.collector",
    tests_require=['nose', 'hocr-spec'],
    setup_requires=['pbr'],
    pbr=True,
)

Response:
<REPLACE_OLD> tests_require="nose",
 <REPLACE_NEW> tests_require=['nose', 'hocr-spec'],
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from __future__ import absolute_import, division, print_function

from setuptools import setup

setup(
    include_package_data=True,
    test_suite="nose.collector",
    tests_require=['nose', 'hocr-spec'],
    setup_requires=['pbr'],
    pbr=True,
)

Prompt:
Add hocr-spec-python to test requirements

#!/usr/bin/env python

from __future__ import absolute_import, division, print_function

from setuptools import setup

setup(
    include_package_data=True,
    test_suite="nose.collector",
    tests_require="nose",
    setup_requires=['pbr'],
    pbr=True,
)


import logging
import os

import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi

from swd6 import config
from swd6.db.models import db

CONF = config.CONF
DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf'
app = None

def start():
    #  pylint: disable=global-statement
    global app
    app = flask.Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = CONF.db.uri
    app.config['SERVER_NAME'] = CONF.api.host

    app.logger.setLevel(logging.DEBUG)

    flask_cors.CORS(app, origins=CONF.api.cors_hosts, supports_credentials=True)

    logging.getLogger('flask_cors').level = logging.DEBUG

    db.init_app(app)

    flask_jsonapi.FlaskJSONAPI(app, db, options={'dasherize': False, 'include_fk_columns': True})
    return app

logging.basicConfig(level=logging.DEBUG)
if os.path.exists(DEFAULT_CONF_PATH):
    config_files = [DEFAULT_CONF_PATH]
else:
    config_files = []

config.load([], default_config_files=config_files)

start()

Fix CORS to allow for credentials

Response:
<REPLACE_OLD> origins=CONF.api.cors_hosts)

 <REPLACE_NEW> origins=CONF.api.cors_hosts, supports_credentials=True)

 <REPLACE_END> <|endoftext|> import logging
import os

import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi

from swd6 import config
from swd6.db.models import db

CONF = config.CONF
DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf'
app = None

def start():
    #  pylint: disable=global-statement
    global app
    app = flask.Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = CONF.db.uri
    app.config['SERVER_NAME'] = CONF.api.host

    app.logger.setLevel(logging.DEBUG)

    flask_cors.CORS(app, origins=CONF.api.cors_hosts, supports_credentials=True)

    logging.getLogger('flask_cors').level = logging.DEBUG

    db.init_app(app)

    flask_jsonapi.FlaskJSONAPI(app, db, options={'dasherize': False, 'include_fk_columns': True})
    return app

logging.basicConfig(level=logging.DEBUG)
if os.path.exists(DEFAULT_CONF_PATH):
    config_files = [DEFAULT_CONF_PATH]
else:
    config_files = []

config.load([], default_config_files=config_files)

start()

Prompt:
Fix CORS to allow for credentials

Something changed in the client code requiring this
setting.

import logging
import os

import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi

from swd6 import config
from swd6.db.models import db

CONF = config.CONF
DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf'
app = None

def start():
    #  pylint: disable=global-statement
    global app
    app = flask.Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = CONF.db.uri
    app.config['SERVER_NAME'] = CONF.api.host

    app.logger.setLevel(logging.DEBUG)

    flask_cors.CORS(app, origins=CONF.api.cors_hosts)

    logging.getLogger('flask_cors').level = logging.DEBUG

    db.init_app(app)

    flask_jsonapi.FlaskJSONAPI(app, db, options={'dasherize': False, 'include_fk_columns': True})
    return app

logging.basicConfig(level=logging.DEBUG)
if os.path.exists(DEFAULT_CONF_PATH):
    config_files = [DEFAULT_CONF_PATH]
else:
    config_files = []

config.load([], default_config_files=config_files)

start()


import pdb
import time
import collections
import random
import itertools
import xmlrpclib
import dis

server_url = 'http://127.0.0.1:20738/RPC2'
server = xmlrpclib.Server(server_url)
G = server.ubigraph

def erdos ():
    vert_ids = range(0,1000)
    p = 0.001

    G.clear()
    pdb.set_trace()

    for id in vert_ids:
        G.new_vertex_w_id(id)

    edge_count = 0
    for i,j in itertools.combinations(vert_ids, 2):
        r = random.random()
        if r <= p:
            edge_count += 1
            id = G.new_edge(i, j)
            #G.set_edge_attribute(id, 'oriented', 'true')
            #G.set_edge_attribute(id, 'arrow', 'true')
            #G.set_edge_attribute(id, 'showstrain', 'true')
            #G.set_edge_attribute(id, 'strength', '0.0')

    print edge_count

def groupbycount (ids):
    return [len(list(li[1])) for li in itertools.groupby(sorted(ids))]

def preferential ():
    G.clear()
    size = 1000
    G.new_vertex_w_id(0)
    ids = [0]
    for i in range(1, size):
        G.new_vertex_w_id(i)
        j = random.choice(ids)
        G.new_edge(i,j)
        ids += [i,j]

    hist = groupbycount(ids)
    histprime = collections.defaultdict(lambda:0)
    for i in hist:
        histprime[i] += 1

    print sorted([(k,v) for k,v in histprime.items()])

if __name__ == '__main__':
    #preferential()
    erdos()

Add code to generate Erdos and preferential attachment graphs

Response:
<REPLACE_OLD>  <REPLACE_NEW> import pdb
import time
import collections
import random
import itertools
import xmlrpclib
import dis

server_url = 'http://127.0.0.1:20738/RPC2'
server = xmlrpclib.Server(server_url)
G = server.ubigraph

def erdos ():
    vert_ids = range(0,1000)
    p = 0.001

    G.clear()
    pdb.set_trace()

    for id in vert_ids:
        G.new_vertex_w_id(id)

    edge_count = 0
    for i,j in itertools.combinations(vert_ids, 2):
        r = random.random()
        if r <= p:
            edge_count += 1
            id = G.new_edge(i, j)
            #G.set_edge_attribute(id, 'oriented', 'true')
            #G.set_edge_attribute(id, 'arrow', 'true')
            #G.set_edge_attribute(id, 'showstrain', 'true')
            #G.set_edge_attribute(id, 'strength', '0.0')

    print edge_count

def groupbycount (ids):
    return [len(list(li[1])) for li in itertools.groupby(sorted(ids))]

def preferential ():
    G.clear()
    size = 1000
    G.new_vertex_w_id(0)
    ids = [0]
    for i in range(1, size):
        G.new_vertex_w_id(i)
        j = random.choice(ids)
        G.new_edge(i,j)
        ids += [i,j]

    hist = groupbycount(ids)
    histprime = collections.defaultdict(lambda:0)
    for i in hist:
        histprime[i] += 1

    print sorted([(k,v) for k,v in histprime.items()])

if __name__ == '__main__':
    #preferential()
    erdos()
 <REPLACE_END> <|endoftext|> import pdb
import time
import collections
import random
import itertools
import xmlrpclib
import dis

server_url = 'http://127.0.0.1:20738/RPC2'
server = xmlrpclib.Server(server_url)
G = server.ubigraph

def erdos ():
    vert_ids = range(0,1000)
    p = 0.001

    G.clear()
    pdb.set_trace()

    for id in vert_ids:
        G.new_vertex_w_id(id)

    edge_count = 0
    for i,j in itertools.combinations(vert_ids, 2):
        r = random.random()
        if r <= p:
            edge_count += 1
            id = G.new_edge(i, j)
            #G.set_edge_attribute(id, 'oriented', 'true')
            #G.set_edge_attribute(id, 'arrow', 'true')
            #G.set_edge_attribute(id, 'showstrain', 'true')
            #G.set_edge_attribute(id, 'strength', '0.0')

    print edge_count

def groupbycount (ids):
    return [len(list(li[1])) for li in itertools.groupby(sorted(ids))]

def preferential ():
    G.clear()
    size = 1000
    G.new_vertex_w_id(0)
    ids = [0]
    for i in range(1, size):
        G.new_vertex_w_id(i)
        j = random.choice(ids)
        G.new_edge(i,j)
        ids += [i,j]

    hist = groupbycount(ids)
    histprime = collections.defaultdict(lambda:0)
    for i in hist:
        histprime[i] += 1

    print sorted([(k,v) for k,v in histprime.items()])

if __name__ == '__main__':
    #preferential()
    erdos()

Prompt: Add code to generate Erdos and preferential attachment graphs


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

from tests_aio.unit._test_base import AioTestBase

class TestInit(AioTestBase):

    async def test_grpc(self):
        import grpc  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_grpc_dot_aio(self):
        import grpc.aio  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)

Response:
<REPLACE_OLD> grpc.aio.Channel)

    async def test_aio_from_grpc(self):
        from grpc import aio  # pylint: disable=wrong-import-position
        channel = aio.insecure_channel('dummy')
        self.assertIsInstance(channel, aio.Channel)

if <REPLACE_NEW> grpc.aio.Channel)

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

from tests_aio.unit._test_base import AioTestBase

class TestInit(AioTestBase):

    async def test_grpc(self):
        import grpc  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_grpc_dot_aio(self):
        import grpc.aio  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)

Prompt:
Make sure the module space won't be polluted by "from grpc import aio"

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

from tests_aio.unit._test_base import AioTestBase

class TestInit(AioTestBase):

    async def test_grpc(self):
        import grpc  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_grpc_dot_aio(self):
        import grpc.aio  # pylint: disable=wrong-import-position
        channel = grpc.aio.insecure_channel('dummy')
        self.assertIsInstance(channel, grpc.aio.Channel)

    async def test_aio_from_grpc(self):
        from grpc import aio  # pylint: disable=wrong-import-position
        channel = aio.insecure_channel('dummy')
        self.assertIsInstance(channel, aio.Channel)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)


from haas.utils import uncamelcase
from .i_plugin import IPlugin

class BasePlugin(IPlugin):

    name = None
    enabled = False
    enabling_option = None

    def __init__(self, name=None):
        if name is None:
            name = uncamelcase(type(self).__name__, sep='-')
        self.name = name
        self.enabling_option = 'with_{0}'.format(name.replace('-', '_'))

    def add_parser_arguments(self, parser):
        parser.add_argument('--with-{0}'.format(self.name),
                            action='store_true',
                            help='Enable the {0} plugin'.format(self.name),
                            dest=self.enabling_option)

    def configure(self, args):
        if getattr(args, self.enabling_option, False):
            self.enabled = True

Add help text for plugin enable option

Add help text for plugin enable option

Response:
<INSERT> help='Enable the {0} plugin'.format(self.name),
                            <INSERT_END> <|endoftext|> from haas.utils import uncamelcase
from .i_plugin import IPlugin

class BasePlugin(IPlugin):

    name = None
    enabled = False
    enabling_option = None

    def __init__(self, name=None):
        if name is None:
            name = uncamelcase(type(self).__name__, sep='-')
        self.name = name
        self.enabling_option = 'with_{0}'.format(name.replace('-', '_'))

    def add_parser_arguments(self, parser):
        parser.add_argument('--with-{0}'.format(self.name),
                            action='store_true',
                            help='Enable the {0} plugin'.format(self.name),
                            dest=self.enabling_option)

    def configure(self, args):
        if getattr(args, self.enabling_option, False):
            self.enabled = True

Prompt:
Add help text for plugin enable option

from haas.utils import uncamelcase
from .i_plugin import IPlugin

class BasePlugin(IPlugin):

    name = None
    enabled = False
    enabling_option = None

    def __init__(self, name=None):
        if name is None:
            name = uncamelcase(type(self).__name__, sep='-')
        self.name = name
        self.enabling_option = 'with_{0}'.format(name.replace('-', '_'))

    def add_parser_arguments(self, parser):
        parser.add_argument('--with-{0}'.format(self.name),
                            action='store_true',
                            dest=self.enabling_option)

    def configure(self, args):
        if getattr(args, self.enabling_option, False):
            self.enabled = True


"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

from django.test import TestCase
from .models import Address

class ModelsTest(TestCase):
    def test_create_address(self):
        a = Address()
        a.street = '23, Test Street'
        a.town = 'London'
        a.postcode = 'xxxxx'
        a.country = 'UK'
        a.save()
        self.assertTrue(a.id >= 0)

Add Address model creation test case

Add Address model creation test case

Response:
<REPLACE_OLD> TestCase

class SimpleTest(TestCase):
 <REPLACE_NEW> TestCase
from .models import Address

class ModelsTest(TestCase):
 <REPLACE_END> <REPLACE_OLD> test_basic_addition(self):
 <REPLACE_NEW> test_create_address(self):
 <REPLACE_END> <REPLACE_OLD> """
 <REPLACE_NEW> a = Address()
 <REPLACE_END> <REPLACE_OLD> Tests that 1 + 1 always equals 2.
 <REPLACE_NEW> a.street = '23, Test Street'
 <REPLACE_END> <REPLACE_OLD> """
 <REPLACE_NEW> a.town = 'London'
 <REPLACE_END> <REPLACE_OLD> self.assertEqual(1 + 1, 2)
 <REPLACE_NEW> a.postcode = 'xxxxx'
        a.country = 'UK'
        a.save()
        self.assertTrue(a.id >= 0)
 <REPLACE_END> <|endoftext|> """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

from django.test import TestCase
from .models import Address

class ModelsTest(TestCase):
    def test_create_address(self):
        a = Address()
        a.street = '23, Test Street'
        a.town = 'London'
        a.postcode = 'xxxxx'
        a.country = 'UK'
        a.save()
        self.assertTrue(a.id >= 0)

Prompt:
Add Address model creation test case

"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

from django.test import TestCase

class SimpleTest(TestCase):
    def test_basic_addition(self):
        """
        Tests that 1 + 1 always equals 2.
        """
        self.assertEqual(1 + 1, 2)


# -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

{
    'name': 'Sale Analytic Cost',
    "version": "8.0.1.0.0",
    "license": 'AGPL-3',
    "author": 'AvanzOSC,'
              'Serv. Tecnol. Avanzados - Pedro M. Baeza',
    'website': "http://www.odoomrp.com",
    "contributors": [
        "Ainara Galdona <ainaragaldona@avanzosc.es>",
        "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
        "Ana Juaristi <anajuaristi@avanzosc.es>",
        ],
    'category': 'Sales',
    'depends': ['sale',
                'account',
                'mrp_production_estimated_cost'],
    'data': [],
    'installable': True,
}

Response:
<REPLACE_OLD> 'mrp_production_project_estimated_cost'],
 <REPLACE_NEW> 'mrp_production_estimated_cost'],
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

{
    'name': 'Sale Analytic Cost',
    "version": "8.0.1.0.0",
    "license": 'AGPL-3',
    "author": 'AvanzOSC,'
              'Serv. Tecnol. Avanzados - Pedro M. Baeza',
    'website': "http://www.odoomrp.com",
    "contributors": [
        "Ainara Galdona <ainaragaldona@avanzosc.es>",
        "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
        "Ana Juaristi <anajuaristi@avanzosc.es>",
        ],
    'category': 'Sales',
    'depends': ['sale',
                'account',
                'mrp_production_estimated_cost'],
    'data': [],
    'installable': True,
}

Prompt:
[FIX] sale_analytic_cost: Change dependency with "mrp_production_project_estimated_cost" by dependecy "mrp_production_estimated_cost".

# -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

{
    'name': 'Sale Analytic Cost',
    "version": "8.0.1.0.0",
    "license": 'AGPL-3',
    "author": 'AvanzOSC,'
              'Serv. Tecnol. Avanzados - Pedro M. Baeza',
    'website': "http://www.odoomrp.com",
    "contributors": [
        "Ainara Galdona <ainaragaldona@avanzosc.es>",
        "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
        "Ana Juaristi <anajuaristi@avanzosc.es>",
        ],
    'category': 'Sales',
    'depends': ['sale',
                'account',
                'mrp_production_project_estimated_cost'],
    'data': [],
    'installable': True,
}


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

from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from django.utils import translation

from cms.models import Title

def from_iterable(iterables):
    """
    Backport of itertools.chain.from_iterable
    """
    for it in iterables:
        for element in it:
            yield element

class CMSSitemap(Sitemap):
    changefreq = "monthly"
    priority = 0.5

    def items(self):
        #
        # It is counter-productive to provide entries for:
        #   > Pages which redirect:
        #       - If the page redirects to another page on this site, the
        #         destination page will already be in the sitemap, and
        #       - If the page redirects externally, then it shouldn't be
        #         part of our sitemap anyway.
        #   > Pages which cannot be accessed by anonymous users (like
        #     search engines are).
        #
        all_titles = Title.objects.public().filter(
            Q(redirect='') | Q(redirect__isnull=True),
            page__login_required=False
        )
        return all_titles

    def lastmod(self, title):
        modification_dates = [title.page.changed_date, title.page.publication_date]
        plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
        plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
        plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
        modification_dates.extend(plugin_modification_dates)
        return max(modification_dates)

    def location(self, title):
        translation.activate(title.language)
        url = title.page.get_absolute_url(title.language)
        translation.deactivate()
        return url

Response:
<REPLACE_OLD> -*-
from <REPLACE_NEW> -*-

from <REPLACE_END> <INSERT> django.db.models import Q
from <INSERT_END> <REPLACE_OLD> translation
from <REPLACE_NEW> translation

from <REPLACE_END> <INSERT> #
        # It is counter-productive to provide entries for:
        #   > Pages which redirect:
        #       - If the page redirects to another page on this site, the
        #         destination page will already be in the sitemap, and
        #       - If the page redirects externally, then it shouldn't be
        #         part of our sitemap anyway.
        #   > Pages which cannot be accessed by anonymous users (like
        #     search engines are).
        #
        <INSERT_END> <REPLACE_OLD> Title.objects.public().filter(page__login_required=False)
 <REPLACE_NEW> Title.objects.public().filter(
            Q(redirect='') | Q(redirect__isnull=True),
            page__login_required=False
        )
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from django.utils import translation

from cms.models import Title

def from_iterable(iterables):
    """
    Backport of itertools.chain.from_iterable
    """
    for it in iterables:
        for element in it:
            yield element

class CMSSitemap(Sitemap):
    changefreq = "monthly"
    priority = 0.5

    def items(self):
        #
        # It is counter-productive to provide entries for:
        #   > Pages which redirect:
        #       - If the page redirects to another page on this site, the
        #         destination page will already be in the sitemap, and
        #       - If the page redirects externally, then it shouldn't be
        #         part of our sitemap anyway.
        #   > Pages which cannot be accessed by anonymous users (like
        #     search engines are).
        #
        all_titles = Title.objects.public().filter(
            Q(redirect='') | Q(redirect__isnull=True),
            page__login_required=False
        )
        return all_titles

    def lastmod(self, title):
        modification_dates = [title.page.changed_date, title.page.publication_date]
        plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
        plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
        plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
        modification_dates.extend(plugin_modification_dates)
        return max(modification_dates)

    def location(self, title):
        translation.activate(title.language)
        url = title.page.get_absolute_url(title.language)
        translation.deactivate()
        return url

Prompt:
Remove redirected pages from the sitemap

# -*- coding: utf-8 -*-
from django.contrib.sitemaps import Sitemap
from django.utils import translation
from cms.models import Title

def from_iterable(iterables):
    """
    Backport of itertools.chain.from_iterable
    """
    for it in iterables:
        for element in it:
            yield element

class CMSSitemap(Sitemap):
    changefreq = "monthly"
    priority = 0.5

    def items(self):
        all_titles = Title.objects.public().filter(page__login_required=False)
        return all_titles

    def lastmod(self, title):
        modification_dates = [title.page.changed_date, title.page.publication_date]
        plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
        plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
        plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
        modification_dates.extend(plugin_modification_dates)
        return max(modification_dates)

    def location(self, title):
        translation.activate(title.language)
        url = title.page.get_absolute_url(title.language)
        translation.deactivate()
        return url


from kivy.uix.screenmanager import Screen
#from kivy.properties import *
from kivy.uix.settings import SettingSpacer

from my_setting import *
import audio as a_m

from kivy.uix.widget import Widget

class HSpacer(Widget):
    pass

class VSpacer(Widget):
    pass

class SettingsScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(SettingsScreen, self).__init__(*args, **kwargs)

    def adjust_volumes(self, *args):
        a_m.adjust_volumes()

    def set_confirmation_popups(self, *args):
        self.app.set_confirmation_popups()

Use our own spacer widgets

Use our own spacer widgets

Response:
<REPLACE_OLD> a_m

class <REPLACE_NEW> a_m

from kivy.uix.widget import Widget

class HSpacer(Widget):
    pass

class VSpacer(Widget):
    pass

class <REPLACE_END> <|endoftext|> from kivy.uix.screenmanager import Screen
#from kivy.properties import *
from kivy.uix.settings import SettingSpacer

from my_setting import *
import audio as a_m

from kivy.uix.widget import Widget

class HSpacer(Widget):
    pass

class VSpacer(Widget):
    pass

class SettingsScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(SettingsScreen, self).__init__(*args, **kwargs)

    def adjust_volumes(self, *args):
        a_m.adjust_volumes()

    def set_confirmation_popups(self, *args):
        self.app.set_confirmation_popups()

Prompt:
Use our own spacer widgets

from kivy.uix.screenmanager import Screen
#from kivy.properties import *
from kivy.uix.settings import SettingSpacer

from my_setting import *
import audio as a_m

class SettingsScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(SettingsScreen, self).__init__(*args, **kwargs)

    def adjust_volumes(self, *args):
        a_m.adjust_volumes()

    def set_confirmation_popups(self, *args):
        self.app.set_confirmation_popups()


import database

def test_encode_csv():
    test_data = (
        # strand, ref, alt, cdna_pos, exon, protein_id, is_ptm
        (('+', 'R', 'H', 204, 'exon1', 123, False), '+RH0cc:exon1:7b'),
        (('-', 'R', 'H', 204, 'exon1', 123, True), '-RH1cc:exon1:7b'),
    )
    for attributes, correct_result in test_data:
        result = database.encode_csv(*attributes)
        assert result == correct_result

def test_decode_csv():
    keys = ('strand', 'ref', 'alt', 'pos', 'cdna_pos', 'exon', 'protein_id', 'is_ptm')
    test_data = (
        ('+RH0cc:exon1:7b', ('+', 'R', 'H', 68, 204, 'exon1', 123, False)),
        ('-RH1cc:exon1:7b', ('-', 'R', 'H', 68, 204, 'exon1', 123, True)),
    )
    for encoded_csv, correct_result in test_data:
        result = database.decode_csv(encoded_csv)
        assert result == dict(zip(keys, correct_result))

Add more tests to database

Add more tests to database

Response:
<REPLACE_OLD> attributes <REPLACE_NEW> test_data <REPLACE_END> <REPLACE_OLD> '+', <REPLACE_NEW> (('+', <REPLACE_END> <REPLACE_OLD> False
 <REPLACE_NEW> False), '+RH0cc:exon1:7b'),
        (('-', 'R', 'H', 204, 'exon1', 123, True), '-RH1cc:exon1:7b'),
 <REPLACE_END> <INSERT>    for attributes, correct_result in test_data:
     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> '+RH0cc:exon1:7b'

def <REPLACE_NEW> correct_result

def <REPLACE_END> <REPLACE_OLD> encoded_csv <REPLACE_NEW> keys <REPLACE_END> <REPLACE_OLD> '+RH0cc:exon1:7b'
 <REPLACE_NEW> ('strand', 'ref', 'alt', 'pos', 'cdna_pos', 'exon', 'protein_id', 'is_ptm')
    test_data = (
        ('+RH0cc:exon1:7b', ('+', 'R', 'H', 68, 204, 'exon1', 123, False)),
        ('-RH1cc:exon1:7b', ('-', 'R', 'H', 68, 204, 'exon1', 123, True)),
    )
    for encoded_csv, correct_result in test_data:
     <REPLACE_END> <DELETE> assert result == dict(zip(
 <DELETE_END> <REPLACE_OLD>    ('strand', 'ref', 'alt', 'pos', 'cdna_pos', 'exon', 'protein_id', 'is_ptm'),
        ('+', 'R', 'H', 68, 204, 'exon1', 123, False)
    ))
 <REPLACE_NEW> assert result == dict(zip(keys, correct_result))
 <REPLACE_END> <|endoftext|> import database

def test_encode_csv():
    test_data = (
        # strand, ref, alt, cdna_pos, exon, protein_id, is_ptm
        (('+', 'R', 'H', 204, 'exon1', 123, False), '+RH0cc:exon1:7b'),
        (('-', 'R', 'H', 204, 'exon1', 123, True), '-RH1cc:exon1:7b'),
    )
    for attributes, correct_result in test_data:
        result = database.encode_csv(*attributes)
        assert result == correct_result

def test_decode_csv():
    keys = ('strand', 'ref', 'alt', 'pos', 'cdna_pos', 'exon', 'protein_id', 'is_ptm')
    test_data = (
        ('+RH0cc:exon1:7b', ('+', 'R', 'H', 68, 204, 'exon1', 123, False)),
        ('-RH1cc:exon1:7b', ('-', 'R', 'H', 68, 204, 'exon1', 123, True)),
    )
    for encoded_csv, correct_result in test_data:
        result = database.decode_csv(encoded_csv)
        assert result == dict(zip(keys, correct_result))

Prompt:
Add more tests to database

import database

def test_encode_csv():
    attributes = (
        # strand, ref, alt, cdna_pos, exon, protein_id, is_ptm
        '+', 'R', 'H', 204, 'exon1', 123, False
    )
    result = database.encode_csv(*attributes)
    assert result == '+RH0cc:exon1:7b'

def test_decode_csv():
    encoded_csv = '+RH0cc:exon1:7b'
    result = database.decode_csv(encoded_csv)
    assert result == dict(zip(
        ('strand', 'ref', 'alt', 'pos', 'cdna_pos', 'exon', 'protein_id', 'is_ptm'),
        ('+', 'R', 'H', 68, 204, 'exon1', 123, False)
    ))


# -*- coding: utf-8 -*-
from urlparse import urljoin

import requests

from dateutil import parser

from satnogsclient import settings
from satnogsclient.observer import Observer
from satnogsclient.scheduler import scheduler

def spawn_observation(*args, **kwargs):
    obj = kwargs.pop('obj')
    observer = Observer()
    tle = {
        'tle0': obj['tle0'],
        'tle1': obj['tle1'],
        'tle2': obj['tle2']
    }
    end = parser.parse(obj['end'])
    observer.setup(tle=tle, observation_end=end, frequency=obj['frequency'])
    observer.observe()

def get_jobs():
    """Query SatNOGS Network API to GET jobs."""
    url = urljoin(settings.NETWORK_API_URL, 'jobs')
    params = {'ground_station': settings.GROUND_STATION_ID}
    response = requests.get(url, params=params)

    if not response.status_code == 200:
        raise Exception('Status code: {0} on request: {1}'.format(response.status_code, url))

    for job in scheduler.get_jobs():
        if job.name == spawn_observation.__name__:
            job.remove()

    for obj in response.json():
        start = parser.parse(obj['start'])
        job_id = str(obj['id'])
        kwargs = {'obj': obj}
        scheduler.add_job(spawn_observation, 'date', run_date=start, id=job_id, kwargs=kwargs)

Response:
<INSERT> satnogsclient.observer import Observer
from <INSERT_END> <REPLACE_OLD> raise NotImplementedError

def <REPLACE_NEW> obj = kwargs.pop('obj')
    observer = Observer()
    tle = {
        'tle0': obj['tle0'],
        'tle1': obj['tle1'],
        'tle2': obj['tle2']
    }
    end = parser.parse(obj['end'])
    observer.setup(tle=tle, observation_end=end, frequency=obj['frequency'])
    observer.observe()

def <REPLACE_END> <INSERT> kwargs = {'obj': obj}
        <INSERT_END> <REPLACE_OLD> kwargs=obj)
 <REPLACE_NEW> kwargs=kwargs)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from urlparse import urljoin

import requests

from dateutil import parser

from satnogsclient import settings
from satnogsclient.observer import Observer
from satnogsclient.scheduler import scheduler

def spawn_observation(*args, **kwargs):
    obj = kwargs.pop('obj')
    observer = Observer()
    tle = {
        'tle0': obj['tle0'],
        'tle1': obj['tle1'],
        'tle2': obj['tle2']
    }
    end = parser.parse(obj['end'])
    observer.setup(tle=tle, observation_end=end, frequency=obj['frequency'])
    observer.observe()

def get_jobs():
    """Query SatNOGS Network API to GET jobs."""
    url = urljoin(settings.NETWORK_API_URL, 'jobs')
    params = {'ground_station': settings.GROUND_STATION_ID}
    response = requests.get(url, params=params)

    if not response.status_code == 200:
        raise Exception('Status code: {0} on request: {1}'.format(response.status_code, url))

    for job in scheduler.get_jobs():
        if job.name == spawn_observation.__name__:
            job.remove()

    for obj in response.json():
        start = parser.parse(obj['start'])
        job_id = str(obj['id'])
        kwargs = {'obj': obj}
        scheduler.add_job(spawn_observation, 'date', run_date=start, id=job_id, kwargs=kwargs)

Prompt:
Initialize and call observer on new observation task.

# -*- coding: utf-8 -*-
from urlparse import urljoin

import requests

from dateutil import parser

from satnogsclient import settings
from satnogsclient.scheduler import scheduler

def spawn_observation(*args, **kwargs):
    raise NotImplementedError

def get_jobs():
    """Query SatNOGS Network API to GET jobs."""
    url = urljoin(settings.NETWORK_API_URL, 'jobs')
    params = {'ground_station': settings.GROUND_STATION_ID}
    response = requests.get(url, params=params)

    if not response.status_code == 200:
        raise Exception('Status code: {0} on request: {1}'.format(response.status_code, url))

    for job in scheduler.get_jobs():
        if job.name == spawn_observation.__name__:
            job.remove()

    for obj in response.json():
        start = parser.parse(obj['start'])
        job_id = str(obj['id'])
        scheduler.add_job(spawn_observation, 'date', run_date=start, id=job_id, kwargs=obj)


import os
import yaml
from thermof.parameters import plot_parameters
from thermof.read import read_framework_distance

# --------------------------------------------------------------------------------------------------
main = ''
results_file = '%s-reldist-results.yaml' % os.path.basename(main)
run_list_file = '%s-run-list.yaml' % os.path.basename(main)
# --------------------------------------------------------------------------------------------------

run_list = [os.path.join(main, i, 'Run1') for i in os.listdir(main) if os.path.isdir(os.path.join(main, i))]
dist_data = read_framework_distance(run_list, plot_parameters['f_dist'])

with open(results_file, 'w') as rfile:
    yaml.dump(dist_data, rfile)

with open(run_list_file, 'w') as rlfile:
    yaml.dump(run_list, rlfile)

Add script for reading reldist for multiple trials

Response:
<INSERT> import os
import yaml
from thermof.parameters import plot_parameters
from thermof.read import read_framework_distance

# --------------------------------------------------------------------------------------------------
main = ''
results_file = '%s-reldist-results.yaml' % os.path.basename(main)
run_list_file = '%s-run-list.yaml' % os.path.basename(main)
# --------------------------------------------------------------------------------------------------

run_list = [os.path.join(main, i, 'Run1') for i in os.listdir(main) if os.path.isdir(os.path.join(main, i))]
dist_data = read_framework_distance(run_list, plot_parameters['f_dist'])

with open(results_file, 'w') as rfile:
 <INSERT_END> <INSERT>   yaml.dump(dist_data, rfile)

with open(run_list_file, 'w') as rlfile:
    yaml.dump(run_list, rlfile)
 <INSERT_END> <|endoftext|> import os
import yaml
from thermof.parameters import plot_parameters
from thermof.read import read_framework_distance

# --------------------------------------------------------------------------------------------------
main = ''
results_file = '%s-reldist-results.yaml' % os.path.basename(main)
run_list_file = '%s-run-list.yaml' % os.path.basename(main)
# --------------------------------------------------------------------------------------------------

run_list = [os.path.join(main, i, 'Run1') for i in os.listdir(main) if os.path.isdir(os.path.join(main, i))]
dist_data = read_framework_distance(run_list, plot_parameters['f_dist'])

with open(results_file, 'w') as rfile:
    yaml.dump(dist_data, rfile)

with open(run_list_file, 'w') as rlfile:
    yaml.dump(run_list, rlfile)

Prompt: Add script for reading reldist for multiple trials


from django import forms

from .models import Story
from cms.forms import ContentManageableModelForm

class StoryForm(ContentManageableModelForm):
    pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5}))

    class Meta:
        model = Story
        fields = (
            'name',
            'company_name',
            'company_url',
            'category',
            'author',
            'author_email',
            'pull_quote',
            'content'
        )

    def clean_name(self):
        name = self.cleaned_data.get('name')
        story = Story.objects.filter(name=name).exclude(pk=self.instance.pk)
        if name is not None and story.exists():
            raise forms.ValidationError('Please use a unique name.')
        return name

Reduce textarea height in Story form

Reduce textarea height in Story form

Response:
<INSERT> pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5}))

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

from .models import Story
from cms.forms import ContentManageableModelForm

class StoryForm(ContentManageableModelForm):
    pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5}))

    class Meta:
        model = Story
        fields = (
            'name',
            'company_name',
            'company_url',
            'category',
            'author',
            'author_email',
            'pull_quote',
            'content'
        )

    def clean_name(self):
        name = self.cleaned_data.get('name')
        story = Story.objects.filter(name=name).exclude(pk=self.instance.pk)
        if name is not None and story.exists():
            raise forms.ValidationError('Please use a unique name.')
        return name

Prompt:
Reduce textarea height in Story form

from django import forms

from .models import Story
from cms.forms import ContentManageableModelForm

class StoryForm(ContentManageableModelForm):
    class Meta:
        model = Story
        fields = (
            'name',
            'company_name',
            'company_url',
            'category',
            'author',
            'author_email',
            'pull_quote',
            'content'
        )

    def clean_name(self):
        name = self.cleaned_data.get('name')
        story = Story.objects.filter(name=name).exclude(pk=self.instance.pk)
        if name is not None and story.exists():
            raise forms.ValidationError('Please use a unique name.')
        return name