# stdlib
import os
from pathlib import Path
from pathlib import PosixPath
import subprocess

# Make a log directory
log_path = Path("logs")
log_path.mkdir(exist_ok=True)

# Get the github job name and create a directory for it
job_name = os.getenv("GITHUB_JOB")
job_path: PosixPath = log_path / job_name
job_path.mkdir(exist_ok=True)

# Get all the containers running (per job)
containers = (
    subprocess.check_output("docker ps --format '{{.Names}}'", shell=True)
    .decode("utf-8")
    .split()
)

# Loop through the container ids and create a log file for each in the job directory
for container in containers:
    # Get the container name

    container_name = container.replace("'", "")

    # Get the container logs
    container_logs = subprocess.check_output(
        "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT
    ).decode("utf-8")

    path = job_path / container_name
    path.write_text(container_logs, encoding="utf-8")

stored_files = list(job_path.iterdir())
for file in stored_files:
    print(file)
print("============Log export completed for job: ", job_name)

Set docker log encoding to utf-8

Set docker log encoding to utf-8

Response:
<REPLACE_OLD> path.write_text(container_logs)

stored_files <REPLACE_NEW> path.write_text(container_logs, encoding="utf-8")

stored_files <REPLACE_END> <|endoftext|> # stdlib
import os
from pathlib import Path
from pathlib import PosixPath
import subprocess

# Make a log directory
log_path = Path("logs")
log_path.mkdir(exist_ok=True)

# Get the github job name and create a directory for it
job_name = os.getenv("GITHUB_JOB")
job_path: PosixPath = log_path / job_name
job_path.mkdir(exist_ok=True)

# Get all the containers running (per job)
containers = (
    subprocess.check_output("docker ps --format '{{.Names}}'", shell=True)
    .decode("utf-8")
    .split()
)

# Loop through the container ids and create a log file for each in the job directory
for container in containers:
    # Get the container name

    container_name = container.replace("'", "")

    # Get the container logs
    container_logs = subprocess.check_output(
        "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT
    ).decode("utf-8")

    path = job_path / container_name
    path.write_text(container_logs, encoding="utf-8")

stored_files = list(job_path.iterdir())
for file in stored_files:
    print(file)
print("============Log export completed for job: ", job_name)

Prompt:
Set docker log encoding to utf-8

# stdlib
import os
from pathlib import Path
from pathlib import PosixPath
import subprocess

# Make a log directory
log_path = Path("logs")
log_path.mkdir(exist_ok=True)

# Get the github job name and create a directory for it
job_name = os.getenv("GITHUB_JOB")
job_path: PosixPath = log_path / job_name
job_path.mkdir(exist_ok=True)

# Get all the containers running (per job)
containers = (
    subprocess.check_output("docker ps --format '{{.Names}}'", shell=True)
    .decode("utf-8")
    .split()
)

# Loop through the container ids and create a log file for each in the job directory
for container in containers:
    # Get the container name

    container_name = container.replace("'", "")

    # Get the container logs
    container_logs = subprocess.check_output(
        "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT
    ).decode("utf-8")

    path = job_path / container_name
    path.write_text(container_logs)

stored_files = list(job_path.iterdir())
for file in stored_files:
    print(file)
print("============Log export completed for job: ", job_name)


Response:
<REPLACE_OLD> v

 <REPLACE_NEW> v

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

from django.conf import settings

from raygun4py import raygunprovider

class Provider(object):

    def __init__(self):
    	config = getattr(settings, 'RAYGUN4PY_CONFIG', {})
    	apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None))

        self.sender = raygunprovider.RaygunSender(apiKey, config=config)

    def process_exception(self, request, exception):
    	raygunRequest = self._mapRequest(request)

        self.sender.send_exception(exception=exception, request=raygunRequest)

    def _mapRequest(self, request):
        headers = request.META.items()
        _headers = dict()
        for k, v in headers:
            if not k.startswith('wsgi'):
                _headers[k] = v

        return {
            'hostName': request.get_host(),
            'url': request.path,
            'httpMethod': request.method,
            'ipAddress': request.META.get('REMOTE_ADDR', '?'),
            'queryString': dict((key, request.GET[key]) for key in request.GET),
            'form': dict((key, request.POST[key]) for key in request.POST),
            'headers': _headers,
            'rawData': request.body if hasattr(request, 'body') else getattr(request, 'raw_post_data', {})
        }

Prompt:
Fix RawPostDataException on request.body access.

Django's HttpRequest class doesn't like the `request.body` to be accessed more than one time.  Upon the second attempt to read from `request.body`, Django throws a `RawPostDataException`.  Since the previous code in this spot was conditional upon a `hasattr(request, 'body')` check, and because hasattr returns False when the attribute access raises an exception, raygun was falling back to looking up the rawData field from `request.raw_post_data`.  But that attribute doesn't exist in newer versions of Django, so we were getting exceptions in the raygun4py's Django process_exception middleware, which is a royal pain in the tush.

So, this change does the hasattr check on both attributes, and only includes rawData if one of the `request.body` or `request.raw_post_data` attributes actually exists and is readable.
from __future__ import absolute_import

from django.conf import settings

from raygun4py import raygunprovider

class Provider(object):

    def __init__(self):
    	config = getattr(settings, 'RAYGUN4PY_CONFIG', {})
    	apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None))

        self.sender = raygunprovider.RaygunSender(apiKey, config=config)

    def process_exception(self, request, exception):
    	raygunRequest = self._mapRequest(request)

        self.sender.send_exception(exception=exception, request=raygunRequest)

    def _mapRequest(self, request):
        headers = request.META.items()
        _headers = dict()
        for k, v in headers:
            if not k.startswith('wsgi'):
                _headers[k] = v

        return {
            'hostName': request.get_host(),
            'url': request.path,
            'httpMethod': request.method,
            'ipAddress': request.META.get('REMOTE_ADDR', '?'),
            'queryString': dict((key, request.GET[key]) for key in request.GET),
            'form': dict((key, request.POST[key]) for key in request.POST),
            'headers': _headers,
            'rawData': request.body if hasattr(request, 'body') else getattr(request, 'raw_post_data', {})
        }


"""ButtonWidget class.

Represents a button in the frontend using a widget.  Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64

from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, CUnicode, Bytes

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
    view_name = Unicode('ImageView', sync=True)

    # Define the custom state properties to sync with the front-end
    format = Unicode('png', sync=True)
    width = CUnicode(sync=True)
    height = CUnicode(sync=True)
    _b64value = Unicode(sync=True)

    value = Bytes()
    def _value_changed(self, name, old, new):
        self._b64value = base64.b64encode(new)

Response:
<INSERT> CUnicode, <INSERT_END> <REPLACE_OLD> Unicode(sync=True) # TODO: C unicode
 <REPLACE_NEW> CUnicode(sync=True)
 <REPLACE_END> <REPLACE_OLD> Unicode(sync=True)
 <REPLACE_NEW> CUnicode(sync=True)
 <REPLACE_END> <|endoftext|> """ButtonWidget class.

Represents a button in the frontend using a widget.  Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64

from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, CUnicode, Bytes

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
    view_name = Unicode('ImageView', sync=True)

    # Define the custom state properties to sync with the front-end
    format = Unicode('png', sync=True)
    width = CUnicode(sync=True)
    height = CUnicode(sync=True)
    _b64value = Unicode(sync=True)

    value = Bytes()
    def _value_changed(self, name, old, new):
        self._b64value = base64.b64encode(new)

Prompt:
Use CUnicode for width and height in ImageWidget

