#!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen

import re
import zipfile

def main():
    '''
    Hint: zip, now there are pairs

    In the readme.txt:
    welcome to my zipped list.

    hint1: start from 90052
    hint2: answer is inside the zip

    Last nothing = 46145
    Collect the comments
    '''
    nothing = '90052'
    file_ext = '.txt'
    file_pattern = re.compile(r'Next nothing is (\d+)')
    zf = zipfile.ZipFile('./zip_chall_06/channel.zip')
    comments = []

    while True:
        filename = nothing + file_ext
        data = zf.read(filename).decode('utf-8')
        match = re.search(file_pattern, data)
        if match:
            nothing = match.group(1)
            # com = zf.getinfo(filename).comment.decode('utf-8')
            comments.append(zf.getinfo(filename).comment.decode('utf-8'))
            # print('Comment: {}'.format(com))
        else:
            break

    # print('Last nothing is: {}'.format(nothing))
    print(''.join(comments))

    return 0

if __name__ == '__main__':
    main()

Add print statements for clarity

Add print statements for clarity

Response:
<INSERT> # com = zf.getinfo(filename).comment.decode('utf-8')
            <INSERT_END> <INSERT>            # print('Comment: {}'.format(com))
 <INSERT_END> <|endoftext|> #!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen

import re
import zipfile

def main():
    '''
    Hint: zip, now there are pairs

    In the readme.txt:
    welcome to my zipped list.

    hint1: start from 90052
    hint2: answer is inside the zip

    Last nothing = 46145
    Collect the comments
    '''
    nothing = '90052'
    file_ext = '.txt'
    file_pattern = re.compile(r'Next nothing is (\d+)')
    zf = zipfile.ZipFile('./zip_chall_06/channel.zip')
    comments = []

    while True:
        filename = nothing + file_ext
        data = zf.read(filename).decode('utf-8')
        match = re.search(file_pattern, data)
        if match:
            nothing = match.group(1)
            # com = zf.getinfo(filename).comment.decode('utf-8')
            comments.append(zf.getinfo(filename).comment.decode('utf-8'))
            # print('Comment: {}'.format(com))
        else:
            break

    # print('Last nothing is: {}'.format(nothing))
    print(''.join(comments))

    return 0

if __name__ == '__main__':
    main()

Prompt:
Add print statements for clarity

#!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen

import re
import zipfile

def main():
    '''
    Hint: zip, now there are pairs

    In the readme.txt:
    welcome to my zipped list.

    hint1: start from 90052
    hint2: answer is inside the zip

    Last nothing = 46145
    Collect the comments
    '''
    nothing = '90052'
    file_ext = '.txt'
    file_pattern = re.compile(r'Next nothing is (\d+)')
    zf = zipfile.ZipFile('./zip_chall_06/channel.zip')
    comments = []

    while True:
        filename = nothing + file_ext
        data = zf.read(filename).decode('utf-8')
        match = re.search(file_pattern, data)
        if match:
            nothing = match.group(1)
            comments.append(zf.getinfo(filename).comment.decode('utf-8'))
        else:
            break

    # print('Last nothing is: {}'.format(nothing))
    print(''.join(comments))

    return 0

if __name__ == '__main__':
    main()


from setuptools import setup, find_packages

setup(
    name='panoptescli',
    version='1.1.1',
    url='https://github.com/zooniverse/panoptes-cli',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    description=(
        'A command-line client for Panoptes, the API behind the Zooniverse'
    ),
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Click>=6.7,<7.1',
        'PyYAML>=5.1,<5.3',
        'panoptes-client>=1.0,<2.0',
        'humanize>=0.5.1,<0.6',
        'pathvalidate>=0.29.0,<0.30',
    ],
    entry_points='''
        [console_scripts]
        panoptes=panoptes_cli.scripts.panoptes:cli
    ''',
)

Response:
<REPLACE_OLD> 'PyYAML>=5.1,<5.2',
 <REPLACE_NEW> 'PyYAML>=5.1,<5.3',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='panoptescli',
    version='1.1.1',
    url='https://github.com/zooniverse/panoptes-cli',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    description=(
        'A command-line client for Panoptes, the API behind the Zooniverse'
    ),
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Click>=6.7,<7.1',
        'PyYAML>=5.1,<5.3',
        'panoptes-client>=1.0,<2.0',
        'humanize>=0.5.1,<0.6',
        'pathvalidate>=0.29.0,<0.30',
    ],
    entry_points='''
        [console_scripts]
        panoptes=panoptes_cli.scripts.panoptes:cli
    ''',
)

Prompt:
Update pyyaml requirement from <5.2,>=5.1 to >=5.1,<5.3

Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES)
- [Commits](https://github.com/yaml/pyyaml/compare/5.1...5.2)

Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages

setup(
    name='panoptescli',
    version='1.1.1',
    url='https://github.com/zooniverse/panoptes-cli',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    description=(
        'A command-line client for Panoptes, the API behind the Zooniverse'
    ),
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Click>=6.7,<7.1',
        'PyYAML>=5.1,<5.2',
        'panoptes-client>=1.0,<2.0',
        'humanize>=0.5.1,<0.6',
        'pathvalidate>=0.29.0,<0.30',
    ],
    entry_points='''
        [console_scripts]
        panoptes=panoptes_cli.scripts.panoptes:cli
    ''',
)


""" A startup script for IPython to patch it to 'inspect' using cinspect. """

# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.

import inspect

from cinspect import getsource, getfile

import IPython.core.oinspect as OI
from IPython.utils.py3compat import cast_unicode

old_find_file = OI.find_file
old_getsource = inspect.getsource

inspect.getsource = getsource

def patch_find_file(obj):
    fname = old_find_file(obj)
    if fname is None:
        try:
            fname = cast_unicode(getfile(obj))
        except:
            pass
    return fname

OI.find_file = patch_find_file

ipy = get_ipython()

old_format = ipy.inspector.format

def c_format(raw, *args, **kwargs):
    return raw

def my_format(raw, out = None, scheme = ''):
    try:
        output = old_format(raw, out, scheme)
    except:
        output = raw
    return output

ipy.inspector.format = my_format

Response:
<REPLACE_OLD> patch_find_file
 <REPLACE_NEW> patch_find_file

ipy = get_ipython()

old_format = ipy.inspector.format

def c_format(raw, *args, **kwargs):
    return raw

def my_format(raw, out = None, scheme = ''):
    try:
        output = old_format(raw, out, scheme)
    except:
        output = raw
    return output

ipy.inspector.format = my_format
 <REPLACE_END> <|endoftext|> """ A startup script for IPython to patch it to 'inspect' using cinspect. """

# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.

import inspect

from cinspect import getsource, getfile

import IPython.core.oinspect as OI
from IPython.utils.py3compat import cast_unicode

old_find_file = OI.find_file
old_getsource = inspect.getsource

inspect.getsource = getsource

def patch_find_file(obj):
    fname = old_find_file(obj)
    if fname is None:
        try:
            fname = cast_unicode(getfile(obj))
        except:
            pass
    return fname

OI.find_file = patch_find_file

ipy = get_ipython()

old_format = ipy.inspector.format

def c_format(raw, *args, **kwargs):
    return raw

def my_format(raw, out = None, scheme = ''):
    try:
        output = old_format(raw, out, scheme)
    except:
        output = raw
    return output

ipy.inspector.format = my_format

Prompt:
Patch the colorized formatter to not break for C modules.

""" A startup script for IPython to patch it to 'inspect' using cinspect. """

# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.

import inspect

from cinspect import getsource, getfile

import IPython.core.oinspect as OI
from IPython.utils.py3compat import cast_unicode

old_find_file = OI.find_file
old_getsource = inspect.getsource

inspect.getsource = getsource

def patch_find_file(obj):
    fname = old_find_file(obj)
    if fname is None:
        try:
            fname = cast_unicode(getfile(obj))
        except:
            pass
    return fname

OI.find_file = patch_find_file


import json
import os
import sys
import time

import requests
import pync

try:
    cache = []
    headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
    since = None
    url = 'https://api.github.com/notifications'

    while True:
        params = {'since': since} if since else {}
        r = requests.get(url, headers=headers, params=params)
        if not r.ok:
            raise Exception('GitHub returned {0}'.format(r.status_code))

        since = time.strptime(r.headers['date'], '%a, %d %b %Y %H:%M:%S %Z')
        notifications = json.loads(r.content)
        if not notifications:
            cache = []

        for notification in notifications:
            if not notification['id'] in cache:
                latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:][0]
                issue_url = notification['subject']['url'].replace('api.', '').replace('repos/', '')
                open_url = '{0}#{1}'.format(issue_url, latest_comment_id)
                kwargs = {
                    'title': notification['repository']['full_name'],
                    'open': open_url,
                    'group': os.getpid(),
                }
                s = notification['subject']['url'].split('/')[-2:]
                pync.Notifier.notify('{0} #{1}'.format(s[0].title(), s[1]), **kwargs)

                cache.append(notification['id'])

        time.sleep(5)