"""ButtonWidget class.

Represents a button in the frontend using a widget.  Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64

from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Bytes

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
    view_name = Unicode('ImageView', sync=True)

    # Define the custom state properties to sync with the front-end
    format = Unicode('png', sync=True)
    width = Unicode(sync=True) # TODO: C unicode
    height = Unicode(sync=True)
    _b64value = Unicode(sync=True)

    value = Bytes()
    def _value_changed(self, name, old, new):
        self._b64value = base64.b64encode(new)


from setuptools import setup, find_packages

install_requires = [
    'dill==0.2.5',
    'easydict==1.6',
    'h5py==2.6.0',
    'jsonpickle==0.9.3',
    'Keras==1.2.0',
    'nflgame==1.2.20',
    'numpy==1.11.2',
    'pandas==0.19.1',
    'scikit-learn==0.18.1',
    'scipy==0.18.1',
    'tensorflow==0.12.0rc1',
    'Theano==0.8.2',
]

with open('README.md', 'r') as f:
    readme = f.read()

setup(
    name="wincast",
    version='0.0.1',
    url='https://github.com/kahnjw/wincast',
    author_email='thomas.welfley+djproxy@gmail.com',
    long_description=readme,
    license='MIT',
    packages=find_packages(exclude=['tests', 'tests.*']),
    install_requires=install_requires,
    data_files=[
        ('models', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']),
        ('data', ['data/Xy.csv'])
    ]
)

Add back models and data

Add back models and data

Response:
<REPLACE_OLD> ('', <REPLACE_NEW> ('models', <REPLACE_END> <REPLACE_OLD> ('', <REPLACE_NEW> ('data', <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

install_requires = [
    'dill==0.2.5',
    'easydict==1.6',
    'h5py==2.6.0',
    'jsonpickle==0.9.3',
    'Keras==1.2.0',
    'nflgame==1.2.20',
    'numpy==1.11.2',
    'pandas==0.19.1',
    'scikit-learn==0.18.1',
    'scipy==0.18.1',
    'tensorflow==0.12.0rc1',
    'Theano==0.8.2',
]

with open('README.md', 'r') as f:
    readme = f.read()

setup(
    name="wincast",
    version='0.0.1',
    url='https://github.com/kahnjw/wincast',
    author_email='thomas.welfley+djproxy@gmail.com',
    long_description=readme,
    license='MIT',
    packages=find_packages(exclude=['tests', 'tests.*']),
    install_requires=install_requires,
    data_files=[
        ('models', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']),
        ('data', ['data/Xy.csv'])
    ]
)

Prompt:
Add back models and data

from setuptools import setup, find_packages

install_requires = [
    'dill==0.2.5',
    'easydict==1.6',
    'h5py==2.6.0',
    'jsonpickle==0.9.3',
    'Keras==1.2.0',
    'nflgame==1.2.20',
    'numpy==1.11.2',
    'pandas==0.19.1',
    'scikit-learn==0.18.1',
    'scipy==0.18.1',
    'tensorflow==0.12.0rc1',
    'Theano==0.8.2',
]

with open('README.md', 'r') as f:
    readme = f.read()

setup(
    name="wincast",
    version='0.0.1',
    url='https://github.com/kahnjw/wincast',
    author_email='thomas.welfley+djproxy@gmail.com',
    long_description=readme,
    license='MIT',
    packages=find_packages(exclude=['tests', 'tests.*']),
    install_requires=install_requires,
    data_files=[
        ('', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']),
        ('', ['data/Xy.csv'])
    ]
)


from setuptools import setup

setup(
    name='armstrong.base',
    version='0.1.3',
    description='Base functionality that needs to be shared widely',
    author='Texas Tribune',
    author_email='tech@texastribune.org',
    url='http://github.com/texastribune/armstrong.base/',
    packages=[
        'armstrong.base',
        'armstrong.base.templatetags',
        'armstrong.base.tests',
        'armstrong.base.tests.templatetags',
    ],
    namespace_packages=[
        "armstrong",
    ],
    install_requires=[
        'setuptools',
    ],

    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)

Response:
<REPLACE_OLD> version='0.1.2',
 <REPLACE_NEW> version='0.1.3',
 <REPLACE_END> <INSERT>        'armstrong.base.tests.templatetags',
 <INSERT_END> <|endoftext|> from setuptools import setup

setup(
    name='armstrong.base',
    version='0.1.3',
    description='Base functionality that needs to be shared widely',
    author='Texas Tribune',
    author_email='tech@texastribune.org',
    url='http://github.com/texastribune/armstrong.base/',
    packages=[
        'armstrong.base',
        'armstrong.base.templatetags',
        'armstrong.base.tests',
        'armstrong.base.tests.templatetags',
    ],
    namespace_packages=[
        "armstrong",
    ],
    install_requires=[
        'setuptools',
    ],

    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)

Prompt:
Install missing templatetags test package

from setuptools import setup

setup(
    name='armstrong.base',
    version='0.1.2',
    description='Base functionality that needs to be shared widely',
    author='Texas Tribune',
    author_email='tech@texastribune.org',
    url='http://github.com/texastribune/armstrong.base/',
    packages=[
        'armstrong.base',
        'armstrong.base.templatetags',
        'armstrong.base.tests',
    ],
    namespace_packages=[
        "armstrong",
    ],
    install_requires=[
        'setuptools',
    ],

    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)


from __future__ import unicode_literals

from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from common.mixins import ForceCapitalizeMixin

class Weekday(ForceCapitalizeMixin, models.Model):
    """Model representing the day of the week."""

    name = models.CharField(max_length=60, unique=True)

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

class Meal(ForceCapitalizeMixin, models.Model):
    """
    Model representing food occasions.

    This represents an occasion during the day that food
    is scheduled to be served. E.g breakfast, lunch, etc.
    """

    name = models.CharField(max_length=60, unique=True)
    start_time = models.TimeField()
    end_time = models.TimeField()

    capitalized_field_names = ('name',)

    def clean(self):
        if self.start_time >= self.end_time:
            raise ValidationError(_('start_time must be less than end_time.'))
        super().clean()

    def __str__(self):
        return self.name

Response:
<REPLACE_OLD> models

from <REPLACE_NEW> models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from <REPLACE_END> <INSERT> clean(self):
        if self.start_time >= self.end_time:
            raise ValidationError(_('start_time must be less than end_time.'))
        super().clean()

    def <INSERT_END> <|endoftext|> from __future__ import unicode_literals

from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from common.mixins import ForceCapitalizeMixin

class Weekday(ForceCapitalizeMixin, models.Model):
    """Model representing the day of the week."""

    name = models.CharField(max_length=60, unique=True)

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

class Meal(ForceCapitalizeMixin, models.Model):
    """
    Model representing food occasions.

    This represents an occasion during the day that food
    is scheduled to be served. E.g breakfast, lunch, etc.
    """

    name = models.CharField(max_length=60, unique=True)
    start_time = models.TimeField()
    end_time = models.TimeField()

    capitalized_field_names = ('name',)

    def clean(self):
        if self.start_time >= self.end_time:
            raise ValidationError(_('start_time must be less than end_time.'))
        super().clean()

    def __str__(self):
        return self.name

Prompt:
Update clean method to ensure that meal end_time is not same as or less than meal start_time

from __future__ import unicode_literals

from django.db import models

from common.mixins import ForceCapitalizeMixin

class Weekday(ForceCapitalizeMixin, models.Model):
    """Model representing the day of the week."""

    name = models.CharField(max_length=60, unique=True)

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

class Meal(ForceCapitalizeMixin, models.Model):
    """
    Model representing food occasions.

    This represents an occasion during the day that food
    is scheduled to be served. E.g breakfast, lunch, etc.
    """

    name = models.CharField(max_length=60, unique=True)
    start_time = models.TimeField()
    end_time = models.TimeField()

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name


from datetime import date, timedelta

def get_cutoff_date(days):
    """Calculate the cutoff date or return None if no time period was set."""
    if days is None or type(days) != int:
        return None
    else:
        if days > 0:
            return date.today() - timedelta(days=days)
        elif days == 0:
            return date.today() + timedelta(days=2)
        else:
            return None

Response:
<REPLACE_OLD> >= <REPLACE_NEW> > <REPLACE_END> <INSERT> elif days == 0:
            return date.today() + timedelta(days=2)
        <INSERT_END> <|endoftext|> from datetime import date, timedelta

def get_cutoff_date(days):
    """Calculate the cutoff date or return None if no time period was set."""
    if days is None or type(days) != int:
        return None
    else:
        if days > 0:
            return date.today() - timedelta(days=days)
        elif days == 0:
            return date.today() + timedelta(days=2)
        else:
            return None

Prompt:
Make it so a cutoff of 0 leads to no invites/registrations being shown.

from datetime import date, timedelta

def get_cutoff_date(days):
    """Calculate the cutoff date or return None if no time period was set."""
    if days is None or type(days) != int:
        return None
    else:
        if days >= 0:
            return date.today() - timedelta(days=days)
        else:
            return None


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

from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models

@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['title']}),
        (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}),
        (_('Secondary image or video'), {
            'fields': ['secondary_image', 'secondary_video_url'],
            'classes': ['collapse'],
            'description': _(
                'Choose either a video or image to include on the first page of the question, '
                'where students select concept tags. This is only used if you want the question '
                'to be hidden when students select concept tags; instead, a preliminary video or '
                'image can be displayed. The main question image will be displayed on all '
                'subsequent pages.'
            ),
        }),
        (_('Answers'), {'fields': [
            'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer'
        ]}),
        (None, {'fields': ['example_rationale']}),
    ]

@admin.register(models.Assignment)
class AssignmentAdmin(admin.ModelAdmin):
    filter_horizontal = ['questions']

Response:
<REPLACE_OLD> pass
 <REPLACE_NEW> filter_horizontal = ['questions']
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models

@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['title']}),
        (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}),
        (_('Secondary image or video'), {
            'fields': ['secondary_image', 'secondary_video_url'],
            'classes': ['collapse'],
            'description': _(
                'Choose either a video or image to include on the first page of the question, '
                'where students select concept tags. This is only used if you want the question '
                'to be hidden when students select concept tags; instead, a preliminary video or '
                'image can be displayed. The main question image will be displayed on all '
                'subsequent pages.'
            ),
        }),
        (_('Answers'), {'fields': [
            'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer'
        ]}),
        (None, {'fields': ['example_rationale']}),
    ]

@admin.register(models.Assignment)
class AssignmentAdmin(admin.ModelAdmin):
    filter_horizontal = ['questions']

Prompt:
Use nifty filter widget for selecting questions for an assignment.

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

from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models

@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['title']}),
        (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}),
        (_('Secondary image or video'), {
            'fields': ['secondary_image', 'secondary_video_url'],
            'classes': ['collapse'],
            'description': _(
                'Choose either a video or image to include on the first page of the question, '
                'where students select concept tags. This is only used if you want the question '
                'to be hidden when students select concept tags; instead, a preliminary video or '
                'image can be displayed. The main question image will be displayed on all '
                'subsequent pages.'
            ),
        }),
        (_('Answers'), {'fields': [
            'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer'
        ]}),
        (None, {'fields': ['example_rationale']}),
    ]

@admin.register(models.Assignment)
class AssignmentAdmin(admin.ModelAdmin):
    pass


#!/usr/bin/env python

from distutils.core import setup

setup(name = 'skeleton',
      version = '0.0',
      description = 'A python skeleton project',
      long_description = '''
This project represents a basic python skeleton project that can be used as
the basis for other projects.  Feel free to fork this project and use as you
see fit, but please update the information here.

Note: Licensing only applies to the skeleton itself, should you use this
      skeleton as the basis for a new project, update the license accordingly.
''',
      author = 'Chris Salch',
      author_email = 'emeraldd.chris@gmail.com',
      url = 'https://github.com/arlaneenalra/python-skeleton',
      classifiers = [
        'License :: OSI Approved :: BSD License'
      ],
      license = 'License :: OSI Approved :: BSD License',
      packages = [],
      scripts = [],
      py_modules = [],
      package_dir = { '': 'lib'},
)

Move generic lib to botton of config.

Move generic lib to botton of config.

Response:
<DELETE> package_dir = { '': 'lib'},
      <DELETE_END> <REPLACE_OLD> [],
)

 <REPLACE_NEW> [],
      package_dir = { '': 'lib'},
)

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

from distutils.core import setup

setup(name = 'skeleton',
      version = '0.0',
      description = 'A python skeleton project',
      long_description = '''
This project represents a basic python skeleton project that can be used as
the basis for other projects.  Feel free to fork this project and use as you
see fit, but please update the information here.

Note: Licensing only applies to the skeleton itself, should you use this
      skeleton as the basis for a new project, update the license accordingly.
''',
      author = 'Chris Salch',
      author_email = 'emeraldd.chris@gmail.com',
      url = 'https://github.com/arlaneenalra/python-skeleton',
      classifiers = [
        'License :: OSI Approved :: BSD License'
      ],
      license = 'License :: OSI Approved :: BSD License',
      packages = [],
      scripts = [],
      py_modules = [],
      package_dir = { '': 'lib'},
)

Prompt:
Move generic lib to botton of config.

#!/usr/bin/env python

from distutils.core import setup

setup(name = 'skeleton',
      version = '0.0',
      description = 'A python skeleton project',
      long_description = '''
This project represents a basic python skeleton project that can be used as
the basis for other projects.  Feel free to fork this project and use as you
see fit, but please update the information here.

Note: Licensing only applies to the skeleton itself, should you use this
      skeleton as the basis for a new project, update the license accordingly.
''',
      author = 'Chris Salch',
      author_email = 'emeraldd.chris@gmail.com',
      url = 'https://github.com/arlaneenalra/python-skeleton',
      classifiers = [
        'License :: OSI Approved :: BSD License'
      ],
      license = 'License :: OSI Approved :: BSD License',
      packages = [],
      package_dir = { '': 'lib'},
      scripts = [],
      py_modules = [],
)


import simuvex

class UserHook(simuvex.SimProcedure):
    NO_RET = True

    # pylint: disable=arguments-differ
    def run(self, user_func=None, user_kwargs=None, default_return_addr=None, length=None):
        result = user_func(self.state, **user_kwargs)
        if result is None:
            self.add_successor(self.state, default_return_addr, self.state.se.true, 'Ijk_NoHook')
        else:
            for state in result:
                self.add_successor(state, state.ip, state.scratch.guard, state.scratch.jumpkind)

Response:
<REPLACE_OLD> default_return_addr=None):
 <REPLACE_NEW> default_return_addr=None, length=None):
 <REPLACE_END> <|endoftext|> import simuvex

class UserHook(simuvex.SimProcedure):
    NO_RET = True

    # pylint: disable=arguments-differ
    def run(self, user_func=None, user_kwargs=None, default_return_addr=None, length=None):
        result = user_func(self.state, **user_kwargs)
        if result is None:
            self.add_successor(self.state, default_return_addr, self.state.se.true, 'Ijk_NoHook')
        else:
            for state in result:
                self.add_successor(state, state.ip, state.scratch.guard, state.scratch.jumpkind)

Prompt:
Make the userhook take the length arg b/c why not

import simuvex

class UserHook(simuvex.SimProcedure):
    NO_RET = True

    # pylint: disable=arguments-differ
    def run(self, user_func=None, user_kwargs=None, default_return_addr=None):
        result = user_func(self.state, **user_kwargs)
        if result is None:
            self.add_successor(self.state, default_return_addr, self.state.se.true, 'Ijk_NoHook')
        else:
            for state in result:
                self.add_successor(state, state.ip, state.scratch.guard, state.scratch.jumpkind)


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

from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

requirements = [
    'furl==0.5.6',
    'six==1.10.0',
    'pytest==3.0.3'
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='surveymonkey',
    version='0.4.2',
    description="Python wrapper for the Survey Monkey v3 API",
    long_description=readme,
    author="Aaron Bassett",
    author_email='engineering@getadministrate.com',
    url='https://github.com/Administrate/surveymonkey',
    packages=[
        'surveymonkey',
        'surveymonkey.collectors',
        'surveymonkey.webhooks',
        'surveymonkey.messages'
    ],
    package_dir={'surveymonkey':
                 'surveymonkey'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='surveymonkey',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

Add pytest to surveymonkey dependencies

Add pytest to surveymonkey dependencies

Response:
<REPLACE_OLD> 'six==1.10.0'
]

test_requirements <REPLACE_NEW> 'six==1.10.0',
    'pytest==3.0.3'
]

test_requirements <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

requirements = [
    'furl==0.5.6',
    'six==1.10.0',
    'pytest==3.0.3'
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='surveymonkey',
    version='0.4.2',
    description="Python wrapper for the Survey Monkey v3 API",
    long_description=readme,
    author="Aaron Bassett",
    author_email='engineering@getadministrate.com',
    url='https://github.com/Administrate/surveymonkey',
    packages=[
        'surveymonkey',
        'surveymonkey.collectors',
        'surveymonkey.webhooks',
        'surveymonkey.messages'
    ],
    package_dir={'surveymonkey':
                 'surveymonkey'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='surveymonkey',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

Prompt:
Add pytest to surveymonkey dependencies

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

from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

requirements = [
    'furl==0.5.6',
    'six==1.10.0'
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='surveymonkey',
    version='0.4.2',
    description="Python wrapper for the Survey Monkey v3 API",
    long_description=readme,
    author="Aaron Bassett",
    author_email='engineering@getadministrate.com',
    url='https://github.com/Administrate/surveymonkey',
    packages=[
        'surveymonkey',
        'surveymonkey.collectors',
        'surveymonkey.webhooks',
        'surveymonkey.messages'
    ],
    package_dir={'surveymonkey':
                 'surveymonkey'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='surveymonkey',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


import sys
from plistlib import writePlist
from defcon import Font

__doc__ = '''
Subset kerning in UFO given a list of glyphs provided.
Will export new plist files that can be swapped into the UFO.

Usage:
python subsetKerning.py subsetList font.ufo
'''

class SubsetKerning(object):
    """docstring for SubsetKerning"""
    def __init__(self, font, subsetFile):
        self.font = Font(font)
        self.subsetFile = subsetFile

        with open(self.subsetFile, 'r') as ssfile:
            rawData = ssfile.read()
            self.subsetGlyphList = [line.split()[0] for line in rawData.splitlines()]

    def subsetGroups(self):

        newGroups = {}
        for groupName, glyphList in self.font.groups.items():
            combinedGlyphs = set(self.subsetGlyphList) & set(glyphList)
            newGlyphList = sorted(list(combinedGlyphs))

            if len(newGlyphList):
                newGroups[groupName] = newGlyphList
        return newGroups

    def subsetKerning(self):
        newGroups = self.subsetGroups()
        newKerning = {}
        plistStyleKerning = {}

        # All allowed items for kerning, which are our subset glyphs,
        # plus the groups filtered earlier:
        allowedItems = set(newGroups) | set(self.subsetGlyphList)

        for [left, right], value in self.font.kerning.items():
            if set([left, right]) <= allowedItems:
                newKerning[left, right] = value

        # Since the kerning paradigm stored in the plist differs from the
        # in the kerning object, the data structure needs some modification:

        for [left, right], value in newKerning.items():
            partnerDict = plistStyleKerning.setdefault(left, {})
            partnerDict[right] = value

        return plistStyleKerning

def run():
    sk = SubsetKerning(sys.argv[-1], sys.argv[-2])

    writePlist(sk.subsetGroups(), 'subset_groups.plist')
    writePlist(sk.subsetKerning(), 'subset_kerning.plist')
    print 'done'

if len(sys.argv) == 3:
    run()
else:
    print __doc__

Add script to subset kerning plist.

Add script to subset kerning plist.

Response:
<REPLACE_OLD>  <REPLACE_NEW> import sys
from plistlib import writePlist
from defcon import Font

__doc__ = '''
Subset kerning in UFO given a list of glyphs provided.
Will export new plist files that can be swapped into the UFO.

Usage:
python subsetKerning.py subsetList font.ufo
'''

class SubsetKerning(object):
    """docstring for SubsetKerning"""
    def __init__(self, font, subsetFile):
        self.font = Font(font)
        self.subsetFile = subsetFile

        with open(self.subsetFile, 'r') as ssfile:
            rawData = ssfile.read()
            self.subsetGlyphList = [line.split()[0] for line in rawData.splitlines()]

    def subsetGroups(self):

        newGroups = {}
        for groupName, glyphList in self.font.groups.items():
            combinedGlyphs = set(self.subsetGlyphList) & set(glyphList)
            newGlyphList = sorted(list(combinedGlyphs))

            if len(newGlyphList):
                newGroups[groupName] = newGlyphList
        return newGroups

    def subsetKerning(self):
        newGroups = self.subsetGroups()
        newKerning = {}
        plistStyleKerning = {}

        # All allowed items for kerning, which are our subset glyphs,
        # plus the groups filtered earlier:
        allowedItems = set(newGroups) | set(self.subsetGlyphList)

        for [left, right], value in self.font.kerning.items():
            if set([left, right]) <= allowedItems:
                newKerning[left, right] = value

        # Since the kerning paradigm stored in the plist differs from the
        # in the kerning object, the data structure needs some modification:

        for [left, right], value in newKerning.items():
            partnerDict = plistStyleKerning.setdefault(left, {})
            partnerDict[right] = value

        return plistStyleKerning

def run():
    sk = SubsetKerning(sys.argv[-1], sys.argv[-2])

    writePlist(sk.subsetGroups(), 'subset_groups.plist')
    writePlist(sk.subsetKerning(), 'subset_kerning.plist')
    print 'done'

if len(sys.argv) == 3:
    run()
else:
    print __doc__

 <REPLACE_END> <|endoftext|> import sys
from plistlib import writePlist
from defcon import Font

__doc__ = '''
Subset kerning in UFO given a list of glyphs provided.
Will export new plist files that can be swapped into the UFO.

Usage:
python subsetKerning.py subsetList font.ufo
'''

class SubsetKerning(object):
    """docstring for SubsetKerning"""
    def __init__(self, font, subsetFile):
        self.font = Font(font)
        self.subsetFile = subsetFile

        with open(self.subsetFile, 'r') as ssfile:
            rawData = ssfile.read()
            self.subsetGlyphList = [line.split()[0] for line in rawData.splitlines()]

    def subsetGroups(self):

        newGroups = {}
        for groupName, glyphList in self.font.groups.items():
            combinedGlyphs = set(self.subsetGlyphList) & set(glyphList)
            newGlyphList = sorted(list(combinedGlyphs))

            if len(newGlyphList):
                newGroups[groupName] = newGlyphList
        return newGroups

    def subsetKerning(self):
        newGroups = self.subsetGroups()
        newKerning = {}
        plistStyleKerning = {}

        # All allowed items for kerning, which are our subset glyphs,
        # plus the groups filtered earlier:
        allowedItems = set(newGroups) | set(self.subsetGlyphList)

        for [left, right], value in self.font.kerning.items():
            if set([left, right]) <= allowedItems:
                newKerning[left, right] = value

        # Since the kerning paradigm stored in the plist differs from the
        # in the kerning object, the data structure needs some modification:

        for [left, right], value in newKerning.items():
            partnerDict = plistStyleKerning.setdefault(left, {})
            partnerDict[right] = value

        return plistStyleKerning

def run():
    sk = SubsetKerning(sys.argv[-1], sys.argv[-2])

    writePlist(sk.subsetGroups(), 'subset_groups.plist')
    writePlist(sk.subsetKerning(), 'subset_kerning.plist')
    print 'done'

if len(sys.argv) == 3:
    run()
else:
    print __doc__

Prompt: Add script to subset kerning plist.


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

from django.conf import settings
from papers.errors import MetadataSourceException
from papers.utils import sanitize_html

import requests

##### Zotero interface #####

def fetch_zotero_by_DOI(doi):
    """
    Fetch Zotero metadata for a given DOI.
    Works only with the doi_cache proxy.
    """
    try:
        request = requests.get('https://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
        return request.json()
    except ValueError as e:
        raise MetadataSourceException('Error while fetching Zotero metadata:\nInvalid JSON response.\n' +
                                      'Error: '+str(e))

def consolidate_publication(publi):
    """
    Fetches the abstract from Zotero and adds it to the publication if it succeeds.
    """
    zotero = fetch_zotero_by_DOI(publi.doi)
    if zotero is None:
        return publi
    for item in zotero:
        if 'abstractNote' in item:
            publi.description = sanitize_html(item['abstractNote'])
            publi.save(update_fields=['description'])
        for attachment in item.get('attachments', []):
            if attachment.get('mimeType') == 'application/pdf':
                publi.pdf_url = attachment.get('url')
                publi.save(update_fields=['pdf_url'])
                publi.about.update_availability()
    return publi

Response:
<REPLACE_OLD> requests.get('http://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
 <REPLACE_NEW> requests.get('https://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
 <REPLACE_END> <|endoftext|> # -*- encoding: utf-8 -*-

from django.conf import settings
from papers.errors import MetadataSourceException
from papers.utils import sanitize_html

import requests

##### Zotero interface #####

def fetch_zotero_by_DOI(doi):
    """
    Fetch Zotero metadata for a given DOI.
    Works only with the doi_cache proxy.
    """
    try:
        request = requests.get('https://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
        return request.json()
    except ValueError as e:
        raise MetadataSourceException('Error while fetching Zotero metadata:\nInvalid JSON response.\n' +
                                      'Error: '+str(e))

def consolidate_publication(publi):
    """
    Fetches the abstract from Zotero and adds it to the publication if it succeeds.
    """
    zotero = fetch_zotero_by_DOI(publi.doi)
    if zotero is None:
        return publi
    for item in zotero:
        if 'abstractNote' in item:
            publi.description = sanitize_html(item['abstractNote'])
            publi.save(update_fields=['description'])
        for attachment in item.get('attachments', []):
            if attachment.get('mimeType') == 'application/pdf':
                publi.pdf_url = attachment.get('url')
                publi.save(update_fields=['pdf_url'])
                publi.about.update_availability()
    return publi

Prompt:
Use HTTPS instead of HTTP since cache does redirect anyways

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

from django.conf import settings
from papers.errors import MetadataSourceException
from papers.utils import sanitize_html

import requests

##### Zotero interface #####

def fetch_zotero_by_DOI(doi):
    """
    Fetch Zotero metadata for a given DOI.
    Works only with the doi_cache proxy.
    """
    try:
        request = requests.get('http://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
        return request.json()
    except ValueError as e:
        raise MetadataSourceException('Error while fetching Zotero metadata:\nInvalid JSON response.\n' +
                                      'Error: '+str(e))

def consolidate_publication(publi):
    """
    Fetches the abstract from Zotero and adds it to the publication if it succeeds.
    """
    zotero = fetch_zotero_by_DOI(publi.doi)
    if zotero is None:
        return publi
    for item in zotero:
        if 'abstractNote' in item:
            publi.description = sanitize_html(item['abstractNote'])
            publi.save(update_fields=['description'])
        for attachment in item.get('attachments', []):
            if attachment.get('mimeType') == 'application/pdf':
                publi.pdf_url = attachment.get('url')
                publi.save(update_fields=['pdf_url'])
                publi.about.update_availability()
    return publi


import numpy
import ast

from django.db import models

class DataPoint(models.Model):
    name = models.CharField(max_length=600)
    exact_name = models.CharField(max_length=1000, null=True, blank=True)
    decay_feature = models.CharField(max_length=1000, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    options = models.CharField(max_length=100)
    homo = models.FloatField()
    lumo = models.FloatField()
    homo_orbital = models.IntegerField()
    energy = models.FloatField()
    dipole = models.FloatField()
    band_gap = models.FloatField(null=True, blank=True)

    def __unicode__(self):
        return unicode(self.name)

    @classmethod
    def get_all_data(cls):
        data = DataPoint.objects.filter(band_gap__isnull=False,
                                        exact_name__isnull=False,
                                        decay_feature__isnull=False)
        M = len(data)
        HOMO = numpy.zeros((M, 1))
        LUMO = numpy.zeros((M, 1))
        GAP = numpy.zeros((M, 1))
        vectors = []
        for i, x in enumerate(data):
            HOMO[i] = x.homo
            LUMO[i] = x.lumo
            GAP[i] = x.band_gap
            vectors.append(ast.literal_eval(x.decay_feature))
        FEATURE = numpy.matrix(vectors)
        return FEATURE, HOMO, LUMO, GAP

Fix __unicode__ for DataPoint model

Fix __unicode__ for DataPoint model

Response:
<REPLACE_OLD> self.exact_name

 <REPLACE_NEW> unicode(self.name)

 <REPLACE_END> <|endoftext|> import numpy
import ast

from django.db import models

class DataPoint(models.Model):
    name = models.CharField(max_length=600)
    exact_name = models.CharField(max_length=1000, null=True, blank=True)
    decay_feature = models.CharField(max_length=1000, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    options = models.CharField(max_length=100)
    homo = models.FloatField()
    lumo = models.FloatField()
    homo_orbital = models.IntegerField()
    energy = models.FloatField()
    dipole = models.FloatField()
    band_gap = models.FloatField(null=True, blank=True)

    def __unicode__(self):
        return unicode(self.name)

    @classmethod
    def get_all_data(cls):
        data = DataPoint.objects.filter(band_gap__isnull=False,
                                        exact_name__isnull=False,
                                        decay_feature__isnull=False)
        M = len(data)
        HOMO = numpy.zeros((M, 1))
        LUMO = numpy.zeros((M, 1))
        GAP = numpy.zeros((M, 1))
        vectors = []
        for i, x in enumerate(data):
            HOMO[i] = x.homo
            LUMO[i] = x.lumo
            GAP[i] = x.band_gap
            vectors.append(ast.literal_eval(x.decay_feature))
        FEATURE = numpy.matrix(vectors)
        return FEATURE, HOMO, LUMO, GAP

Prompt:
Fix __unicode__ for DataPoint model

import numpy
import ast

from django.db import models

class DataPoint(models.Model):
    name = models.CharField(max_length=600)
    exact_name = models.CharField(max_length=1000, null=True, blank=True)
    decay_feature = models.CharField(max_length=1000, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    options = models.CharField(max_length=100)
    homo = models.FloatField()
    lumo = models.FloatField()
    homo_orbital = models.IntegerField()
    energy = models.FloatField()
    dipole = models.FloatField()
    band_gap = models.FloatField(null=True, blank=True)

    def __unicode__(self):
        return self.exact_name

    @classmethod
    def get_all_data(cls):
        data = DataPoint.objects.filter(band_gap__isnull=False,
                                        exact_name__isnull=False,
                                        decay_feature__isnull=False)
        M = len(data)
        HOMO = numpy.zeros((M, 1))
        LUMO = numpy.zeros((M, 1))
        GAP = numpy.zeros((M, 1))
        vectors = []
        for i, x in enumerate(data):
            HOMO[i] = x.homo
            LUMO[i] = x.lumo
            GAP[i] = x.band_gap
            vectors.append(ast.literal_eval(x.decay_feature))
        FEATURE = numpy.matrix(vectors)
        return FEATURE, HOMO, LUMO, GAP


from tests.BaseTestWithDB import BaseTestWithDB
from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator

class TestCaseModelTest(BaseTestWithDB):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.test_data = TopicsTestDataGenerator()

    def create_testcase(self):
        topic = self.test_data.create_topic(1)
        difficulty = self.test_data.create_difficulty_level(1)
        challenge = self.test_data.create_programming_challenge(topic, 1, difficulty)

        self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge)

    def test_testcase_verbose_model_name(self):
        self.create_testcase()
        verbose_name = self.test_case._meta.verbose_name
        self.assertEquals(verbose_name, "Test Case")

Fix models unit test for plugging it in

Fix models unit test for plugging it in

Response:
<DELETE> plugging_it_in.models import TestCase

from <DELETE_END> <DELETE> self.test_data.create_programming_challenge_test_case(1, challenge)
        <DELETE_END> <REPLACE_OLD> TestCase.objects.get(id=1)

 <REPLACE_NEW> self.test_data.create_programming_challenge_test_case(1, challenge)

 <REPLACE_END> <|endoftext|> from tests.BaseTestWithDB import BaseTestWithDB
from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator

class TestCaseModelTest(BaseTestWithDB):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.test_data = TopicsTestDataGenerator()

    def create_testcase(self):
        topic = self.test_data.create_topic(1)
        difficulty = self.test_data.create_difficulty_level(1)
        challenge = self.test_data.create_programming_challenge(topic, 1, difficulty)

        self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge)

    def test_testcase_verbose_model_name(self):
        self.create_testcase()
        verbose_name = self.test_case._meta.verbose_name
        self.assertEquals(verbose_name, "Test Case")

Prompt:
Fix models unit test for plugging it in

from plugging_it_in.models import TestCase

from tests.BaseTestWithDB import BaseTestWithDB
from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator

class TestCaseModelTest(BaseTestWithDB):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.test_data = TopicsTestDataGenerator()

    def create_testcase(self):
        topic = self.test_data.create_topic(1)
        difficulty = self.test_data.create_difficulty_level(1)
        challenge = self.test_data.create_programming_challenge(topic, 1, difficulty)

        self.test_data.create_programming_challenge_test_case(1, challenge)
        self.test_case = TestCase.objects.get(id=1)

    def test_testcase_verbose_model_name(self):
        self.create_testcase()
        verbose_name = self.test_case._meta.verbose_name
        self.assertEquals(verbose_name, "Test Case")


import os
from datetime import datetime

def save_logs(groomer, test_description):
    divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
    test_log_path = 'tests/test_logs/{}.log'.format(test_description)
    with open(test_log_path, 'w+') as test_log:
        test_log.write(divider.format('TEST LOG'))
        test_log.write(str(datetime.now().time()) + '\n')
        test_log.write(test_description + '\n')
        test_log.write('-' * 20 + '\n')
        with open(groomer.logger.log_path, 'r') as logfile:
            log = logfile.read()
            test_log.write(log)
        if os.path.exists(groomer.logger.log_debug_err):
            test_log.write(divider.format('ERR LOG'))
            with open(groomer.logger.log_debug_err, 'r') as debug_err:
                err = debug_err.read()
                test_log.write(err)
        if os.path.exists(groomer.logger.log_debug_out):
            test_log.write(divider.format('OUT LOG'))
            with open(groomer.logger.log_debug_out, 'r') as debug_out:
                out = debug_out.read()
                test_log.write(out)

Add time information to test logs

Add time information to test logs

Response:
<REPLACE_OLD> os

def <REPLACE_NEW> os
from datetime import datetime

def <REPLACE_END> <INSERT> test_log.write(str(datetime.now().time()) + '\n')
        test_log.write(test_description + '\n')
        test_log.write('-' * 20 + '\n')
        <INSERT_END> <|endoftext|> import os
from datetime import datetime

def save_logs(groomer, test_description):
    divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
    test_log_path = 'tests/test_logs/{}.log'.format(test_description)
    with open(test_log_path, 'w+') as test_log:
        test_log.write(divider.format('TEST LOG'))
        test_log.write(str(datetime.now().time()) + '\n')
        test_log.write(test_description + '\n')
        test_log.write('-' * 20 + '\n')
        with open(groomer.logger.log_path, 'r') as logfile:
            log = logfile.read()
            test_log.write(log)
        if os.path.exists(groomer.logger.log_debug_err):
            test_log.write(divider.format('ERR LOG'))
            with open(groomer.logger.log_debug_err, 'r') as debug_err:
                err = debug_err.read()
                test_log.write(err)
        if os.path.exists(groomer.logger.log_debug_out):
            test_log.write(divider.format('OUT LOG'))
            with open(groomer.logger.log_debug_out, 'r') as debug_out:
                out = debug_out.read()
                test_log.write(out)

Prompt:
Add time information to test logs

import os

def save_logs(groomer, test_description):
    divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
    test_log_path = 'tests/test_logs/{}.log'.format(test_description)
    with open(test_log_path, 'w+') as test_log:
        test_log.write(divider.format('TEST LOG'))
        with open(groomer.logger.log_path, 'r') as logfile:
            log = logfile.read()
            test_log.write(log)
        if os.path.exists(groomer.logger.log_debug_err):
            test_log.write(divider.format('ERR LOG'))
            with open(groomer.logger.log_debug_err, 'r') as debug_err:
                err = debug_err.read()
                test_log.write(err)
        if os.path.exists(groomer.logger.log_debug_out):
            test_log.write(divider.format('OUT LOG'))
            with open(groomer.logger.log_debug_out, 'r') as debug_out:
                out = debug_out.read()
                test_log.write(out)


#!/usr/bin/env python
import io

from setuptools import setup, Extension

with io.open('README.rst', encoding='utf8') as readme:
    long_description = readme.read()

setup(
    name="pyspamsum",
    version="1.0.5",
    description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
    long_description=long_description,
    long_description_content_type='text/x-rst',
    author="Russell Keith-Magee",
    author_email="russell@keith-magee.com",
    url='http://github.com/freakboy3742/pyspamsum/',
    license="New BSD",
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Topic :: Text Processing',
        'Topic :: Utilities',
    ],
    ext_modules=[
        Extension(
            "spamsum", [
                "pyspamsum.c",
                "spamsum.c",
                "edit_dist.c",
            ]
        )
    ],
    test_suite='tests',
)

Response:
<INSERT> long_description_content_type='text/x-rst',
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
import io

from setuptools import setup, Extension

with io.open('README.rst', encoding='utf8') as readme:
    long_description = readme.read()

setup(
    name="pyspamsum",
    version="1.0.5",
    description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
    long_description=long_description,
    long_description_content_type='text/x-rst',
    author="Russell Keith-Magee",
    author_email="russell@keith-magee.com",
    url='http://github.com/freakboy3742/pyspamsum/',
    license="New BSD",
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Topic :: Text Processing',
        'Topic :: Utilities',
    ],
    ext_modules=[
        Extension(
            "spamsum", [
                "pyspamsum.c",
                "spamsum.c",
                "edit_dist.c",
            ]
        )
    ],
    test_suite='tests',
)

Prompt:
Add a content type description to keep twine happy.

#!/usr/bin/env python
import io

from setuptools import setup, Extension

with io.open('README.rst', encoding='utf8') as readme:
    long_description = readme.read()

setup(
    name="pyspamsum",
    version="1.0.5",
    description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
    long_description=long_description,
    author="Russell Keith-Magee",
    author_email="russell@keith-magee.com",
    url='http://github.com/freakboy3742/pyspamsum/',
    license="New BSD",
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Topic :: Text Processing',
        'Topic :: Utilities',
    ],
    ext_modules=[
        Extension(
            "spamsum", [
                "pyspamsum.c",
                "spamsum.c",
                "edit_dist.c",
            ]
        )
    ],
    test_suite='tests',
)


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

"""