except KeyboardInterrupt:
    sys.exit(0)

Use the list item, not the list.

Response:
<REPLACE_OLD> notification['subject']['latest_comment_url'].split('/')[-1:]
 <REPLACE_NEW> notification['subject']['latest_comment_url'].split('/')[-1:][0]
 <REPLACE_END> <|endoftext|> import json
import os
import sys
import time

import requests
import pync

try:
    cache = []
    headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
    since = None
    url = 'https://api.github.com/notifications'

    while True:
        params = {'since': since} if since else {}
        r = requests.get(url, headers=headers, params=params)
        if not r.ok:
            raise Exception('GitHub returned {0}'.format(r.status_code))

        since = time.strptime(r.headers['date'], '%a, %d %b %Y %H:%M:%S %Z')
        notifications = json.loads(r.content)
        if not notifications:
            cache = []

        for notification in notifications:
            if not notification['id'] in cache:
                latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:][0]
                issue_url = notification['subject']['url'].replace('api.', '').replace('repos/', '')
                open_url = '{0}#{1}'.format(issue_url, latest_comment_id)
                kwargs = {
                    'title': notification['repository']['full_name'],
                    'open': open_url,
                    'group': os.getpid(),
                }
                s = notification['subject']['url'].split('/')[-2:]
                pync.Notifier.notify('{0} #{1}'.format(s[0].title(), s[1]), **kwargs)

                cache.append(notification['id'])

        time.sleep(5)
except KeyboardInterrupt:
    sys.exit(0)

Prompt:
Use the list item, not the list.

Otherwise you get urls with `[u'1234']` in.

import json
import os
import sys
import time

import requests
import pync

try:
    cache = []
    headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
    since = None
    url = 'https://api.github.com/notifications'

    while True:
        params = {'since': since} if since else {}
        r = requests.get(url, headers=headers, params=params)
        if not r.ok:
            raise Exception('GitHub returned {0}'.format(r.status_code))

        since = time.strptime(r.headers['date'], '%a, %d %b %Y %H:%M:%S %Z')
        notifications = json.loads(r.content)
        if not notifications:
            cache = []

        for notification in notifications:
            if not notification['id'] in cache:
                latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:]
                issue_url = notification['subject']['url'].replace('api.', '').replace('repos/', '')
                open_url = '{0}#{1}'.format(issue_url, latest_comment_id)
                kwargs = {
                    'title': notification['repository']['full_name'],
                    'open': open_url,
                    'group': os.getpid(),
                }
                s = notification['subject']['url'].split('/')[-2:]
                pync.Notifier.notify('{0} #{1}'.format(s[0].title(), s[1]), **kwargs)

                cache.append(notification['id'])

        time.sleep(5)
except KeyboardInterrupt:
    sys.exit(0)


def ibm_rng(x1, a=65539, c=0, m=2**31):
    x = x1
    while True:
        x = (a * x + c) % m
        yield x / (m-1)

def main():
    rng = ibm_rng(1, 65539, 0, 2**31)

    while True:
        x = next(rng)
        print(x)

if __name__ == '__main__':
    main()

Add defaults to the ibm RNG

Add defaults to the ibm RNG

Response:
<REPLACE_OLD> a, c, m):
 <REPLACE_NEW> a=65539, c=0, m=2**31):
 <REPLACE_END> <|endoftext|> def ibm_rng(x1, a=65539, c=0, m=2**31):
    x = x1
    while True:
        x = (a * x + c) % m
        yield x / (m-1)

def main():
    rng = ibm_rng(1, 65539, 0, 2**31)

    while True:
        x = next(rng)
        print(x)

if __name__ == '__main__':
    main()

Prompt:
Add defaults to the ibm RNG

def ibm_rng(x1, a, c, m):
    x = x1
    while True:
        x = (a * x + c) % m
        yield x / (m-1)

def main():
    rng = ibm_rng(1, 65539, 0, 2**31)

    while True:
        x = next(rng)
        print(x)

if __name__ == '__main__':
    main()


from __future__ import unicode_literals, absolute_import

import os

if os.environ.get('ENV') and os.path.exists(os.environ['ENV']):
    for line in open(os.environ['ENV']):
        var = line.strip().split('=')
        if len(var) == 2:
            os.environ[var[0]] = var[1]

from identity import app

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0',
            port=port,
            debug=os.environ.get('DEBUG', False))

Load env-vars from a .env file

Load env-vars from a .env file

Response:
<REPLACE_OLD> os
from <REPLACE_NEW> os

if os.environ.get('ENV') and os.path.exists(os.environ['ENV']):
    for line in open(os.environ['ENV']):
        var = line.strip().split('=')
        if len(var) == 2:
            os.environ[var[0]] = var[1]

from <REPLACE_END> <|endoftext|> from __future__ import unicode_literals, absolute_import

import os

if os.environ.get('ENV') and os.path.exists(os.environ['ENV']):
    for line in open(os.environ['ENV']):
        var = line.strip().split('=')
        if len(var) == 2:
            os.environ[var[0]] = var[1]

from identity import app

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0',
            port=port,
            debug=os.environ.get('DEBUG', False))

Prompt:
Load env-vars from a .env file

from __future__ import unicode_literals, absolute_import

import os
from identity import app

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0',
            port=port,
            debug=os.environ.get('DEBUG', False))


from paraview.simple import *

import tonic
from tonic import paraview as pv

dataset_destination_path = '/Users/seb/spherical'

# Initial ParaView scene setup
Cone(Center=[2,4,8])
Show()
view = Render()
view.CameraFocalPoint = [2,4,8]
view.CameraPosition = [2,4,0]
view.CenterOfRotation = [2,4,8]
view.CameraViewUp = [0,1,0]
view = Render()

# Choose data location
dh = tonic.DataHandler(dataset_destination_path)
camera = pv.create_spherical_camera(view, dh, range(0, 360, 30), range(-60, 61, 30))

# Create data
dh.registerData(name='image', type='blob', mimeType='image/png', fileName='.png')

# Loop over data
for pos in camera:
    pv.update_camera(view, pos)
    WriteImage(dh.getDataAbsoluteFilePath('image'))

# Write metadata
dh.writeDataDescriptor()

test(CenterOfRotation): Add a test for spherical camera with off center object

Response:
<INSERT> from paraview.simple import *

import tonic
from tonic import paraview as pv

dataset_destination_path = '/Users/seb/spherical'

# Initial ParaView scene setup
Cone(Center=[2,4,8])
Show()
view = Render()
view.CameraFocalPoint = [2,4,8]
view.CameraPosition = [2,4,0]
view.CenterOfRotation = [2,4,8]
view.CameraViewUp = [0,1,0]
view = Render()

# Choose data location
dh = tonic.DataHandler(dataset_destination_path)
camera = pv.create_spherical_camera(view, dh, range(0, 360, 30), range(-60, 61, 30))

# Create data
dh.registerData(name='image', type='blob', mimeType='image/png', fileName='.png')

# Loop over data
for pos in camera:
 <INSERT_END> <INSERT>   pv.update_camera(view, pos)
    WriteImage(dh.getDataAbsoluteFilePath('image'))

# Write metadata
dh.writeDataDescriptor()
 <INSERT_END> <|endoftext|> from paraview.simple import *

import tonic
from tonic import paraview as pv

dataset_destination_path = '/Users/seb/spherical'

# Initial ParaView scene setup
Cone(Center=[2,4,8])
Show()
view = Render()
view.CameraFocalPoint = [2,4,8]
view.CameraPosition = [2,4,0]
view.CenterOfRotation = [2,4,8]
view.CameraViewUp = [0,1,0]
view = Render()

# Choose data location
dh = tonic.DataHandler(dataset_destination_path)
camera = pv.create_spherical_camera(view, dh, range(0, 360, 30), range(-60, 61, 30))

# Create data
dh.registerData(name='image', type='blob', mimeType='image/png', fileName='.png')

# Loop over data
for pos in camera:
    pv.update_camera(view, pos)
    WriteImage(dh.getDataAbsoluteFilePath('image'))

# Write metadata
dh.writeDataDescriptor()

Prompt: test(CenterOfRotation): Add a test for spherical camera with off center object


import json
import hunting.sim.entities as entities

class GameObjectEncoder(json.JSONEncoder):
    def default(self, o):
        d = o.__dict__
        d.pop('owner', None)

        if isinstance(o, entities.GameObject):
            d.pop('log', None)
            d.pop('ai', None)
            return d
        elif isinstance(o, entities.Fighter):
            d.pop('death_function')
            return d
        elif isinstance(o, entities.ChangeableProperty):
            return {k: o.__dict__[k] for k in ['property_type', 'base']}
        else:
            return d

def encode_level(level):
    save_factions = {f: level.get_faction_info(f) for f in level.get_factions()
                     if level.get_faction_info(f)['save'] is True}

    for f in save_factions:
        save_factions[f]['objects'] = level.get_objects_inside_faction(f)

    output = {'log': level.log.events,
              'factions': save_factions}

    return json.dumps(output, cls=GameObjectEncoder, indent=2)