Add directory for start symbol tests

Add directory for start symbol tests

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

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

"""

Prompt: Add directory for start symbol tests


from kqml import cl_json, KQMLList

def test_parse():
    json_dict = {'a': 1, 'b': 2,
                 'c': ['foo', {'bar': None, 'done': False}],
                 'this is json': True}
    res = cl_json.parse_json(json_dict)
    assert isinstance(res, KQMLList)
    assert len(res) == 2*len(json_dict.keys())

Add a test of the parser.

Add a test of the parser.

Response:
<INSERT> from kqml import cl_json, KQMLList

def test_parse():
 <INSERT_END> <INSERT>   json_dict = {'a': 1, 'b': 2,
                 'c': ['foo', {'bar': None, 'done': False}],
                 'this is json': True}
    res = cl_json.parse_json(json_dict)
    assert isinstance(res, KQMLList)
    assert len(res) == 2*len(json_dict.keys())
 <INSERT_END> <|endoftext|> from kqml import cl_json, KQMLList

def test_parse():
    json_dict = {'a': 1, 'b': 2,
                 'c': ['foo', {'bar': None, 'done': False}],
                 'this is json': True}
    res = cl_json.parse_json(json_dict)
    assert isinstance(res, KQMLList)
    assert len(res) == 2*len(json_dict.keys())

Prompt: Add a test of the parser.


import dask
import dask.distributed

import distributed

try:
    import dask.distributed.joblib
except ImportError:
    pass

try:
    import distributed.joblib
except ImportError:
    pass

import sklearn
import sklearn.externals
import sklearn.externals.joblib

Add backwards compatible Distributed Joblib hook

Depending on the versions of Distributed, Joblib, and scikit-learn,
there are different strategies for registering the Joblib backend. Try
going with the standard Distributed technique first, which may fail for
Distributed 1.24.0+. In other cases, import `joblib` and
`sklearn.externals.joblib`, which should handle this for Dask when
Joblib 0.12.2+ and scikit-learn 0.20.0+ are present. This should ensure
that all three are aware of each other and can work correctly.

This dummy module is only useful internally. So mark it as such. It can
be dropped at any time without explanation once convenient.

Using this design, we can comfortably use this in-place of the other
`import`s we were doing to achieve this effect.

Response:
<INSERT> import dask
import dask.distributed

import distributed

try:
 <INSERT_END> <INSERT>   import dask.distributed.joblib
except ImportError:
    pass

try:
    import distributed.joblib
except ImportError:
    pass

import sklearn
import sklearn.externals
import sklearn.externals.joblib
 <INSERT_END> <|endoftext|> import dask
import dask.distributed

import distributed

try:
    import dask.distributed.joblib
except ImportError:
    pass

try:
    import distributed.joblib
except ImportError:
    pass

import sklearn
import sklearn.externals
import sklearn.externals.joblib

Prompt:
Add backwards compatible Distributed Joblib hook

Depending on the versions of Distributed, Joblib, and scikit-learn,
there are different strategies for registering the Joblib backend. Try
going with the standard Distributed technique first, which may fail for
Distributed 1.24.0+. In other cases, import `joblib` and
`sklearn.externals.joblib`, which should handle this for Dask when
Joblib 0.12.2+ and scikit-learn 0.20.0+ are present. This should ensure
that all three are aware of each other and can work correctly.

This dummy module is only useful internally. So mark it as such. It can
be dropped at any time without explanation once convenient.

Using this design, we can comfortably use this in-place of the other
`import`s we were doing to achieve this effect.


from __future__ import unicode_literals
from moto.core.exceptions import RESTError

class IAMNotFoundException(RESTError):
    code = 404

    def __init__(self, message):
        super(IAMNotFoundException, self).__init__(
            "NoSuchEntity", message)

class IAMConflictException(RESTError):
    code = 409

    def __init__(self, code='Conflict', message=""):
        super(IAMConflictException, self).__init__(
            code, message)

class IAMReportNotPresentException(RESTError):
    code = 410

    def __init__(self, message):
        super(IAMReportNotPresentException, self).__init__(
            "ReportNotPresent", message)

Response:
<REPLACE_OLD> "Not Found", <REPLACE_NEW> "NoSuchEntity", <REPLACE_END> <|endoftext|> from __future__ import unicode_literals
from moto.core.exceptions import RESTError

class IAMNotFoundException(RESTError):
    code = 404

    def __init__(self, message):
        super(IAMNotFoundException, self).__init__(
            "NoSuchEntity", message)

class IAMConflictException(RESTError):
    code = 409

    def __init__(self, code='Conflict', message=""):
        super(IAMConflictException, self).__init__(
            code, message)

class IAMReportNotPresentException(RESTError):
    code = 410

    def __init__(self, message):
        super(IAMReportNotPresentException, self).__init__(
            "ReportNotPresent", message)

Prompt:
Fix the error code for IAMNotFoundException to NoSuchEntity used by AWS.

from __future__ import unicode_literals
from moto.core.exceptions import RESTError

class IAMNotFoundException(RESTError):
    code = 404

    def __init__(self, message):
        super(IAMNotFoundException, self).__init__(
            "Not Found", message)

class IAMConflictException(RESTError):
    code = 409

    def __init__(self, code='Conflict', message=""):
        super(IAMConflictException, self).__init__(
            code, message)

class IAMReportNotPresentException(RESTError):
    code = 410

    def __init__(self, message):
        super(IAMReportNotPresentException, self).__init__(
            "ReportNotPresent", message)


# Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
Tests for top-level ``flocker`` package.
"""

from sys import executable
from subprocess import check_output, STDOUT

from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath

import flocker

class WarningsTests(SynchronousTestCase):
    """
    Tests for warning suppression.
    """
    def test_warnings_suppressed(self):
        """
        Warnings are suppressed for processes that import flocker.
        """
        root = FilePath(flocker.__file__)
        result = check_output(
            [executable, b"-c", (b"import flocker; import warnings; " +
                                 b"warnings.warn('ohno')")],
            stderr=STDOUT,
            # Make sure we can import flocker package:
            cwd=root.parent().parent().path)
        self.assertEqual(result, b"")

Response:
<REPLACE_OLD> SynchronousTestCase

class <REPLACE_NEW> SynchronousTestCase
from twisted.python.filepath import FilePath

import flocker

class <REPLACE_END> <INSERT>        root = FilePath(flocker.__file__)
 <INSERT_END> <REPLACE_OLD> stderr=STDOUT)
 <REPLACE_NEW> stderr=STDOUT,
            # Make sure we can import flocker package:
            cwd=root.parent().parent().path)
 <REPLACE_END> <|endoftext|> # Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
Tests for top-level ``flocker`` package.
"""

from sys import executable
from subprocess import check_output, STDOUT

from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath

import flocker

class WarningsTests(SynchronousTestCase):
    """
    Tests for warning suppression.
    """
    def test_warnings_suppressed(self):
        """
        Warnings are suppressed for processes that import flocker.
        """
        root = FilePath(flocker.__file__)
        result = check_output(
            [executable, b"-c", (b"import flocker; import warnings; " +
                                 b"warnings.warn('ohno')")],
            stderr=STDOUT,
            # Make sure we can import flocker package:
            cwd=root.parent().parent().path)
        self.assertEqual(result, b"")

Prompt:
Make sure flocker package can be imported even if it's not installed.

# Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
Tests for top-level ``flocker`` package.
"""