Response:
<REPLACE_OLD> [f <REPLACE_NEW> {f: level.get_faction_info(f) <REPLACE_END> <REPLACE_OLD> level.get_factions() <REPLACE_NEW> level.get_factions()
                     <REPLACE_END> <REPLACE_OLD> True]
    factions_to_objects = {f: level.get_objects_inside_faction(f) <REPLACE_NEW> True}

    <REPLACE_END> <REPLACE_OLD> save_factions}
    return json.dumps(factions_to_objects, <REPLACE_NEW> save_factions:
        save_factions[f]['objects'] = level.get_objects_inside_faction(f)

    output = {'log': level.log.events,
              'factions': save_factions}

    return json.dumps(output, <REPLACE_END> <|endoftext|> import json
import hunting.sim.entities as entities

class GameObjectEncoder(json.JSONEncoder):
    def default(self, o):
        d = o.__dict__
        d.pop('owner', None)

        if isinstance(o, entities.GameObject):
            d.pop('log', None)
            d.pop('ai', None)
            return d
        elif isinstance(o, entities.Fighter):
            d.pop('death_function')
            return d
        elif isinstance(o, entities.ChangeableProperty):
            return {k: o.__dict__[k] for k in ['property_type', 'base']}
        else:
            return d

def encode_level(level):
    save_factions = {f: level.get_faction_info(f) for f in level.get_factions()
                     if level.get_faction_info(f)['save'] is True}

    for f in save_factions:
        save_factions[f]['objects'] = level.get_objects_inside_faction(f)

    output = {'log': level.log.events,
              'factions': save_factions}

    return json.dumps(output, cls=GameObjectEncoder, indent=2)

Prompt:
Add log to encoding output (still fails due to objects)

import json
import hunting.sim.entities as entities

class GameObjectEncoder(json.JSONEncoder):
    def default(self, o):
        d = o.__dict__
        d.pop('owner', None)

        if isinstance(o, entities.GameObject):
            d.pop('log', None)
            d.pop('ai', None)
            return d
        elif isinstance(o, entities.Fighter):
            d.pop('death_function')
            return d
        elif isinstance(o, entities.ChangeableProperty):
            return {k: o.__dict__[k] for k in ['property_type', 'base']}
        else:
            return d

def encode_level(level):
    save_factions = [f for f in level.get_factions() if level.get_faction_info(f)['save'] is True]
    factions_to_objects = {f: level.get_objects_inside_faction(f) for f in save_factions}
    return json.dumps(factions_to_objects, cls=GameObjectEncoder, indent=2)


"""
General example for an attack against code like this:

    Py_DECREF(obj->attr); obj->attr = ...;

here in Module/_json.c:scanner_init().

Explanation: if the first Py_DECREF() calls either a __del__ or a
weakref callback, it will run while the 'obj' appears to have in
'obj->attr' still the old reference to the object, but not holding
the reference count any more.

Status: progress has been made replacing these cases, but there is an
infinite number of such cases.
"""

import _json, weakref

class Ctx1(object):
    encoding = "utf8"
    strict = None
    object_hook = None
    object_pairs_hook = None
    parse_float = None
    parse_int = None
    parse_constant = None

class Foo(unicode):
    pass

def delete_me(*args):
    print scanner.encoding.__dict__

class Ctx2(Ctx1):
    @property
    def encoding(self):
        global wref
        f = Foo("utf8")
        f.abc = globals()
        wref = weakref.ref(f, delete_me)
        return f

scanner = _json.make_scanner(Ctx1())
scanner.__init__(Ctx2())

Add a crasher for the documented issue of calling "Py_DECREF(self->xxx)";

Response:
<INSERT> """
General example for an attack against code like this:

 <INSERT_END> <INSERT>   Py_DECREF(obj->attr); obj->attr = ...;

here in Module/_json.c:scanner_init().

Explanation: if the first Py_DECREF() calls either a __del__ or a
weakref callback, it will run while the 'obj' appears to have in
'obj->attr' still the old reference to the object, but not holding
the reference count any more.

Status: progress has been made replacing these cases, but there is an
infinite number of such cases.
"""

import _json, weakref

class Ctx1(object):
    encoding = "utf8"
    strict = None
    object_hook = None
    object_pairs_hook = None
    parse_float = None
    parse_int = None
    parse_constant = None

class Foo(unicode):
    pass

def delete_me(*args):
    print scanner.encoding.__dict__

class Ctx2(Ctx1):
    @property
    def encoding(self):
        global wref
        f = Foo("utf8")
        f.abc = globals()
        wref = weakref.ref(f, delete_me)
        return f

scanner = _json.make_scanner(Ctx1())
scanner.__init__(Ctx2())
 <INSERT_END> <|endoftext|> """
General example for an attack against code like this:

    Py_DECREF(obj->attr); obj->attr = ...;

here in Module/_json.c:scanner_init().

Explanation: if the first Py_DECREF() calls either a __del__ or a
weakref callback, it will run while the 'obj' appears to have in
'obj->attr' still the old reference to the object, but not holding
the reference count any more.

Status: progress has been made replacing these cases, but there is an
infinite number of such cases.
"""

import _json, weakref

class Ctx1(object):
    encoding = "utf8"
    strict = None
    object_hook = None
    object_pairs_hook = None
    parse_float = None
    parse_int = None
    parse_constant = None

class Foo(unicode):
    pass

def delete_me(*args):
    print scanner.encoding.__dict__

class Ctx2(Ctx1):
    @property
    def encoding(self):
        global wref
        f = Foo("utf8")
        f.abc = globals()
        wref = weakref.ref(f, delete_me)
        return f

scanner = _json.make_scanner(Ctx1())
scanner.__init__(Ctx2())

Prompt: Add a crasher for the documented issue of calling "Py_DECREF(self->xxx)";


"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin

import requests

from src.authorization_tokens import authorization
from src.parsing import parse_token_clause

def post_data_to_user_intent_endpoint(context, payload=None):
    """Post data into the REST API endpoint for user-intent."""
    url = "/api/v1/user-intent"

    if payload is not None:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context),
                                         json=payload)
    else:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context))

@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
    """Post no payload into the REST API endpoint for user-intent."""
    post_data_to_user_intent_endpoint(context)

@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
    """Post empty into the REST API endpoint for user-intent."""
    payload = {}
    post_data_to_user_intent_endpoint(context, payload)

Response:
<REPLACE_OLD> data=payload)
 <REPLACE_NEW> json=payload)
 <REPLACE_END> <|endoftext|> """Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin

import requests

from src.authorization_tokens import authorization
from src.parsing import parse_token_clause

def post_data_to_user_intent_endpoint(context, payload=None):
    """Post data into the REST API endpoint for user-intent."""
    url = "/api/v1/user-intent"

    if payload is not None:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context),
                                         json=payload)
    else:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context))

@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
    """Post no payload into the REST API endpoint for user-intent."""
    post_data_to_user_intent_endpoint(context)

@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
    """Post empty into the REST API endpoint for user-intent."""
    payload = {}
    post_data_to_user_intent_endpoint(context, payload)

Prompt:
Fix - send JSON to the API, not raw data

"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin

import requests

from src.authorization_tokens import authorization
from src.parsing import parse_token_clause

def post_data_to_user_intent_endpoint(context, payload=None):
    """Post data into the REST API endpoint for user-intent."""
    url = "/api/v1/user-intent"

    if payload is not None:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context),
                                         data=payload)
    else:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context))

@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
    """Post no payload into the REST API endpoint for user-intent."""
    post_data_to_user_intent_endpoint(context)

@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
    """Post empty into the REST API endpoint for user-intent."""
    payload = {}
    post_data_to_user_intent_endpoint(context, payload)


from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)

    def test_home_page_returns_correct_html(self):
        expected_html = render_to_string('home.html')
        request = HttpRequest()
        response = home(request)
        actual_html = response.content.decode()
        self.assertEqual(actual_html, expected_html)

Add test for home page html content

Add test for home page html content

Response:
<INSERT> django.http import HttpRequest
from django.template.loader import render_to_string
from <INSERT_END> <REPLACE_OLD> home)
 <REPLACE_NEW> home)

    def test_home_page_returns_correct_html(self):
        expected_html = render_to_string('home.html')
        request = HttpRequest()
        response = home(request)
        actual_html = response.content.decode()
        self.assertEqual(actual_html, expected_html)
 <REPLACE_END> <|endoftext|> from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)

    def test_home_page_returns_correct_html(self):
        expected_html = render_to_string('home.html')
        request = HttpRequest()
        response = home(request)
        actual_html = response.content.decode()
        self.assertEqual(actual_html, expected_html)

Prompt:
Add test for home page html content

from django.core.urlresolvers import resolve
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)


from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from jsonfield import JSONField

@python_2_unicode_compatible
class KeyValue(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, db_index=True)
    value = JSONField()

    def __str__(self):
        return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

Response:
<REPLACE_OLD> models

from <REPLACE_NEW> models
from django.utils.encoding import python_2_unicode_compatible

from <REPLACE_END> <REPLACE_OLD> JSONField

class <REPLACE_NEW> JSONField

@python_2_unicode_compatible
class <REPLACE_END> <DELETE> __unicode__(self):
        return u'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

    def <DELETE_END> <|endoftext|> from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from jsonfield import JSONField

@python_2_unicode_compatible
class KeyValue(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, db_index=True)
    value = JSONField()

    def __str__(self):
        return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

Prompt:
Use @python_2_unicode_compatible rather than repeating methods

from django.contrib.auth.models import Group
from django.db import models

from jsonfield import JSONField

class KeyValue(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, db_index=True)
    value = JSONField()

    def __unicode__(self):
        return u'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

    def __str__(self):
        return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)


"""yolk