from sys import executable
from subprocess import check_output, STDOUT

from twisted.trial.unittest import SynchronousTestCase

class WarningsTests(SynchronousTestCase):
    """
    Tests for warning suppression.
    """
    def test_warnings_suppressed(self):
        """
        Warnings are suppressed for processes that import flocker.
        """
        result = check_output(
            [executable, b"-c", (b"import flocker; import warnings; " +
                                 b"warnings.warn('ohno')")],
            stderr=STDOUT)
        self.assertEqual(result, b"")


#!/usr/bin/env python

import sys, os
import serial
from PIL import Image

if not len(sys.argv) == 2:
    print sys.argv[0], "/path/to/image"
    sys.exit(1)

filepath = sys.argv[1]
im = Image.open(filepath)
rgb_im = im.convert('RGB')

width, height = im.size

if not width == 96 or not height == 64:
    print "Image wrong size. Must be 96x64."
    sys.exit(1)

bytes = []

for y in range(0, height):
    for byteIndex in range(0, width / 8):
        byte = 0

        for bit in range(0, 8):
            x = byteIndex * 8 + bit
            r, g, b = rgb_im.getpixel((x, y))
            v = (r + g + b) / 3.0

            if v < 128:
                byte |= 0x80 >> bit

        bytes += [byte]