Author: Rob Cakebread <cakebread at gmail>

License  : BSD

"""

__version__ = '0.6.2'

Increment patch version to 0.6.2

Increment patch version to 0.6.2

Response:
<REPLACE_OLD> '0.6.1'
 <REPLACE_NEW> '0.6.2'
 <REPLACE_END> <|endoftext|> """yolk

Author: Rob Cakebread <cakebread at gmail>

License  : BSD

"""

__version__ = '0.6.2'

Prompt:
Increment patch version to 0.6.2

"""yolk

Author: Rob Cakebread <cakebread at gmail>

License  : BSD

"""

__version__ = '0.6.1'


from django.conf import settings
from django.core.urlresolvers import reverse

TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"

# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY

# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD

# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL

Response:
<REPLACE_OLD>
from <REPLACE_NEW> from <REPLACE_END> <REPLACE_OLD> reverse
from helios.views import election_shortcut

TEMPLATE_BASE <REPLACE_NEW> reverse

TEMPLATE_BASE <REPLACE_END> <|endoftext|> from django.conf import settings
from django.core.urlresolvers import reverse

TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"

# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY

# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD

# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL

Prompt:
Remove unused import causing deprecation warning

Warning in the form:
RemovedInDjango19Warning: "ModelXYZ" doesn't declare an explicit app_label
Apparently this happens because it tries to import models before app
configuration runs

from django.conf import settings
from django.core.urlresolvers import reverse
from helios.views import election_shortcut

TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"

# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY

# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD

# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL


import pytest

import wee_slack

@pytest.mark.parametrize("text", [
    """
    * an item
    * another item
    """,
    "* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
    assert wee_slack.render_formatting(text) == text

Add tests for no formatting cases

Add tests for no formatting cases

Response:
<INSERT> import pytest

import wee_slack

@pytest.mark.parametrize("text", [
 <INSERT_END> <INSERT>   """
    * an item
    * another item
    """,
    "* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
    assert wee_slack.render_formatting(text) == text
 <INSERT_END> <|endoftext|> import pytest

import wee_slack

@pytest.mark.parametrize("text", [
    """
    * an item
    * another item
    """,
    "* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
    assert wee_slack.render_formatting(text) == text

Prompt: Add tests for no formatting cases


"""The WaveBlocks Project

This file is main script for running simulations with WaveBlocks.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import ParameterLoader

# Read the path for the configuration file we use for this simulation.
try:
    parametersfile = sys.argv[1]
except IndexError:
    raise ValueError("No configuration file given!")

print("Using configuration from file: " + parametersfile)

# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)

# Print the parameters that apply for this simulation
print(PA)

# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
    from WaveBlocksND import SimulationLoopFourier
    SL = SimulationLoopFourier(PA)

elif PA["algorithm"] == "hagedorn":
    from WaveBlocksND import SimulationLoopHagedorn
    SL = SimulationLoopHagedorn(PA)

elif PA["algorithm"] == "hagedorn_inhomog":
    from WaveBlocksND import SimulationLoopHagedornInhomogeneous
    SL = SimulationLoopHagedornInhomogeneous(PA)

# TODO: Add new algorithms here

else:
    raise ValueError("Invalid propagator algorithm.")

# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()

# End the simulation, close output files etc.
SL.end_simulation()

Response:
<REPLACE_OLD> SimulationLoopHagedorn(PA)

# <REPLACE_NEW> SimulationLoopHagedorn(PA)

elif PA["algorithm"] == "hagedorn_inhomog":
    from WaveBlocksND import SimulationLoopHagedornInhomogeneous
    SL = SimulationLoopHagedornInhomogeneous(PA)

# <REPLACE_END> <|endoftext|> """The WaveBlocks Project

This file is main script for running simulations with WaveBlocks.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import ParameterLoader

# Read the path for the configuration file we use for this simulation.
try:
    parametersfile = sys.argv[1]
except IndexError:
    raise ValueError("No configuration file given!")

print("Using configuration from file: " + parametersfile)

# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)

# Print the parameters that apply for this simulation
print(PA)

# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
    from WaveBlocksND import SimulationLoopFourier
    SL = SimulationLoopFourier(PA)

elif PA["algorithm"] == "hagedorn":
    from WaveBlocksND import SimulationLoopHagedorn
    SL = SimulationLoopHagedorn(PA)

elif PA["algorithm"] == "hagedorn_inhomog":
    from WaveBlocksND import SimulationLoopHagedornInhomogeneous
    SL = SimulationLoopHagedornInhomogeneous(PA)

# TODO: Add new algorithms here

else:
    raise ValueError("Invalid propagator algorithm.")

# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()

# End the simulation, close output files etc.
SL.end_simulation()

Prompt:
Enable inhomogeneous packets in the main simulation runner

"""The WaveBlocks Project

This file is main script for running simulations with WaveBlocks.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import ParameterLoader

# Read the path for the configuration file we use for this simulation.
try:
    parametersfile = sys.argv[1]
except IndexError:
    raise ValueError("No configuration file given!")

print("Using configuration from file: " + parametersfile)

# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)

# Print the parameters that apply for this simulation
print(PA)

# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
    from WaveBlocksND import SimulationLoopFourier
    SL = SimulationLoopFourier(PA)

elif PA["algorithm"] == "hagedorn":
    from WaveBlocksND import SimulationLoopHagedorn
    SL = SimulationLoopHagedorn(PA)

# TODO: Add new algorithms here

else:
    raise ValueError("Invalid propagator algorithm.")

# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()

# End the simulation, close output files etc.
SL.end_simulation()


import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint

def multi_size(max_len):

	for n in [2**(n+1) for n in range(max_len)]:
		print 'Array size: %d' % n
		arr = [randint(0, 2**max_len) for n in range(n)]

		current_time = time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
		print 'Merge sort: %f' % (time.time() - current_time)

		current_time = time.time()
		quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
		print 'Quicksort: %f' % (time.time() - current_time)
		print '-----------------'

def fixed_time(sec, length):

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		mergesort.merge_sort.sort(arr)
		count += 1

	print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		quicksort.quicksort.sort(arr, 0, length)
		count += 1

	print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)

if __name__ == '__main__':

	if len(sys.argv) > 2:
		fixed_time(int(sys.argv[1]), int(sys.argv[2]))
	else:
		multi_size(int(sys.argv[1]))

Response:
<REPLACE_OLD> main(max_len):

	for <REPLACE_NEW> multi_size(max_len):

	for <REPLACE_END> <REPLACE_OLD> time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
		print <REPLACE_NEW> time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
		print <REPLACE_END> <REPLACE_OLD> len(arr)))
		print <REPLACE_NEW> n+1), n+1)
		print <REPLACE_END> <REPLACE_OLD> '-----------------'

if <REPLACE_NEW> '-----------------'

def fixed_time(sec, length):

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		mergesort.merge_sort.sort(arr)
		count += 1

	print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		quicksort.quicksort.sort(arr, 0, length)
		count += 1

	print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)

if <REPLACE_END> <REPLACE_OLD> '__main__':

	try:
		max_len = int(sys.argv[1])
	except (IndexError, ValueError):
		print 'Format: python sorting_test.py <log(max input)>'

	main(max_len) <REPLACE_NEW> '__main__':

	if len(sys.argv) > 2:
		fixed_time(int(sys.argv[1]), int(sys.argv[2]))
	else:
		multi_size(int(sys.argv[1])) <REPLACE_END> <|endoftext|> import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint

def multi_size(max_len):

	for n in [2**(n+1) for n in range(max_len)]:
		print 'Array size: %d' % n
		arr = [randint(0, 2**max_len) for n in range(n)]

		current_time = time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
		print 'Merge sort: %f' % (time.time() - current_time)

		current_time = time.time()
		quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
		print 'Quicksort: %f' % (time.time() - current_time)
		print '-----------------'

def fixed_time(sec, length):

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		mergesort.merge_sort.sort(arr)
		count += 1

	print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		quicksort.quicksort.sort(arr, 0, length)
		count += 1

	print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)

if __name__ == '__main__':

	if len(sys.argv) > 2:
		fixed_time(int(sys.argv[1]), int(sys.argv[2]))
	else:
		multi_size(int(sys.argv[1]))

Prompt:
Allow comparison within a fixed time period

To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.

import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint

def main(max_len):

	for n in [2**(n+1) for n in range(max_len)]:
		print 'Array size: %d' % n
		arr = [randint(0, 2**max_len) for n in range(n)]

		current_time = time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
		print 'Merge sort: %f' % (time.time() - current_time)

		current_time = time.time()
		quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
		print 'Quicksort: %f' % (time.time() - current_time)
		print '-----------------'

if __name__ == '__main__':

	try:
		max_len = int(sys.argv[1])
	except (IndexError, ValueError):
		print 'Format: python sorting_test.py <log(max input)>'

	main(max_len)


"""
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip

class GeoLocator(object):
    """Geo locate IP addresses using the MaxMind database"""
    def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
                 ipv6_geo_path='/usr/share/GeoIP/GeoIPv6.dat'):
        self.ipv4_geo_path = ipv4_geo_path
        self.ipv6_geo_path = ipv6_geo_path

    @property
    def ipv4_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv4 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv4_geo'):
            self._ipv4_geo = pygeoip.GeoIP(filename=self.ipv4_geo_path, flags=1)
        return self._ipv4_geo

    @property
    def ipv6_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv6 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv6_geo'):
            self._ipv6_geo = pygeoip.GeoIP(filename=self.ipv6_geo_path, flags=1)
        return self._ipv6_geo

    def _check_if_ipv6(self, ip_address):
        """Return true if given ip_address is IPv6, false otherwise"""
        try:
            # socket.inet_pton throws an exception if it isn't a valid address
            # of the stated address class
            socket.inet_pton(socket.AF_INET6, ip_address)
            return True
        except:
            return False

    def find_country(self, ip_address):
        """Return best guess of country in which this IP address resides"""
        if self._check_if_ipv6(ip_address):
            return self.ipv6_geo.country_code_by_addr(ip_address)
        else:
            return self.ipv4_geo.country_code_by_addr(ip_address)

Response:
<REPLACE_OLD> #Using MaxMind, so import pygeoip
import pygeoip

def geolocate(ip_addresses):

  #Read <REPLACE_NEW> """
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip

class GeoLocator(object):
    """Geo locate IP addresses using the MaxMind database"""
    def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
                 ipv6_geo_path='/usr/share/GeoIP/GeoIPv6.dat'):
        self.ipv4_geo_path = ipv4_geo_path
        self.ipv6_geo_path = ipv6_geo_path

    @property
    def ipv4_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv4 geolocation data.

        The data is stored <REPLACE_END> <REPLACE_OLD> files, storing <REPLACE_NEW> memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv4_geo'):
            self._ipv4_geo = pygeoip.GeoIP(filename=self.ipv4_geo_path, flags=1)
        return self._ipv4_geo

    @property
    def ipv6_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv6 geolocation data.

        The data is stored <REPLACE_END> <REPLACE_OLD> memory for speed
  ip4_geo <REPLACE_NEW> memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv6_geo'):
            self._ipv6_geo <REPLACE_END> <REPLACE_OLD> pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIP.dat", flags = 1)
  ip6_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIPv6.dat", flags = 1)

  #Check type
  <REPLACE_NEW> pygeoip.GeoIP(filename=self.ipv6_geo_path, flags=1)
        return self._ipv6_geo

    def _check_if_ipv6(self, ip_address):
        """Return true <REPLACE_END> <REPLACE_OLD> not(isinstance(ip_addresses,list)):
    ip_addresses = [ip_addresses]

  #Construct output list
  output = []

  #For each entry <REPLACE_NEW> given ip_address is IPv6, false otherwise"""
        try:
            # socket.inet_pton throws an exception if it isn't a valid address
            # of the stated address class
            socket.inet_pton(socket.AF_INET6, ip_address)
            return True
        except:
            return False

    def find_country(self, ip_address):
        """Return best guess of country <REPLACE_END> <REPLACE_OLD> the input list, retrieve the country code and add it to the output object
  for entry in ip_addresses:

    if(bool(re.search(":",entry))):

      try:

        output.append(ip6_geo.country_code_by_addr(entry))

      except:

        output.append("Invalid")

 <REPLACE_NEW> which this IP address resides"""
        if self._check_if_ipv6(ip_address):
            return self.ipv6_geo.country_code_by_addr(ip_address)
     <REPLACE_END> <REPLACE_OLD>
      try:

        output.append(ip4_geo.country_code_by_addr(entry))

      except:

        output.append("Invalid")

  #Return
  return output
 <REPLACE_NEW>       return self.ipv4_geo.country_code_by_addr(ip_address)
 <REPLACE_END> <|endoftext|> """
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip

class GeoLocator(object):
    """Geo locate IP addresses using the MaxMind database"""
    def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
                 ipv6_geo_path='/usr/share/GeoIP/GeoIPv6.dat'):
        self.ipv4_geo_path = ipv4_geo_path
        self.ipv6_geo_path = ipv6_geo_path

    @property
    def ipv4_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv4 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv4_geo'):
            self._ipv4_geo = pygeoip.GeoIP(filename=self.ipv4_geo_path, flags=1)
        return self._ipv4_geo

    @property
    def ipv6_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv6 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv6_geo'):
            self._ipv6_geo = pygeoip.GeoIP(filename=self.ipv6_geo_path, flags=1)
        return self._ipv6_geo

    def _check_if_ipv6(self, ip_address):
        """Return true if given ip_address is IPv6, false otherwise"""
        try:
            # socket.inet_pton throws an exception if it isn't a valid address
            # of the stated address class
            socket.inet_pton(socket.AF_INET6, ip_address)
            return True
        except:
            return False

    def find_country(self, ip_address):
        """Return best guess of country in which this IP address resides"""
        if self._check_if_ipv6(ip_address):
            return self.ipv6_geo.country_code_by_addr(ip_address)
        else:
            return self.ipv4_geo.country_code_by_addr(ip_address)

Prompt:
Move the Geo Location stuff into a class

#Using MaxMind, so import pygeoip
import pygeoip

def geolocate(ip_addresses):

  #Read in files, storing in memory for speed
  ip4_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIP.dat", flags = 1)
  ip6_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIPv6.dat", flags = 1)

  #Check type
  if not(isinstance(ip_addresses,list)):
    ip_addresses = [ip_addresses]

  #Construct output list
  output = []

  #For each entry in the input list, retrieve the country code and add it to the output object
  for entry in ip_addresses:

    if(bool(re.search(":",entry))):

      try:

        output.append(ip6_geo.country_code_by_addr(entry))

      except:

        output.append("Invalid")

    else:

      try:

        output.append(ip4_geo.country_code_by_addr(entry))

      except:

        output.append("Invalid")

  #Return
  return output


from flask import current_app
from functools import wraps
from hashlib import md5

from changes.ext.redis import UnableToGetLock
from changes.config import redis

def lock(func):
    @wraps(func)
    def wrapped(**kwargs):
        key = '{0}:{1}:{2}'.format(
            func.__module__,
            func.__name__,
            md5(
                '&'.join('{0}={1}'.format(k, repr(v))
                for k, v in sorted(kwargs.iteritems()))
            ).hexdigest()
        )
        try:
            with redis.lock(key, timeout=1, expire=300, nowait=True):
                return func(**kwargs)
        except UnableToGetLock:
            current_app.logger.warn('Unable to get lock for %s', key)

    return wrapped

Use __module__ to make @lock unique

Response:
<REPLACE_OLD> '{0}:{1}'.format(
 <REPLACE_NEW> '{0}:{1}:{2}'.format(
            func.__module__,
 <REPLACE_END> <|endoftext|> from flask import current_app
from functools import wraps
from hashlib import md5

from changes.ext.redis import UnableToGetLock
from changes.config import redis

def lock(func):
    @wraps(func)
    def wrapped(**kwargs):
        key = '{0}:{1}:{2}'.format(
            func.__module__,
            func.__name__,
            md5(
                '&'.join('{0}={1}'.format(k, repr(v))
                for k, v in sorted(kwargs.iteritems()))
            ).hexdigest()
        )
        try:
            with redis.lock(key, timeout=1, expire=300, nowait=True):
                return func(**kwargs)
        except UnableToGetLock:
            current_app.logger.warn('Unable to get lock for %s', key)

    return wrapped

Prompt:
Use __module__ to make @lock unique

Summary: Fixes T49428.

Test Plan:
Hard to test on changes_dev because it can't run both handlers (no
place to send notifications to), but this seems simple enough...

Reviewers: armooo, kylec

Reviewed By: kylec

Subscribers: changesbot, mkedia, jukka, vishal

Maniphest Tasks: T49428

Differential Revision: https://tails.corp.dropbox.com/D122408

from flask import current_app
from functools import wraps
from hashlib import md5

from changes.ext.redis import UnableToGetLock
from changes.config import redis

def lock(func):
    @wraps(func)
    def wrapped(**kwargs):
        key = '{0}:{1}'.format(
            func.__name__,
            md5(
                '&'.join('{0}={1}'.format(k, repr(v))
                for k, v in sorted(kwargs.iteritems()))
            ).hexdigest()
        )
        try:
            with redis.lock(key, timeout=1, expire=300, nowait=True):
                return func(**kwargs)
        except UnableToGetLock:
            current_app.logger.warn('Unable to get lock for %s', key)

    return wrapped


from setuptools import setup, find_packages

setup(
    name='django-flatblocks',
    version='0.9',
    description='django-flatblocks acts like django.contrib.flatpages but '
                'for parts of a page; like an editable help box you want '
                'show alongside the main content.',
    long_description=open('README.rst').read(),
    keywords='django apps',
    license='New BSD License',
    author='Horst Gutmann',
    author_email='zerok@zerokspot.com',
    url='http://github.com/zerok/django-flatblocks/',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Plugins',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    packages=find_packages('flatblocks'),
    package_data={
        'flatblocks': [
            'templates/flatblocks/*.html',
            'locale/*/*/*.mo',
            'locale/*/*/*.po',
        ]
    },
    zip_safe=False,
    requires = [
        'Django (>=1.4)',
    ],
)

Remove kws: does not exist

Remove kws: does not exist

Response:
<REPLACE_OLD> ],
    **kws
)
 <REPLACE_NEW> ],
)
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='django-flatblocks',
    version='0.9',
    description='django-flatblocks acts like django.contrib.flatpages but '
                'for parts of a page; like an editable help box you want '
                'show alongside the main content.',
    long_description=open('README.rst').read(),
    keywords='django apps',
    license='New BSD License',
    author='Horst Gutmann',
    author_email='zerok@zerokspot.com',
    url='http://github.com/zerok/django-flatblocks/',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Plugins',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    packages=find_packages('flatblocks'),
    package_data={
        'flatblocks': [
            'templates/flatblocks/*.html',
            'locale/*/*/*.mo',
            'locale/*/*/*.po',
        ]
    },
    zip_safe=False,
    requires = [
        'Django (>=1.4)',
    ],
)

Prompt:
Remove kws: does not exist

from setuptools import setup, find_packages

setup(
    name='django-flatblocks',
    version='0.9',
    description='django-flatblocks acts like django.contrib.flatpages but '
                'for parts of a page; like an editable help box you want '
                'show alongside the main content.',
    long_description=open('README.rst').read(),
    keywords='django apps',
    license='New BSD License',
    author='Horst Gutmann',
    author_email='zerok@zerokspot.com',
    url='http://github.com/zerok/django-flatblocks/',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Plugins',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    packages=find_packages('flatblocks'),
    package_data={
        'flatblocks': [
            'templates/flatblocks/*.html',
            'locale/*/*/*.mo',
            'locale/*/*/*.po',
        ]
    },
    zip_safe=False,
    requires = [
        'Django (>=1.4)',
    ],
    **kws
)


# Copyright (c) 2015, Daniele Venzano
#
# 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 flask import Blueprint

web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

import zoe_web.web.start
import zoe_web.web.status
import zoe_web.web.applications

from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION

@web_bp.context_processor
def inject_version():
    return {
        'zoe_version': ZOE_VERSION,
        'zoe_api_version': ZOE_API_VERSION,
    }

Fix version in web pages

Fix version in web pages

Response:
<REPLACE_OLD> 'zoe_lib_version': <REPLACE_NEW> 'zoe_version': <REPLACE_END> <|endoftext|> # Copyright (c) 2015, Daniele Venzano
#
# 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 flask import Blueprint

web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

import zoe_web.web.start
import zoe_web.web.status
import zoe_web.web.applications

from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION

@web_bp.context_processor
def inject_version():
    return {
        'zoe_version': ZOE_VERSION,
        'zoe_api_version': ZOE_API_VERSION,
    }

Prompt:
Fix version in web pages

# Copyright (c) 2015, Daniele Venzano
#
# 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 flask import Blueprint

web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

import zoe_web.web.start
import zoe_web.web.status
import zoe_web.web.applications

from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION

@web_bp.context_processor
def inject_version():
    return {
        'zoe_lib_version': ZOE_VERSION,
        'zoe_api_version': ZOE_API_VERSION,
    }


import requests, json, urllib

SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'

def getCOREMentions(identifier, **kwargs):
    """Return the number of mentions in CORE and a descriptor, as a tuple.

    Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
    params = {
        'api_key': API_KEY,
        'format': 'json',
    }
    params.update(kwargs)

    response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
    response.raise_for_status()

    results = response.json()
    score = results['ListRecords'][0]['total_hits']

    return score, 'mentions in Open Access articles (via http://core.ac.uk/)'