ser = serial.Serial("/dev/ttyUSB0", 500000)

for byte in bytes:
    x = ser.write(chr(byte))

ser.close()

print "sent", len(bytes), "bytes"

Send images to calculator over serial.

Send images to calculator over serial.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python

import sys, os
import serial
from PIL import Image

if not len(sys.argv) == 2:
    print sys.argv[0], "/path/to/image"
    sys.exit(1)

filepath = sys.argv[1]
im = Image.open(filepath)
rgb_im = im.convert('RGB')

width, height = im.size

if not width == 96 or not height == 64:
    print "Image wrong size. Must be 96x64."
    sys.exit(1)

bytes = []

for y in range(0, height):
    for byteIndex in range(0, width / 8):
        byte = 0

        for bit in range(0, 8):
            x = byteIndex * 8 + bit
            r, g, b = rgb_im.getpixel((x, y))
            v = (r + g + b) / 3.0

            if v < 128:
                byte |= 0x80 >> bit

        bytes += [byte]

ser = serial.Serial("/dev/ttyUSB0", 500000)

for byte in bytes:
    x = ser.write(chr(byte))

ser.close()

print "sent", len(bytes), "bytes"
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import sys, os
import serial
from PIL import Image

if not len(sys.argv) == 2:
    print sys.argv[0], "/path/to/image"
    sys.exit(1)

filepath = sys.argv[1]
im = Image.open(filepath)
rgb_im = im.convert('RGB')

width, height = im.size

if not width == 96 or not height == 64:
    print "Image wrong size. Must be 96x64."
    sys.exit(1)

bytes = []

for y in range(0, height):
    for byteIndex in range(0, width / 8):
        byte = 0

        for bit in range(0, 8):
            x = byteIndex * 8 + bit
            r, g, b = rgb_im.getpixel((x, y))
            v = (r + g + b) / 3.0

            if v < 128:
                byte |= 0x80 >> bit

        bytes += [byte]

ser = serial.Serial("/dev/ttyUSB0", 500000)

for byte in bytes:
    x = ser.write(chr(byte))

ser.close()

print "sent", len(bytes), "bytes"

Prompt: Send images to calculator over serial.


from shapely.geometry import MultiPolygon, Point, Polygon

def test_empty_polygon():
    """No constructor arg makes an empty polygon geometry."""
    assert Polygon().is_empty

def test_empty_multipolygon():
    """No constructor arg makes an empty multipolygon geometry."""
    assert MultiPolygon().is_empty

def test_multipolygon_empty_polygon():
    """An empty polygon passed to MultiPolygon() makes an empty
    multipolygon geometry."""
    assert MultiPolygon([Polygon()]).is_empty

def test_multipolygon_empty_among_polygon():
    """An empty polygon passed to MultiPolygon() is ignored."""
    assert len(MultiPolygon([Point(0,0).buffer(1.0), Polygon()])) == 1