Response:
<REPLACE_OLD> 'http://core.ac.uk:80/api-v2/articles/search/'
API_KEY <REPLACE_NEW> 'http://core.kmi.open.ac.uk/api/search/'
API_KEY <REPLACE_END> <REPLACE_OLD> 'apiKey': <REPLACE_NEW> 'api_key': <REPLACE_END> <REPLACE_OLD> 'metadata': 'false',
        'pageSize': 100,
        'page': 1
 <REPLACE_NEW> 'format': 'json',
 <REPLACE_END> <REPLACE_OLD> response.json()

 <REPLACE_NEW> response.json()
    score = results['ListRecords'][0]['total_hits']

 <REPLACE_END> <REPLACE_OLD> (len(results['data'] or []),
            <REPLACE_NEW> score, <REPLACE_END> <REPLACE_OLD> http://core.ac.uk/)')
 <REPLACE_NEW> http://core.ac.uk/)'
 <REPLACE_END> <|endoftext|> import requests, json, urllib

SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'

def getCOREMentions(identifier, **kwargs):
    """Return the number of mentions in CORE and a descriptor, as a tuple.

    Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
    params = {
        'api_key': API_KEY,
        'format': 'json',
    }
    params.update(kwargs)

    response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
    response.raise_for_status()

    results = response.json()
    score = results['ListRecords'][0]['total_hits']

    return score, 'mentions in Open Access articles (via http://core.ac.uk/)'

Prompt:
Switch to using the v1 API to get total hits.

import requests, json, urllib

SEARCH_URL = 'http://core.ac.uk:80/api-v2/articles/search/'
API_KEY = 'FILL THIS IN'

def getCOREMentions(identifier, **kwargs):
    """Return the number of mentions in CORE and a descriptor, as a tuple.

    Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
    params = {
        'apiKey': API_KEY,
        'metadata': 'false',
        'pageSize': 100,
        'page': 1
    }
    params.update(kwargs)

    response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
    response.raise_for_status()

    results = response.json()

    return (len(results['data'] or []),
            'mentions in Open Access articles (via http://core.ac.uk/)')


import os, logging
from flask import Flask
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.debug("\nConfiguration\n%s\n" % app.config)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

# Validate config
for property_to_check in ['CASEWORK_URL', 'CHECK_URL']:
	if not app.config[property_to_check]:
		raise Exception('Missing %r configuation property.' % (property_to_check))

Set config logging in init to debug

Set config logging in init to debug

Response:
<REPLACE_OLD> Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.info("\nConfiguration\n%s\n" <REPLACE_NEW> Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.debug("\nConfiguration\n%s\n" <REPLACE_END> <REPLACE_OLD> config
for <REPLACE_NEW> config
for <REPLACE_END> <REPLACE_OLD> (property_to_check))
	 <REPLACE_NEW> (property_to_check))

 <REPLACE_END> <|endoftext|> import os, logging
from flask import Flask
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.debug("\nConfiguration\n%s\n" % app.config)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

# Validate config
for property_to_check in ['CASEWORK_URL', 'CHECK_URL']:
	if not app.config[property_to_check]:
		raise Exception('Missing %r configuation property.' % (property_to_check))

Prompt:
Set config logging in init to debug

import os, logging
from flask import Flask
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.info("\nConfiguration\n%s\n" % app.config)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

# Validate config
for property_to_check in ['CASEWORK_URL', 'CHECK_URL']:
	if not app.config[property_to_check]:
		raise Exception('Missing %r configuation property.' % (property_to_check))


import logging
import logging.handlers

# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)

# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
                                                backupCount=7)
tfh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)

Response:
<REPLACE_OLD> backupCount=5)
tfh.setLevel(logging.DEBUG)

# <REPLACE_NEW> backupCount=7)
tfh.setLevel(logging.DEBUG)

# <REPLACE_END> <REPLACE_OLD> %(levelname)s: <REPLACE_NEW> [%(levelname)s] <REPLACE_END> <REPLACE_OLD> %(levelname)s: %(message)s - %(name)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# <REPLACE_NEW> [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# <REPLACE_END> <|endoftext|> import logging
import logging.handlers

# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)

# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
                                                backupCount=7)
tfh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)

Prompt:
Update log output so that it works more nicely with ELK

import logging
import logging.handlers

# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)

# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
                                                backupCount=5)
tfh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s: %(message)s - %(name)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)


# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017

import os.path

# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
	os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js'

PYGMENTS_STYLE = 'default'

def get_pygments_stylesheet(selector, style=None):
	if style is None:
		style = PYGMENTS_STYLE
	if style == '':
		return ''
	try:
		from pygments.formatters import HtmlFormatter
	except ImportError:
		return ''
	else:
		return HtmlFormatter(style=style).get_style_defs(selector) + '\n'

def get_mathjax_url(webenv):
	if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
		return MATHJAX_LOCAL_URL
	else:
		return MATHJAX_WEB_URL

Update MathJax URL to 2.7.1

Update MathJax URL to 2.7.1

Response:
<REPLACE_OLD> 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js'

PYGMENTS_STYLE <REPLACE_NEW> 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js'

PYGMENTS_STYLE <REPLACE_END> <|endoftext|> # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017

import os.path

# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
	os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js'

PYGMENTS_STYLE = 'default'

def get_pygments_stylesheet(selector, style=None):
	if style is None:
		style = PYGMENTS_STYLE
	if style == '':
		return ''
	try:
		from pygments.formatters import HtmlFormatter
	except ImportError:
		return ''
	else:
		return HtmlFormatter(style=style).get_style_defs(selector) + '\n'

def get_mathjax_url(webenv):
	if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
		return MATHJAX_LOCAL_URL
	else:
		return MATHJAX_WEB_URL

Prompt:
Update MathJax URL to 2.7.1

# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017

import os.path

# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
	os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js'

PYGMENTS_STYLE = 'default'

def get_pygments_stylesheet(selector, style=None):
	if style is None:
		style = PYGMENTS_STYLE
	if style == '':
		return ''
	try:
		from pygments.formatters import HtmlFormatter
	except ImportError:
		return ''
	else:
		return HtmlFormatter(style=style).get_style_defs(selector) + '\n'

def get_mathjax_url(webenv):
	if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
		return MATHJAX_LOCAL_URL
	else:
		return MATHJAX_WEB_URL


from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
        adzerk_srs = g.live_config.get("adzerk_srs")
        in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs
        if adzerk_all_the_things or in_adzerk_sr:
            url_key = "adzerk_https_url" if c.secure else "adzerk_url"
            site_name = getattr(c.site, "analytics_name", c.site.name)
            self.ad_url = g.config[url_key].format(
                subreddit=quote(site_name.lower()),
                origin=c.request_origin,
            )
            self.frame_id = "ad_main"

Response:
<INSERT> site_name = getattr(c.site, "analytics_name", c.site.name)
            <INSERT_END> <REPLACE_OLD> subreddit=quote(c.site.name.lower()),
 <REPLACE_NEW> subreddit=quote(site_name.lower()),
 <REPLACE_END> <|endoftext|> from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
        adzerk_srs = g.live_config.get("adzerk_srs")
        in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs
        if adzerk_all_the_things or in_adzerk_sr:
            url_key = "adzerk_https_url" if c.secure else "adzerk_url"
            site_name = getattr(c.site, "analytics_name", c.site.name)
            self.ad_url = g.config[url_key].format(
                subreddit=quote(site_name.lower()),
                origin=c.request_origin,
            )
            self.frame_id = "ad_main"

Prompt:
Use analytics name for subreddits if available.

This allows a catch-all for multis to be used.

from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
        adzerk_srs = g.live_config.get("adzerk_srs")
        in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs
        if adzerk_all_the_things or in_adzerk_sr:
            url_key = "adzerk_https_url" if c.secure else "adzerk_url"
            self.ad_url = g.config[url_key].format(
                subreddit=quote(c.site.name.lower()),
                origin=c.request_origin,
            )
            self.frame_id = "ad_main"


# Run the _testcapi module tests (tests for the Python/C API):  by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.

import sys
import test_support
import _testcapi

for name in dir(_testcapi):
    if name.startswith('test_'):
        test = getattr(_testcapi, name)
        if test_support.verbose:
            print "internal", name
        try:
            test()
        except _testcapi.error:
            raise test_support.TestFailed, sys.exc_info()[1]

Response:
<REPLACE_OLD> _test <REPLACE_NEW> _testcapi <REPLACE_END> <|endoftext|> # Run the _testcapi module tests (tests for the Python/C API):  by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.

import sys
import test_support
import _testcapi

for name in dir(_testcapi):
    if name.startswith('test_'):
        test = getattr(_testcapi, name)
        if test_support.verbose:
            print "internal", name
        try:
            test()
        except _testcapi.error:
            raise test_support.TestFailed, sys.exc_info()[1]

Prompt:
Fix typo in comment (the module is now called _testcapi, not _test).

# Run the _testcapi module tests (tests for the Python/C API):  by defn,
# these are all functions _test exports whose name begins with 'test_'.

import sys
import test_support
import _testcapi

for name in dir(_testcapi):
    if name.startswith('test_'):
        test = getattr(_testcapi, name)
        if test_support.verbose:
            print "internal", name
        try:
            test()
        except _testcapi.error:
            raise test_support.TestFailed, sys.exc_info()[1]


import argparse
import hashlib
import logging
import os

import yaml

from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify

log = logging.getLogger("mklocale")

def cmdline(argv):
    logging.basicConfig(level=logging.INFO)
    ap = argparse.ArgumentParser()
    ap.add_argument("config")
    args = ap.parse_args()

    try:
        import requests_cache
        requests_cache.install_cache(
            os.path.realpath('./mklocale.%s.cache' % hashlib.md5(args.config).hexdigest()),
            expire_after=86400
        )
    except ImportError:
        pass
    os.chdir(os.path.dirname(args.config))
    with open(args.config, "r") as infp:
        config = yaml.safe_load(infp)
    catalogs = []
    for tx_config in listify(config.get("transifex")):
        catalogs.extend(transifex.read_catalogs(tx_config))
    for merged_catalog in merge_by_language(catalogs):
        targets = [
            t.format(lang=merged_catalog.locale)
            for t
            in listify(config["target"])
        ]
        for target_file in targets:
            write_catalog(target_file, merged_catalog)

Add optional use of requests_cache

Add optional use of requests_cache

Response:
<REPLACE_OLD> logging

import <REPLACE_NEW> hashlib
import logging
import os

import <REPLACE_END> <REPLACE_OLD> ap.parse_args()
 <REPLACE_NEW> ap.parse_args()

    try:
        import requests_cache
        requests_cache.install_cache(
            os.path.realpath('./mklocale.%s.cache' % hashlib.md5(args.config).hexdigest()),
            expire_after=86400
        )
    except ImportError:
        pass
    os.chdir(os.path.dirname(args.config))
 <REPLACE_END> <|endoftext|> import argparse
import hashlib
import logging
import os

import yaml

from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify

log = logging.getLogger("mklocale")

def cmdline(argv):
    logging.basicConfig(level=logging.INFO)
    ap = argparse.ArgumentParser()
    ap.add_argument("config")
    args = ap.parse_args()

    try:
        import requests_cache
        requests_cache.install_cache(
            os.path.realpath('./mklocale.%s.cache' % hashlib.md5(args.config).hexdigest()),
            expire_after=86400
        )
    except ImportError:
        pass
    os.chdir(os.path.dirname(args.config))
    with open(args.config, "r") as infp:
        config = yaml.safe_load(infp)
    catalogs = []
    for tx_config in listify(config.get("transifex")):
        catalogs.extend(transifex.read_catalogs(tx_config))
    for merged_catalog in merge_by_language(catalogs):
        targets = [
            t.format(lang=merged_catalog.locale)
            for t
            in listify(config["target"])
        ]
        for target_file in targets:
            write_catalog(target_file, merged_catalog)

Prompt:
Add optional use of requests_cache

import argparse
import logging

import yaml

from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify

log = logging.getLogger("mklocale")

def cmdline(argv):
    logging.basicConfig(level=logging.INFO)
    ap = argparse.ArgumentParser()
    ap.add_argument("config")
    args = ap.parse_args()
    with open(args.config, "r") as infp:
        config = yaml.safe_load(infp)
    catalogs = []
    for tx_config in listify(config.get("transifex")):
        catalogs.extend(transifex.read_catalogs(tx_config))
    for merged_catalog in merge_by_language(catalogs):
        targets = [
            t.format(lang=merged_catalog.locale)
            for t
            in listify(config["target"])
        ]
        for target_file in targets:
            write_catalog(target_file, merged_catalog)


"""
acute models.
"""
from django.db.models import fields

from opal import models

class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatment(models.Treatment): pass
class Investigation(models.Investigation): pass