Response:
<INSERT> Point, <INSERT_END> <REPLACE_OLD> MultiPolygon([Polygon()]).is_empty
 <REPLACE_NEW> MultiPolygon([Polygon()]).is_empty

def test_multipolygon_empty_among_polygon():
    """An empty polygon passed to MultiPolygon() is ignored."""
    assert len(MultiPolygon([Point(0,0).buffer(1.0), Polygon()])) == 1
 <REPLACE_END> <|endoftext|> from shapely.geometry import MultiPolygon, Point, Polygon

def test_empty_polygon():
    """No constructor arg makes an empty polygon geometry."""
    assert Polygon().is_empty

def test_empty_multipolygon():
    """No constructor arg makes an empty multipolygon geometry."""
    assert MultiPolygon().is_empty

def test_multipolygon_empty_polygon():
    """An empty polygon passed to MultiPolygon() makes an empty
    multipolygon geometry."""
    assert MultiPolygon([Polygon()]).is_empty

def test_multipolygon_empty_among_polygon():
    """An empty polygon passed to MultiPolygon() is ignored."""
    assert len(MultiPolygon([Point(0,0).buffer(1.0), Polygon()])) == 1

Prompt:
Add test of an empty and non empty polygon

from shapely.geometry import MultiPolygon, Polygon

def test_empty_polygon():
    """No constructor arg makes an empty polygon geometry."""
    assert Polygon().is_empty

def test_empty_multipolygon():
    """No constructor arg makes an empty multipolygon geometry."""
    assert MultiPolygon().is_empty

def test_multipolygon_empty_polygon():
    """An empty polygon passed to MultiPolygon() makes an empty
    multipolygon geometry."""
    assert MultiPolygon([Polygon()]).is_empty


import husk
from setuptools import setup, find_packages

kwargs = {
    'packages': find_packages(),
    'include_package_data': True,
    'test_suite': 'tests',
    'name': 'husk',
    'version': husk.__version__,
    'author': 'Byron Ruth, Patrick Henning',
    'author_email': 'b@devel.io',
    'description': husk.__doc__,
    'license': 'BSD',
    'keywords': 'note-taking Cornell',
    'url': 'http://husk.github.com/husk/',
    'scripts': ['bin/husk'],
    'classifiers': [
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7'
    ],
}

setup(**kwargs)

Response:
<REPLACE_OLD> 'https://bruth.github.com/husk/',
 <REPLACE_NEW> 'http://husk.github.com/husk/',
 <REPLACE_END> <|endoftext|> import husk
from setuptools import setup, find_packages

kwargs = {
    'packages': find_packages(),
    'include_package_data': True,
    'test_suite': 'tests',
    'name': 'husk',
    'version': husk.__version__,
    'author': 'Byron Ruth, Patrick Henning',
    'author_email': 'b@devel.io',
    'description': husk.__doc__,
    'license': 'BSD',
    'keywords': 'note-taking Cornell',
    'url': 'http://husk.github.com/husk/',
    'scripts': ['bin/husk'],
    'classifiers': [
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7'
    ],
}

setup(**kwargs)

Prompt:
Update URL to point to new repository/website
import husk
from setuptools import setup, find_packages

kwargs = {
    'packages': find_packages(),
    'include_package_data': True,
    'test_suite': 'tests',
    'name': 'husk',
    'version': husk.__version__,
    'author': 'Byron Ruth, Patrick Henning',
    'author_email': 'b@devel.io',
    'description': husk.__doc__,
    'license': 'BSD',
    'keywords': 'note-taking Cornell',
    'url': 'https://bruth.github.com/husk/',
    'scripts': ['bin/husk'],
    'classifiers': [
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7'
    ],
}

setup(**kwargs)


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

# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License

# Standard Library
import collections

# Django
from django.core.management.base import BaseCommand

# wger
from wger.core.models import Language
from wger.exercises.models import ExerciseBase
from wger.utils.constants import ENGLISH_SHORT_NAME

class Command(BaseCommand):
    """
    Performs some sanity checks on the exercise database
    """

    help = """Performs some sanity checks on the database

            At the moment this script checks the following:
            - each base has at least one exercise
            - each exercise base has a translation in English
            - exercise bases have no duplicate translations
            """

    def add_arguments(self, parser):

        # Add dry run argument
        parser.add_argument(
            '--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete problematic exercise bases from the database (use with care!!)',
        )

    def handle(self, **options):

        delete = options['delete']
        english = Language.objects.get(short_name=ENGLISH_SHORT_NAME)

        for base in ExerciseBase.objects.all():

            if not base.exercises.count():
                warning = f'Exercise base {base.uuid} has no translations!'
                self.stdout.write(self.style.WARNING(warning))

                if delete:
                    base.delete()
                    self.stdout.write('  Deleting base...')
                continue

            if not base.exercises.filter(language=english).exists():
                warning = f'Exercise base {base.uuid} has no English translation!'
                self.stdout.write(self.style.WARNING(warning))

                if delete:
                    base.delete()
                    self.stdout.write('  Deleting base...')

            exercise_languages = base.exercises.values_list('language_id', flat=True)
            duplicates = [
                item for item, count in collections.Counter(exercise_languages).items() if count > 1
            ]

            if not duplicates:
                continue

            warning = f'Exercise base {base.uuid} has duplicate translations for language IDs: {duplicates}!'
            self.stdout.write(self.style.WARNING(warning))

            if delete:
                exercises = base.exercises.filter(language_id__in=duplicates)
                for exercise in exercises[1:]:
                    exercise.delete()
                    self.stdout.write(
                        f'  Deleting translation {exercise.uuid} for language ID {exercise.language_id}...'
                    )

Add script to check the current exercise translations

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 *-*

# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License

# Standard Library
import collections

# Django
from django.core.management.base import BaseCommand

# wger
from wger.core.models import Language
from wger.exercises.models import ExerciseBase
from wger.utils.constants import ENGLISH_SHORT_NAME

class Command(BaseCommand):
    """
    Performs some sanity checks on the exercise database
    """

    help = """Performs some sanity checks on the database

            At the moment this script checks the following:
            - each base has at least one exercise
            - each exercise base has a translation in English
            - exercise bases have no duplicate translations
            """

    def add_arguments(self, parser):

        # Add dry run argument
        parser.add_argument(
            '--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete problematic exercise bases from the database (use with care!!)',
        )

    def handle(self, **options):

        delete = options['delete']
        english = Language.objects.get(short_name=ENGLISH_SHORT_NAME)

        for base in ExerciseBase.objects.all():

            if not base.exercises.count():
                warning = f'Exercise base {base.uuid} has no translations!'
                self.stdout.write(self.style.WARNING(warning))

                if delete:
                    base.delete()
                    self.stdout.write('  Deleting base...')
                continue

            if not base.exercises.filter(language=english).exists():
                warning = f'Exercise base {base.uuid} has no English translation!'
                self.stdout.write(self.style.WARNING(warning))

                if delete:
                    base.delete()
                    self.stdout.write('  Deleting base...')

            exercise_languages = base.exercises.values_list('language_id', flat=True)
            duplicates = [
                item for item, count in collections.Counter(exercise_languages).items() if count > 1
            ]

            if not duplicates:
                continue

            warning = f'Exercise base {base.uuid} has duplicate translations for language IDs: {duplicates}!'
            self.stdout.write(self.style.WARNING(warning))

            if delete:
                exercises = base.exercises.filter(language_id__in=duplicates)
                for exercise in exercises[1:]:
                    exercise.delete()
                    self.stdout.write(
                        f'  Deleting translation {exercise.uuid} for language ID {exercise.language_id}...'
                    )
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 *-*

# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License

# Standard Library
import collections

# Django
from django.core.management.base import BaseCommand

# wger
from wger.core.models import Language
from wger.exercises.models import ExerciseBase
from wger.utils.constants import ENGLISH_SHORT_NAME

class Command(BaseCommand):
    """
    Performs some sanity checks on the exercise database
    """

    help = """Performs some sanity checks on the database

            At the moment this script checks the following:
            - each base has at least one exercise
            - each exercise base has a translation in English
            - exercise bases have no duplicate translations
            """

    def add_arguments(self, parser):

        # Add dry run argument
        parser.add_argument(
            '--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete problematic exercise bases from the database (use with care!!)',
        )

    def handle(self, **options):

        delete = options['delete']
        english = Language.objects.get(short_name=ENGLISH_SHORT_NAME)

        for base in ExerciseBase.objects.all():

            if not base.exercises.count():
                warning = f'Exercise base {base.uuid} has no translations!'
                self.stdout.write(self.style.WARNING(warning))

                if delete:
                    base.delete()
                    self.stdout.write('  Deleting base...')
                continue

            if not base.exercises.filter(language=english).exists():
                warning = f'Exercise base {base.uuid} has no English translation!'
                self.stdout.write(self.style.WARNING(warning))

                if delete:
                    base.delete()
                    self.stdout.write('  Deleting base...')

            exercise_languages = base.exercises.values_list('language_id', flat=True)
            duplicates = [
                item for item, count in collections.Counter(exercise_languages).items() if count > 1
            ]

            if not duplicates:
                continue

            warning = f'Exercise base {base.uuid} has duplicate translations for language IDs: {duplicates}!'
            self.stdout.write(self.style.WARNING(warning))

            if delete:
                exercises = base.exercises.filter(language_id__in=duplicates)
                for exercise in exercises[1:]:
                    exercise.delete()
                    self.stdout.write(
                        f'  Deleting translation {exercise.uuid} for language ID {exercise.language_id}...'
                    )

Prompt: Add script to check the current exercise translations


"""
Automated processing of associated exposures
"""