class Clerking(models.EpisodeSubrecord):
    _icon = 'fa fa-user'
    _title = 'Seen by'

    referrer   = fields.CharField(max_length=200, blank=True, null=True)
    clerked_by = fields.CharField(max_length=200, blank=True, null=True)
    consultant = fields.CharField(max_length=200, blank=True, null=True)

class Plan(models.EpisodeSubrecord):
    _is_singleton = True
    _icon = 'fa fa-list-ol'

    plan = fields.TextField(blank=True, null=True)

class Rescuscitation(models.EpisodeSubrecord):
    _icon = 'fa fa-warning'

    status = fields.CharField(max_length=200, blank=True, null=True)

class NursingNotes(models.EpisodeSubrecord):
    _icon = 'fa fa-info-circle'

    notes = fields.TextField(blank=True, null=True)

class DischargeDue(models.EpisodeSubrecord):
    _icon = 'fa fa-calendar'

    date = fields.DateField(blank=True, null=True)

Rename Clerking -> Seen by

Rename Clerking -> Seen by

closes #1

Response:
<INSERT>    _title = 'Seen by'
 <INSERT_END> <|endoftext|> """
acute models.
"""
from django.db.models import fields

from opal import models

class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatment(models.Treatment): pass
class Investigation(models.Investigation): pass

class Clerking(models.EpisodeSubrecord):
    _icon = 'fa fa-user'
    _title = 'Seen by'

    referrer   = fields.CharField(max_length=200, blank=True, null=True)
    clerked_by = fields.CharField(max_length=200, blank=True, null=True)
    consultant = fields.CharField(max_length=200, blank=True, null=True)

class Plan(models.EpisodeSubrecord):
    _is_singleton = True
    _icon = 'fa fa-list-ol'

    plan = fields.TextField(blank=True, null=True)

class Rescuscitation(models.EpisodeSubrecord):
    _icon = 'fa fa-warning'

    status = fields.CharField(max_length=200, blank=True, null=True)

class NursingNotes(models.EpisodeSubrecord):
    _icon = 'fa fa-info-circle'

    notes = fields.TextField(blank=True, null=True)

class DischargeDue(models.EpisodeSubrecord):
    _icon = 'fa fa-calendar'

    date = fields.DateField(blank=True, null=True)

Prompt:
Rename Clerking -> Seen by

closes #1

"""
acute models.
"""
from django.db.models import fields

from opal import models

class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatment(models.Treatment): pass
class Investigation(models.Investigation): pass

class Clerking(models.EpisodeSubrecord):
    _icon = 'fa fa-user'

    referrer   = fields.CharField(max_length=200, blank=True, null=True)
    clerked_by = fields.CharField(max_length=200, blank=True, null=True)
    consultant = fields.CharField(max_length=200, blank=True, null=True)

class Plan(models.EpisodeSubrecord):
    _is_singleton = True
    _icon = 'fa fa-list-ol'

    plan = fields.TextField(blank=True, null=True)

class Rescuscitation(models.EpisodeSubrecord):
    _icon = 'fa fa-warning'

    status = fields.CharField(max_length=200, blank=True, null=True)

class NursingNotes(models.EpisodeSubrecord):
    _icon = 'fa fa-info-circle'

    notes = fields.TextField(blank=True, null=True)

class DischargeDue(models.EpisodeSubrecord):
    _icon = 'fa fa-calendar'

    date = fields.DateField(blank=True, null=True)


#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""

import sys
import threading

from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run

def main():
    config = parse_arguments()
    set_default_repeat(config["ttr"])
    set_default_ttl(config["ttl"])
    set_default_duration(config["ttd"])
    message_queue = MessageQueue(config["limit"])
    module_class = load_module_from_conf(config)
    message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
    message_manager_thread = threading.Thread(target=message_manager.manage)
    message_manager_thread.daemon = True
    message_manager_thread.start()
    run(message_queue, config["ptl"])

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You killed me.")
        sys.exit(0)

Response:
<INSERT> core.moduleloader import load_module_from_conf
from <INSERT_END> <REPLACE_OLD> run

from modules.printer.printer import Printer # To remove, has to be done dynamically

def <REPLACE_NEW> run

def <REPLACE_END> <INSERT> module_class = load_module_from_conf(config)
    <INSERT_END> <REPLACE_OLD> Printer, <REPLACE_NEW> module_class, <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""

import sys
import threading

from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run

def main():
    config = parse_arguments()
    set_default_repeat(config["ttr"])
    set_default_ttl(config["ttl"])
    set_default_duration(config["ttd"])
    message_queue = MessageQueue(config["limit"])
    module_class = load_module_from_conf(config)
    message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
    message_manager_thread = threading.Thread(target=message_manager.manage)
    message_manager_thread.daemon = True
    message_manager_thread.start()
    run(message_queue, config["ptl"])

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You killed me.")
        sys.exit(0)

Prompt:
Update to load dynamically the module selected by user.

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""

import sys
import threading

from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run

from modules.printer.printer import Printer # To remove, has to be done dynamically

def main():
    config = parse_arguments()
    set_default_repeat(config["ttr"])
    set_default_ttl(config["ttl"])
    set_default_duration(config["ttd"])
    message_queue = MessageQueue(config["limit"])
    message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
    message_manager_thread = threading.Thread(target=message_manager.manage)
    message_manager_thread.daemon = True
    message_manager_thread.start()
    run(message_queue, config["ptl"])

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You killed me.")
        sys.exit(0)


#!flask/bin/python
from flask import Blueprint, jsonify

api_si = Blueprint('api_si', __name__)

@api_si.route("/stock_indicators")
def get_stock_indicators():
    return jsonify(stock_indicators=[
        {"username": "alice", "user_id": 1},
        {"username": "bob", "user_id": 2}
    ])

Implement blueprints on stock indicators

Response:
<INSERT> #!flask/bin/python
from flask import Blueprint, jsonify

api_si = Blueprint('api_si', __name__)

@api_si.route("/stock_indicators")
def get_stock_indicators():
 <INSERT_END> <INSERT>   return jsonify(stock_indicators=[
        {"username": "alice", "user_id": 1},
        {"username": "bob", "user_id": 2}
    ])
 <INSERT_END> <|endoftext|> #!flask/bin/python
from flask import Blueprint, jsonify

api_si = Blueprint('api_si', __name__)

@api_si.route("/stock_indicators")
def get_stock_indicators():
    return jsonify(stock_indicators=[
        {"username": "alice", "user_id": 1},
        {"username": "bob", "user_id": 2}
    ])

Prompt: Implement blueprints on stock indicators


#
# Copyright (c) SAS Institute Inc.
#
# 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.
#

"""
List image types
"""

from rbuild import pluginapi
from rbuild.pluginapi import command

class ListImageTypesCommand(command.ListCommand):
    help = "List image types"
    resource = "imagetypes"
    listFields = ("name", "description")

class ImageTypes(pluginapi.Plugin):
    name = 'imagetypes'

    def initialize(self):
        for command, subcommand, commandClass in (
                ('list', 'imagetypes', ListImageTypesCommand),
                ):
            cmd = self.handle.Commands.getCommandClass(command)
            cmd.registerSubCommand(subcommand, commandClass)

    def list(self):
        rb = self.handle.facade.rbuilder
        return [type for type in rb.getImageTypes() if type.name]

Response:
<REPLACE_OLD> ("description", "name")

class <REPLACE_NEW> ("name", "description")

class <REPLACE_END> <|endoftext|> #
# Copyright (c) SAS Institute Inc.
#
# 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.
#

"""
List image types
"""

from rbuild import pluginapi
from rbuild.pluginapi import command

class ListImageTypesCommand(command.ListCommand):
    help = "List image types"
    resource = "imagetypes"
    listFields = ("name", "description")

class ImageTypes(pluginapi.Plugin):
    name = 'imagetypes'

    def initialize(self):
        for command, subcommand, commandClass in (
                ('list', 'imagetypes', ListImageTypesCommand),
                ):
            cmd = self.handle.Commands.getCommandClass(command)
            cmd.registerSubCommand(subcommand, commandClass)

    def list(self):
        rb = self.handle.facade.rbuilder
        return [type for type in rb.getImageTypes() if type.name]

Prompt:
Swap order of name and description when listing image types

Uses the same order as target types, which puts the most important information,
the name, in front.

Refs APPENG-3419

#
# Copyright (c) SAS Institute Inc.
#
# 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.
#

"""
List image types
"""

from rbuild import pluginapi
from rbuild.pluginapi import command

class ListImageTypesCommand(command.ListCommand):
    help = "List image types"
    resource = "imagetypes"
    listFields = ("description", "name")

class ImageTypes(pluginapi.Plugin):
    name = 'imagetypes'

    def initialize(self):
        for command, subcommand, commandClass in (
                ('list', 'imagetypes', ListImageTypesCommand),
                ):
            cmd = self.handle.Commands.getCommandClass(command)
            cmd.registerSubCommand(subcommand, commandClass)

    def list(self):
        rb = self.handle.facade.rbuilder
        return [type for type in rb.getImageTypes() if type.name]