def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True):
    """
    Fetch products from the Grizli AWS bucket.

    Boto3 will require that you have set up your AWS credentials in, e.g.,
    ~/.aws/credentials
    """
    import os
    import boto3

    s3 = boto3.resource('s3')
    s3_client = boto3.client('s3')
    bkt = s3.Bucket(bucket_name)

    files = [obj.key for obj in bkt.objects.filter(Prefix='Pipeline/{0}/Extractions/{0}_{1:05d}{2}'.format(root, id, product))]

    if get_fit_args:
        files += ['Pipeline/{0}/Extractions/fit_args.npy'.format(root)]

    for file in files:
        local = os.path.join(output_path, os.path.basename(file))

        if verbose:
            print('{0} -> {1}'.format(file, output_path))

        if not dryrun:
            if os.path.exists(local) & skip_existing:
                continue

            bkt.download_file(file, local,
                          ExtraArgs={"RequestPayer": "requester"})

Add script to fetch data from AWS

Add script to fetch data from AWS

Response:
<REPLACE_OLD> exposures
"""

 <REPLACE_NEW> exposures
"""

def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True):
    """
    Fetch products from the Grizli AWS bucket.

    Boto3 will require that you have set up your AWS credentials in, e.g.,
    ~/.aws/credentials
    """
    import os
    import boto3

    s3 = boto3.resource('s3')
    s3_client = boto3.client('s3')
    bkt = s3.Bucket(bucket_name)

    files = [obj.key for obj in bkt.objects.filter(Prefix='Pipeline/{0}/Extractions/{0}_{1:05d}{2}'.format(root, id, product))]

    if get_fit_args:
        files += ['Pipeline/{0}/Extractions/fit_args.npy'.format(root)]

    for file in files:
        local = os.path.join(output_path, os.path.basename(file))

        if verbose:
            print('{0} -> {1}'.format(file, output_path))

        if not dryrun:
            if os.path.exists(local) & skip_existing:
                continue

            bkt.download_file(file, local,
                          ExtraArgs={"RequestPayer": "requester"})

 <REPLACE_END> <|endoftext|> """
Automated processing of associated exposures
"""

def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True):
    """
    Fetch products from the Grizli AWS bucket.

    Boto3 will require that you have set up your AWS credentials in, e.g.,
    ~/.aws/credentials
    """
    import os
    import boto3

    s3 = boto3.resource('s3')
    s3_client = boto3.client('s3')
    bkt = s3.Bucket(bucket_name)

    files = [obj.key for obj in bkt.objects.filter(Prefix='Pipeline/{0}/Extractions/{0}_{1:05d}{2}'.format(root, id, product))]

    if get_fit_args:
        files += ['Pipeline/{0}/Extractions/fit_args.npy'.format(root)]

    for file in files:
        local = os.path.join(output_path, os.path.basename(file))

        if verbose:
            print('{0} -> {1}'.format(file, output_path))

        if not dryrun:
            if os.path.exists(local) & skip_existing:
                continue

            bkt.download_file(file, local,
                          ExtraArgs={"RequestPayer": "requester"})

Prompt:
Add script to fetch data from AWS

"""
Automated processing of associated exposures
"""


from s2v1 import *

def number_of_records(data_sample):
	return len(data_sample)

number_of_ties = number_of_records(data_from_csv) - 1 # minus header row

# print(number_of_ties, "ties in our data sample")

def number_of_records2(data_sample):
	return data_sample.size

number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")

Response:
<REPLACE_OLD> row

print(number_of_ties, <REPLACE_NEW> row

# print(number_of_ties, <REPLACE_END> <REPLACE_OLD> number_of_records2(my_csv)
print(number_of_ties_my_csv, <REPLACE_NEW> number_of_records2(my_csv)
# print(number_of_ties_my_csv, <REPLACE_END> <|endoftext|> from s2v1 import *

def number_of_records(data_sample):
	return len(data_sample)

number_of_ties = number_of_records(data_from_csv) - 1 # minus header row

# print(number_of_ties, "ties in our data sample")

def number_of_records2(data_sample):
	return data_sample.size

number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")

Prompt:
Comment out print statements for total number of ties

from s2v1 import *

def number_of_records(data_sample):
	return len(data_sample)

number_of_ties = number_of_records(data_from_csv) - 1 # minus header row

print(number_of_ties, "ties in our data sample")

def number_of_records2(data_sample):
	return data_sample.size

number_of_ties_my_csv = number_of_records2(my_csv)
print(number_of_ties_my_csv, "ties in our data sample")


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from .core import Conveyor

def main():
    Conveyor().run()

if __name__ == "__main__":
    main()

Response:
<REPLACE_OLD> absolute_import

from <REPLACE_NEW> absolute_import
from __future__ import division
from __future__ import unicode_literals

from <REPLACE_END> <REPLACE_OLD> Conveyor().run()

if <REPLACE_NEW> Conveyor().run()

if <REPLACE_END> <|endoftext|> from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from .core import Conveyor

def main():
    Conveyor().run()

if __name__ == "__main__":
    main()

Prompt:
Bring the standard __future__ imports over

from __future__ import absolute_import

from .core import Conveyor

def main():
    Conveyor().run()

if __name__ == "__main__":
    main()


Response:
<REPLACE_OLD> }

    def test_contains_links(self, loaded_request):
        """
        Test that each page contains links to the defined URLs.
        """
        result = utility.get_links_from_page(loaded_request)

        assert "http://iatistandard.org" in result

    @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"])
    def test_login_form_presence(self, target_request):
        """
        Test that there is a valid login form on the CSV2IATI Homepage.
        """
        req = self.loaded_request_from_test_name(target_request)
        form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form'
        form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action'
        input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input'

        forms = utility.locate_xpath_result(req, form_xpath)
        form_action = utility.locate_xpath_result(req, form_action_xpath)
        form_inputs = utility.locate_xpath_result(req, input_xpath)

        assert len(forms) == 1
        assert form_action == ['/login']
        assert len(form_inputs) == 3
 <REPLACE_NEW> }
 <REPLACE_END> <|endoftext|> import pytest
from web_test_base import *

class TestCSV2IATI(WebTestBase):
    requests_to_load = {
        'CSV2IATI Homepage': {
            'url': 'http://csv2iati.iatistandard.org/'
        }
    }

Prompt:
Remove redundant csv2iati test now site has been decommissioned

import pytest
from web_test_base import *

class TestCSV2IATI(WebTestBase):
    requests_to_load = {
        'CSV2IATI Homepage': {
            'url': 'http://csv2iati.iatistandard.org/'
        }
    }

    def test_contains_links(self, loaded_request):
        """
        Test that each page contains links to the defined URLs.
        """
        result = utility.get_links_from_page(loaded_request)

        assert "http://iatistandard.org" in result

    @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"])
    def test_login_form_presence(self, target_request):
        """
        Test that there is a valid login form on the CSV2IATI Homepage.
        """
        req = self.loaded_request_from_test_name(target_request)
        form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form'
        form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action'
        input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input'

        forms = utility.locate_xpath_result(req, form_xpath)
        form_action = utility.locate_xpath_result(req, form_action_xpath)
        form_inputs = utility.locate_xpath_result(req, input_xpath)

        assert len(forms) == 1
        assert form_action == ['/login']
        assert len(form_inputs) == 3


from django.conf.urls import url
from haystack.views import SearchView, basic_search, search_view_factory

from ..forms import AdvancedSearchForm
from ..views.snippets import autocomplete

search_view = search_view_factory(view_class=SearchView,
                                  template='search/advanced_search.html',
                                  form_class=AdvancedSearchForm)

urlpatterns = [
    url(r'^$', basic_search, name='cab_search'),
    url(r'^autocomplete/$', autocomplete, name='snippet_autocomplete'),
    url(r'^advanced/$', search_view, name='cab_search_advanced'),
]

Remove string views in urlpatterns

Remove string views in urlpatterns

Response:
<INSERT> basic_search, <INSERT_END> <REPLACE_OLD> AdvancedSearchForm

search_view <REPLACE_NEW> AdvancedSearchForm
from ..views.snippets import autocomplete

search_view <REPLACE_END> <REPLACE_OLD> url(r'^$',
        'haystack.views.basic_search',
        <REPLACE_NEW> url(r'^$', basic_search, <REPLACE_END> <REPLACE_OLD> url(r'^autocomplete/$',
        'cab.views.snippets.autocomplete',
        <REPLACE_NEW> url(r'^autocomplete/$', autocomplete, <REPLACE_END> <REPLACE_OLD> url(r'^advanced/$',
        search_view,
        <REPLACE_NEW> url(r'^advanced/$', search_view, <REPLACE_END> <|endoftext|> from django.conf.urls import url
from haystack.views import SearchView, basic_search, search_view_factory

from ..forms import AdvancedSearchForm
from ..views.snippets import autocomplete

search_view = search_view_factory(view_class=SearchView,
                                  template='search/advanced_search.html',
                                  form_class=AdvancedSearchForm)

urlpatterns = [
    url(r'^$', basic_search, name='cab_search'),
    url(r'^autocomplete/$', autocomplete, name='snippet_autocomplete'),
    url(r'^advanced/$', search_view, name='cab_search_advanced'),
]

Prompt:
Remove string views in urlpatterns

from django.conf.urls import url
from haystack.views import SearchView, search_view_factory

from ..forms import AdvancedSearchForm

search_view = search_view_factory(view_class=SearchView,
                                  template='search/advanced_search.html',
                                  form_class=AdvancedSearchForm)

urlpatterns = [
    url(r'^$',
        'haystack.views.basic_search',
        name='cab_search'),
    url(r'^autocomplete/$',
        'cab.views.snippets.autocomplete',
        name='snippet_autocomplete'),
    url(r'^advanced/$',
        search_view,
        name='cab_search_advanced'),
]