from django.core.management.base import BaseCommand
from corehq.apps.reminders.models import (CaseReminderHandler,
    UI_COMPLEX, ON_DATETIME, REMINDER_TYPE_DEFAULT,
    RECIPIENT_SURVEY_SAMPLE)
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    """
      The new reminders UI removes support for some edge cases, and the
    purpose of this script is to confirm that there are no reminder
    definitions which use those edge use cases.

    Usage:
        python manage.py check_for_old_reminders
    """
    args = ""
    help = ("A command which checks for edge use cases that are no longer"
        "supported in the new reminders UI")

    def get_reminder_definition_ids(self):
        result = CaseReminderHandler.view(
            "reminders/handlers_by_domain_case_type",
            include_docs=False,
        ).all()
        return [row["id"] for row in result]

    def check_for_ui_type(self, handler):
        if handler.ui_type != UI_COMPLEX:
            print "%s: Handler %s does not have advanced ui flag set" % (
                handler.domain, handler._id)

    def check_for_multiple_fire_time_types(self, handler):
        if len(handler.events) > 1:
            fire_time_type = handler.events[0].fire_time_type
            for event in handler.events[1:]:
                if event.fire_time_type != fire_time_type:
                    print ("%s: Handler %s references multiple fire time "
                        "types" % (handler.domain, handler._id))

    def check_for_datetime_criteria(self, handler):
        if handler.start_condition_type == ON_DATETIME:
            print ("%s: Handler %s starts on datetime criteria and is not a "
                "broadcast" % (handler.domain, handler._id))

    def check_for_case_group_recipient(self, handler):
        if handler.recipient == RECIPIENT_SURVEY_SAMPLE:
            print ("%s: Handler %s sends to case group and is not a "
                "broadcast" % (handler.domain, handler._id))

    def handle(self, *args, **options):
        ids = self.get_reminder_definition_ids()
        for handler_doc in iter_docs(CaseReminderHandler.get_db(), ids):
            handler = CaseReminderHandler.wrap(handler_doc)
            if handler.reminder_type == REMINDER_TYPE_DEFAULT:
                self.check_for_ui_type(handler)
                self.check_for_multiple_fire_time_types(handler)
                self.check_for_datetime_criteria(handler)
                self.check_for_case_group_recipient(handler)

Add script to check for unsupported edge cases

Response:
<REPLACE_OLD>  <REPLACE_NEW> from django.core.management.base import BaseCommand
from corehq.apps.reminders.models import (CaseReminderHandler,
    UI_COMPLEX, ON_DATETIME, REMINDER_TYPE_DEFAULT,
    RECIPIENT_SURVEY_SAMPLE)
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    """
      The new reminders UI removes support for some edge cases, and the
    purpose of this script is to confirm that there are no reminder
    definitions which use those edge use cases.

    Usage:
        python manage.py check_for_old_reminders
    """
    args = ""
    help = ("A command which checks for edge use cases that are no longer"
        "supported in the new reminders UI")

    def get_reminder_definition_ids(self):
        result = CaseReminderHandler.view(
            "reminders/handlers_by_domain_case_type",
            include_docs=False,
        ).all()
        return [row["id"] for row in result]

    def check_for_ui_type(self, handler):
        if handler.ui_type != UI_COMPLEX:
            print "%s: Handler %s does not have advanced ui flag set" % (
                handler.domain, handler._id)

    def check_for_multiple_fire_time_types(self, handler):
        if len(handler.events) > 1:
            fire_time_type = handler.events[0].fire_time_type
            for event in handler.events[1:]:
                if event.fire_time_type != fire_time_type:
                    print ("%s: Handler %s references multiple fire time "
                        "types" % (handler.domain, handler._id))

    def check_for_datetime_criteria(self, handler):
        if handler.start_condition_type == ON_DATETIME:
            print ("%s: Handler %s starts on datetime criteria and is not a "
                "broadcast" % (handler.domain, handler._id))

    def check_for_case_group_recipient(self, handler):
        if handler.recipient == RECIPIENT_SURVEY_SAMPLE:
            print ("%s: Handler %s sends to case group and is not a "
                "broadcast" % (handler.domain, handler._id))

    def handle(self, *args, **options):
        ids = self.get_reminder_definition_ids()
        for handler_doc in iter_docs(CaseReminderHandler.get_db(), ids):
            handler = CaseReminderHandler.wrap(handler_doc)
            if handler.reminder_type == REMINDER_TYPE_DEFAULT:
                self.check_for_ui_type(handler)
                self.check_for_multiple_fire_time_types(handler)
                self.check_for_datetime_criteria(handler)
                self.check_for_case_group_recipient(handler)

 <REPLACE_END> <|endoftext|> from django.core.management.base import BaseCommand
from corehq.apps.reminders.models import (CaseReminderHandler,
    UI_COMPLEX, ON_DATETIME, REMINDER_TYPE_DEFAULT,
    RECIPIENT_SURVEY_SAMPLE)
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    """
      The new reminders UI removes support for some edge cases, and the
    purpose of this script is to confirm that there are no reminder
    definitions which use those edge use cases.

    Usage:
        python manage.py check_for_old_reminders
    """
    args = ""
    help = ("A command which checks for edge use cases that are no longer"
        "supported in the new reminders UI")

    def get_reminder_definition_ids(self):
        result = CaseReminderHandler.view(
            "reminders/handlers_by_domain_case_type",
            include_docs=False,
        ).all()
        return [row["id"] for row in result]

    def check_for_ui_type(self, handler):
        if handler.ui_type != UI_COMPLEX:
            print "%s: Handler %s does not have advanced ui flag set" % (
                handler.domain, handler._id)

    def check_for_multiple_fire_time_types(self, handler):
        if len(handler.events) > 1:
            fire_time_type = handler.events[0].fire_time_type
            for event in handler.events[1:]:
                if event.fire_time_type != fire_time_type:
                    print ("%s: Handler %s references multiple fire time "
                        "types" % (handler.domain, handler._id))

    def check_for_datetime_criteria(self, handler):
        if handler.start_condition_type == ON_DATETIME:
            print ("%s: Handler %s starts on datetime criteria and is not a "
                "broadcast" % (handler.domain, handler._id))

    def check_for_case_group_recipient(self, handler):
        if handler.recipient == RECIPIENT_SURVEY_SAMPLE:
            print ("%s: Handler %s sends to case group and is not a "
                "broadcast" % (handler.domain, handler._id))

    def handle(self, *args, **options):
        ids = self.get_reminder_definition_ids()
        for handler_doc in iter_docs(CaseReminderHandler.get_db(), ids):
            handler = CaseReminderHandler.wrap(handler_doc)
            if handler.reminder_type == REMINDER_TYPE_DEFAULT:
                self.check_for_ui_type(handler)
                self.check_for_multiple_fire_time_types(handler)
                self.check_for_datetime_criteria(handler)
                self.check_for_case_group_recipient(handler)

Prompt: Add script to check for unsupported edge cases


# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend

class CoalesceFilterBackend(DjangoFilterBackend):
    """Support Ember Data coalesceFindRequests."""

    def filter_queryset(self, request, queryset, view):
        raw = request.query_params.get('filter[id]')
        if raw:
            ids = raw.split(',')
            view.pagination_class = None
            queryset = queryset.filter(id__in=ids)
        return queryset

Remove unused score filter backend

Remove unused score filter backend

Response:
<REPLACE_OLD> DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase

class <REPLACE_NEW> DjangoFilterBackend

class <REPLACE_END> <REPLACE_OLD> queryset

class ScoreFilterBackend(DRYPermissionFiltersBase):
    def filter_list_queryset(self, request, queryset, view):
        """Limit all requests to superuser."""
        if request.user.is_authenticated():
            if request.user.is_staff:
                return queryset.all()
            # else:
            #     return queryset.filter(
            #         song__appearance__entry__entity__officers__person__user=request.user,
            #     )
        return queryset.none()
 <REPLACE_NEW> queryset
 <REPLACE_END> <|endoftext|>
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend

class CoalesceFilterBackend(DjangoFilterBackend):
    """Support Ember Data coalesceFindRequests."""

    def filter_queryset(self, request, queryset, view):
        raw = request.query_params.get('filter[id]')
        if raw:
            ids = raw.split(',')
            view.pagination_class = None
            queryset = queryset.filter(id__in=ids)
        return queryset

Prompt:
Remove unused score filter backend

# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase

class CoalesceFilterBackend(DjangoFilterBackend):
    """Support Ember Data coalesceFindRequests."""

    def filter_queryset(self, request, queryset, view):
        raw = request.query_params.get('filter[id]')
        if raw:
            ids = raw.split(',')
            view.pagination_class = None
            queryset = queryset.filter(id__in=ids)
        return queryset

class ScoreFilterBackend(DRYPermissionFiltersBase):
    def filter_list_queryset(self, request, queryset, view):
        """Limit all requests to superuser."""
        if request.user.is_authenticated():
            if request.user.is_staff:
                return queryset.all()
            # else:
            #     return queryset.filter(
            #         song__appearance__entry__entity__officers__person__user=request.user,
            #     )
        return queryset.none()


#!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Parse device output to extract LLVM profile data.

The profile data obtained from the device is raw. Thus, it must be indexed
before it can be used to generate coverage reports.

Typical usage:
    stty -F /dev/ttyUSB0 icanon
    cat /dev/ttyUSB0 | ./device_profile_data.py foo.profraw
    llvm-profdata merge -sparse foo.profraw -o foo.profdata
    llvm-cov show OBJECT_FILE -instr-profile=foo.profdata
"""
import argparse
import zlib
import re
import sys

def extract_profile_data(device_output_file):
    """Parse device output to extract LLVM profile data.

    This function returns the LLVM profile data as a byte array after
    verifying its length and checksum.

    Args:
        device_output_file: File that contains the device output.
    Returns:
        LLVM profile data.
    Raises:
        ValueError: If LLVM profile data cannot be detected in the device
            output or its length or checksum is incorrect.
    """
    lines = device_output_file.read().decode('utf-8', 'ignore').splitlines()
    for i, line in zip(reversed(range(len(lines))), reversed(lines)):
        match = re.match(
            r"""
                LLVM\ profile\ data
                \ \(length:\ (?P<length>\d*),
                \ CRC32:\ (?P<checksum>[0-9A-F]*)\):
            """, line, re.VERBOSE)
        if match:
            exp_length = int(match.group('length'))
            exp_checksum = match.group('checksum')
            byte_array = bytes.fromhex(lines[i + 1])
            break
    # Check if output has LLVM profile data
    if not match:
        raise ValueError(
            'Could not detect the LLVM profile data in device output.')
    # Check length
    act_length = len(byte_array)
    if act_length != exp_length:
        raise ValueError(('Length check failed! ',
                          f'Expected: {exp_length}, actual: {act_length}.'))
    # Check checksum
    act_checksum = zlib.crc32(byte_array).to_bytes(4,
                                                   byteorder='little',
                                                   signed=False).hex().upper()
    if act_checksum != exp_checksum:
        raise ValueError(
            ('Checksum check failed! ',
             f'Expected: {exp_checksum}, actual: {act_checksum}.'))
    return byte_array

def main():
    """Parses command line arguments and extracts the profile data from device
    output."""
    argparser = argparse.ArgumentParser(
        description='Extract LLVM profile data from device output.')
    argparser.add_argument(dest='output_file',
                           type=argparse.FileType('wb'),
                           default=sys.stdout,
                           help='output file for writing LLVM profile data')
    argparser.add_argument('--input_file',
                           type=argparse.FileType('rb'),
                           default=sys.stdin.buffer,
                           help='device output')
    args = argparser.parse_args()

    args.output_file.write(extract_profile_data(args.input_file))

if __name__ == '__main__':
    main()

[util] Implement a script for extracting profile data from device output

This change introduces a python script that extracts profile data from
device output.

Signed-off-by: Alphan Ulusoy <23b245cc5a07aacf75a9db847b24c67dee1707bf@google.com>

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Parse device output to extract LLVM profile data.

The profile data obtained from the device is raw. Thus, it must be indexed
before it can be used to generate coverage reports.

Typical usage:
    stty -F /dev/ttyUSB0 icanon
    cat /dev/ttyUSB0 | ./device_profile_data.py foo.profraw
    llvm-profdata merge -sparse foo.profraw -o foo.profdata
    llvm-cov show OBJECT_FILE -instr-profile=foo.profdata
"""
import argparse
import zlib
import re
import sys

def extract_profile_data(device_output_file):
    """Parse device output to extract LLVM profile data.

    This function returns the LLVM profile data as a byte array after
    verifying its length and checksum.

    Args:
        device_output_file: File that contains the device output.
    Returns:
        LLVM profile data.
    Raises:
        ValueError: If LLVM profile data cannot be detected in the device
            output or its length or checksum is incorrect.
    """
    lines = device_output_file.read().decode('utf-8', 'ignore').splitlines()
    for i, line in zip(reversed(range(len(lines))), reversed(lines)):
        match = re.match(
            r"""
                LLVM\ profile\ data
                \ \(length:\ (?P<length>\d*),
                \ CRC32:\ (?P<checksum>[0-9A-F]*)\):
            """, line, re.VERBOSE)
        if match:
            exp_length = int(match.group('length'))
            exp_checksum = match.group('checksum')
            byte_array = bytes.fromhex(lines[i + 1])
            break
    # Check if output has LLVM profile data
    if not match:
        raise ValueError(
            'Could not detect the LLVM profile data in device output.')
    # Check length
    act_length = len(byte_array)
    if act_length != exp_length:
        raise ValueError(('Length check failed! ',
                          f'Expected: {exp_length}, actual: {act_length}.'))
    # Check checksum
    act_checksum = zlib.crc32(byte_array).to_bytes(4,
                                                   byteorder='little',
                                                   signed=False).hex().upper()
    if act_checksum != exp_checksum:
        raise ValueError(
            ('Checksum check failed! ',
             f'Expected: {exp_checksum}, actual: {act_checksum}.'))
    return byte_array

def main():
    """Parses command line arguments and extracts the profile data from device
    output."""
    argparser = argparse.ArgumentParser(
        description='Extract LLVM profile data from device output.')
    argparser.add_argument(dest='output_file',
                           type=argparse.FileType('wb'),
                           default=sys.stdout,
                           help='output file for writing LLVM profile data')
    argparser.add_argument('--input_file',
                           type=argparse.FileType('rb'),
                           default=sys.stdin.buffer,
                           help='device output')
    args = argparser.parse_args()

    args.output_file.write(extract_profile_data(args.input_file))

if __name__ == '__main__':
    main()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Parse device output to extract LLVM profile data.

The profile data obtained from the device is raw. Thus, it must be indexed
before it can be used to generate coverage reports.

Typical usage:
    stty -F /dev/ttyUSB0 icanon
    cat /dev/ttyUSB0 | ./device_profile_data.py foo.profraw
    llvm-profdata merge -sparse foo.profraw -o foo.profdata
    llvm-cov show OBJECT_FILE -instr-profile=foo.profdata
"""
import argparse
import zlib
import re
import sys

def extract_profile_data(device_output_file):
    """Parse device output to extract LLVM profile data.

    This function returns the LLVM profile data as a byte array after
    verifying its length and checksum.

    Args:
        device_output_file: File that contains the device output.
    Returns:
        LLVM profile data.
    Raises:
        ValueError: If LLVM profile data cannot be detected in the device
            output or its length or checksum is incorrect.
    """
    lines = device_output_file.read().decode('utf-8', 'ignore').splitlines()
    for i, line in zip(reversed(range(len(lines))), reversed(lines)):
        match = re.match(
            r"""
                LLVM\ profile\ data
                \ \(length:\ (?P<length>\d*),
                \ CRC32:\ (?P<checksum>[0-9A-F]*)\):
            """, line, re.VERBOSE)
        if match:
            exp_length = int(match.group('length'))
            exp_checksum = match.group('checksum')
            byte_array = bytes.fromhex(lines[i + 1])
            break
    # Check if output has LLVM profile data
    if not match:
        raise ValueError(
            'Could not detect the LLVM profile data in device output.')
    # Check length
    act_length = len(byte_array)
    if act_length != exp_length:
        raise ValueError(('Length check failed! ',
                          f'Expected: {exp_length}, actual: {act_length}.'))
    # Check checksum
    act_checksum = zlib.crc32(byte_array).to_bytes(4,
                                                   byteorder='little',
                                                   signed=False).hex().upper()
    if act_checksum != exp_checksum:
        raise ValueError(
            ('Checksum check failed! ',
             f'Expected: {exp_checksum}, actual: {act_checksum}.'))
    return byte_array

def main():
    """Parses command line arguments and extracts the profile data from device
    output."""
    argparser = argparse.ArgumentParser(
        description='Extract LLVM profile data from device output.')
    argparser.add_argument(dest='output_file',
                           type=argparse.FileType('wb'),
                           default=sys.stdout,
                           help='output file for writing LLVM profile data')
    argparser.add_argument('--input_file',
                           type=argparse.FileType('rb'),
                           default=sys.stdin.buffer,
                           help='device output')
    args = argparser.parse_args()

    args.output_file.write(extract_profile_data(args.input_file))

if __name__ == '__main__':
    main()

Prompt:
[util] Implement a script for extracting profile data from device output

This change introduces a python script that extracts profile data from
device output.

Signed-off-by: Alphan Ulusoy <23b245cc5a07aacf75a9db847b24c67dee1707bf@google.com>


#!/usr/bin/env python

from __future__ import division

import climate
import lmj.cubes
import pandas as pd
import scipy.signal

logging = climate.get_logger('lowpass')

def lowpass(df, freq=10., order=4):
    '''Filter marker data using a butterworth low-pass filter.

    This method alters the data in `df` in-place.

    Parameters
    ----------
    freq : float, optional
        Use a butterworth filter with this cutoff frequency. Defaults to
        10Hz.
    order : int, optional
        Order of the butterworth filter. Defaults to 4.
    '''
    nyquist = 1 / (2 * pd.Series(df.index).diff().mean())
    assert 0 < freq < nyquist
    passes = 2  # filtfilt makes two passes over the data.
    correct = (2 ** (1 / passes) - 1) ** 0.25
    b, a = scipy.signal.butter(order / passes, (freq / correct) / nyquist)
    for c in df.columns:
        if c.startswith('marker') and c[-1] in 'xyz':
            df.loc[:, c] = scipy.signal.filtfilt(b, a, df[c])

@climate.annotate(
    root='load data files from this directory tree',
    output='save smoothed data files to this directory tree',
    pattern=('process only trials matching this pattern', 'option'),
    freq=('lowpass filter at N Hz', 'option', None, float),
)
def main(root, output, pattern='*', freq=None):
    for t in lmj.cubes.Experiment(root).trials_matching(pattern):
        lowpass(t.df, freq)
        t.save(t.root.replace(root, output))

if __name__ == '__main__':
    climate.call(main)

Split lowpass filtering into another script.

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

from __future__ import division

import climate
import lmj.cubes
import pandas as pd
import scipy.signal

logging = climate.get_logger('lowpass')

def lowpass(df, freq=10., order=4):
    '''Filter marker data using a butterworth low-pass filter.

    This method alters the data in `df` in-place.

    Parameters
    ----------
    freq : float, optional
        Use a butterworth filter with this cutoff frequency. Defaults to
        10Hz.
    order : int, optional
        Order of the butterworth filter. Defaults to 4.
    '''
    nyquist = 1 / (2 * pd.Series(df.index).diff().mean())
    assert 0 < freq < nyquist
    passes = 2  # filtfilt makes two passes over the data.
    correct = (2 ** (1 / passes) - 1) ** 0.25
    b, a = scipy.signal.butter(order / passes, (freq / correct) / nyquist)
    for c in df.columns:
        if c.startswith('marker') and c[-1] in 'xyz':
            df.loc[:, c] = scipy.signal.filtfilt(b, a, df[c])

@climate.annotate(
    root='load data files from this directory tree',
    output='save smoothed data files to this directory tree',
    pattern=('process only trials matching this pattern', 'option'),
    freq=('lowpass filter at N Hz', 'option', None, float),
)
def main(root, output, pattern='*', freq=None):
    for t in lmj.cubes.Experiment(root).trials_matching(pattern):
        lowpass(t.df, freq)
        t.save(t.root.replace(root, output))

if __name__ == '__main__':
    climate.call(main)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from __future__ import division

import climate
import lmj.cubes
import pandas as pd
import scipy.signal

logging = climate.get_logger('lowpass')

def lowpass(df, freq=10., order=4):
    '''Filter marker data using a butterworth low-pass filter.

    This method alters the data in `df` in-place.

    Parameters
    ----------
    freq : float, optional
        Use a butterworth filter with this cutoff frequency. Defaults to
        10Hz.
    order : int, optional
        Order of the butterworth filter. Defaults to 4.
    '''
    nyquist = 1 / (2 * pd.Series(df.index).diff().mean())
    assert 0 < freq < nyquist
    passes = 2  # filtfilt makes two passes over the data.
    correct = (2 ** (1 / passes) - 1) ** 0.25
    b, a = scipy.signal.butter(order / passes, (freq / correct) / nyquist)
    for c in df.columns:
        if c.startswith('marker') and c[-1] in 'xyz':
            df.loc[:, c] = scipy.signal.filtfilt(b, a, df[c])

@climate.annotate(
    root='load data files from this directory tree',
    output='save smoothed data files to this directory tree',
    pattern=('process only trials matching this pattern', 'option'),
    freq=('lowpass filter at N Hz', 'option', None, float),
)
def main(root, output, pattern='*', freq=None):
    for t in lmj.cubes.Experiment(root).trials_matching(pattern):
        lowpass(t.df, freq)
        t.save(t.root.replace(root, output))

if __name__ == '__main__':
    climate.call(main)

Prompt: Split lowpass filtering into another script.


#! /usr/bin/env python

from subprocess import Popen, PIPE

def launch(cmd):
    """
    Fork the specified command, returning a tuple of (stdout, stderr)
    """
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()

def get_stdout(cmd):
    """
    Fork the specified command, returning stdout
    """
    return launch(cmd)[0]

Add a wrapper to get just stdout back

Add a wrapper to get just stdout back

Response:
<REPLACE_OLD> _popen(cmd):
 <REPLACE_NEW> launch(cmd):
 <REPLACE_END> <REPLACE_OLD> stderr=PIPE).communicate()
 <REPLACE_NEW> stderr=PIPE).communicate()

def get_stdout(cmd):
    """
    Fork the specified command, returning stdout
    """
    return launch(cmd)[0]
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python

from subprocess import Popen, PIPE

def launch(cmd):
    """
    Fork the specified command, returning a tuple of (stdout, stderr)
    """
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()

def get_stdout(cmd):
    """
    Fork the specified command, returning stdout
    """
    return launch(cmd)[0]

Prompt:
Add a wrapper to get just stdout back

#! /usr/bin/env python

from subprocess import Popen, PIPE

def _popen(cmd):
    """
    Fork the specified command, returning a tuple of (stdout, stderr)
    """
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()


# Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.

from trac.db import Table, Column

name = 'mastertickets'
version = 2
tables = [
    Table('mastertickets', key=('source','dest'))[
        Column('source', type='integer'),
        Column('dest', type='integer'),
    ],
]

def convert_to_int(data):
    """Convert both source and dest in the mastertickets table to ints."""
    rows = data['mastertickets'][1]
    for i, (n1, n2) in enumerate(rows):
        rows[i] = [int(n1), int(n2)]

migrations = [
    (xrange(1,2), convert_to_int),
]

Fix the migration to actual work.

Fix the migration to actual work.

Response:
<REPLACE_OLD> for row in data['mastertickets'][1]:
     <REPLACE_NEW> rows = data['mastertickets'][1]
 <REPLACE_END> <REPLACE_OLD> enumerate(row):
 <REPLACE_NEW> enumerate(rows):
 <REPLACE_END> <REPLACE_OLD>     row[i] <REPLACE_NEW> rows[i] <REPLACE_END> <|endoftext|> # Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.

from trac.db import Table, Column

name = 'mastertickets'
version = 2
tables = [
    Table('mastertickets', key=('source','dest'))[
        Column('source', type='integer'),
        Column('dest', type='integer'),
    ],
]

def convert_to_int(data):
    """Convert both source and dest in the mastertickets table to ints."""
    rows = data['mastertickets'][1]
    for i, (n1, n2) in enumerate(rows):
        rows[i] = [int(n1), int(n2)]

migrations = [
    (xrange(1,2), convert_to_int),
]

Prompt:
Fix the migration to actual work.
# Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.

from trac.db import Table, Column

name = 'mastertickets'
version = 2
tables = [
    Table('mastertickets', key=('source','dest'))[
        Column('source', type='integer'),
        Column('dest', type='integer'),
    ],
]

def convert_to_int(data):
    """Convert both source and dest in the mastertickets table to ints."""
    for row in data['mastertickets'][1]:
        for i, (n1, n2) in enumerate(row):
            row[i] = [int(n1), int(n2)]

migrations = [
    (xrange(1,2), convert_to_int),
]


from __future__ import absolute_import, division, print_function

from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage

__all__ = ['VispyLayerState']

class VispyLayerState(State):
    """
    A base state object for all Vispy layers
    """

    layer = CallbackProperty()
    visible = CallbackProperty(True)
    zorder = CallbackProperty(0)
    color = CallbackProperty()
    alpha = CallbackProperty()

    def __init__(self, **kwargs):

        super(VispyLayerState, self).__init__(**kwargs)

        self._sync_color = None
        self._sync_alpha = None

        self.add_callback('layer', self._layer_changed)
        self._layer_changed()

        self.add_global_callback(self._notify_layer_update)

    def _notify_layer_update(self, **kwargs):
        message = LayerArtistUpdatedMessage(self)
        if self.layer is not None and self.layer.hub is not None:
            self.layer.hub.broadcast(message)

    def _layer_changed(self):

        if self._sync_color is not None:
            self._sync_color.stop_syncing()

        if self._sync_alpha is not None:
            self._sync_alpha.stop_syncing()

        if self.layer is not None:

            self.color = self.layer.style.color
            self.alpha = self.layer.style.alpha

            self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
            self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')

Response:
<REPLACE_OLD> State

__all__ <REPLACE_NEW> State
from glue.core.message import LayerArtistUpdatedMessage

__all__ <REPLACE_END> <INSERT>     self.add_global_callback(self._notify_layer_update)

    def _notify_layer_update(self, **kwargs):
        message = LayerArtistUpdatedMessage(self)
        if self.layer is not None and self.layer.hub is not None:
            self.layer.hub.broadcast(message)

    <INSERT_END> <|endoftext|> from __future__ import absolute_import, division, print_function

from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage

__all__ = ['VispyLayerState']

class VispyLayerState(State):
    """
    A base state object for all Vispy layers
    """

    layer = CallbackProperty()
    visible = CallbackProperty(True)
    zorder = CallbackProperty(0)
    color = CallbackProperty()
    alpha = CallbackProperty()

    def __init__(self, **kwargs):

        super(VispyLayerState, self).__init__(**kwargs)

        self._sync_color = None
        self._sync_alpha = None

        self.add_callback('layer', self._layer_changed)
        self._layer_changed()

        self.add_global_callback(self._notify_layer_update)

    def _notify_layer_update(self, **kwargs):
        message = LayerArtistUpdatedMessage(self)
        if self.layer is not None and self.layer.hub is not None:
            self.layer.hub.broadcast(message)

    def _layer_changed(self):

        if self._sync_color is not None:
            self._sync_color.stop_syncing()

        if self._sync_alpha is not None:
            self._sync_alpha.stop_syncing()

        if self.layer is not None:

            self.color = self.layer.style.color
            self.alpha = self.layer.style.alpha

            self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
            self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')

Prompt:
Make sure layer artist icon updates when changing the color mode or colormaps
from __future__ import absolute_import, division, print_function

from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State

__all__ = ['VispyLayerState']

class VispyLayerState(State):
    """
    A base state object for all Vispy layers
    """

    layer = CallbackProperty()
    visible = CallbackProperty(True)
    zorder = CallbackProperty(0)
    color = CallbackProperty()
    alpha = CallbackProperty()

    def __init__(self, **kwargs):

        super(VispyLayerState, self).__init__(**kwargs)

        self._sync_color = None
        self._sync_alpha = None

        self.add_callback('layer', self._layer_changed)
        self._layer_changed()

    def _layer_changed(self):

        if self._sync_color is not None:
            self._sync_color.stop_syncing()

        if self._sync_alpha is not None:
            self._sync_alpha.stop_syncing()

        if self.layer is not None:

            self.color = self.layer.style.color
            self.alpha = self.layer.style.alpha

            self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
            self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')


from distutils.core import Extension, setup

try:
    from Cython.Build import cythonize
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = cythonize([
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ])

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    license='MIT',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)

Use "cythonize" if Cython is installed.

Use "cythonize" if Cython is installed.

Response:
<INSERT> Cython.Build import cythonize
    from <INSERT_END> <REPLACE_OLD> [
 <REPLACE_NEW> cythonize([
 <REPLACE_END> <REPLACE_OLD> ]

 <REPLACE_NEW> ])

 <REPLACE_END> <|endoftext|> from distutils.core import Extension, setup

try:
    from Cython.Build import cythonize
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = cythonize([
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ])

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    license='MIT',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)

Prompt:
Use "cythonize" if Cython is installed.

from distutils.core import Extension, setup

try:
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ]

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    license='MIT',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)


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

"""
{{cookiecutter.repo_name}}
============================

The root of :class:`{{cookiecutter.app_class_name}}` is created from the kv file.
"""

import kivy
kivy.require('{{cookiecutter.kivy_version}}')

from kivy.app import App

class {{cookiecutter.app_class_name}}(App):
    """Basic Kivy App with a user defined title."""

    title = '{{cookiecutter.app_title}}'

    def build(self):
        return self.root

Implement a basic kivy application

Implement a basic kivy application

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

"""
{{cookiecutter.repo_name}}
============================

The root of :class:`{{cookiecutter.app_class_name}}` is created from the kv file.
"""

import kivy
kivy.require('{{cookiecutter.kivy_version}}')

from kivy.app import App

class {{cookiecutter.app_class_name}}(App):
 <INSERT_END> <INSERT>   """Basic Kivy App with a user defined title."""

    title = '{{cookiecutter.app_title}}'

    def build(self):
        return self.root
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

"""
{{cookiecutter.repo_name}}
============================

The root of :class:`{{cookiecutter.app_class_name}}` is created from the kv file.
"""

import kivy
kivy.require('{{cookiecutter.kivy_version}}')

from kivy.app import App

class {{cookiecutter.app_class_name}}(App):
    """Basic Kivy App with a user defined title."""

    title = '{{cookiecutter.app_title}}'

    def build(self):
        return self.root

Prompt: Implement a basic kivy application


from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from social.app.models.author import Author

class FriendRequestsListView(generic.ListView):
    context_object_name = "all_friend_requests"
    template_name = "app/friend_requests_list.html"

    def get_queryset(self):
        return self.request.user.profile.incoming_friend_requests.all()

    def post(self, request):
        logged_in_author = self.request.user.profile
        accepted_friend_requests = request.POST.getlist('accepted_friend_requests')

        for new_friend_id in accepted_friend_requests:
            new_friend = Author.objects.get(id=new_friend_id)

            if new_friend.node.local:
                logged_in_author.accept_friend_request(new_friend)
            else:
                r = new_friend.node.post_friend_request(request, logged_in_author, new_friend)

                if 200 <= r.status_code < 300:
                    # Success!
                    logged_in_author.accept_friend_request(new_friend)
                else:
                    r.raise_for_status()

        logged_in_author.save()

        return HttpResponseRedirect(reverse("app:friend-requests-list"))

Put in a raise for status for now

Put in a raise for status for now

Response:
<REPLACE_OLD> # This one didn't work. Oh well! No easy way to show an error without ruining other accepts
                    pass

 <REPLACE_NEW> r.raise_for_status()

 <REPLACE_END> <|endoftext|> from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from social.app.models.author import Author

class FriendRequestsListView(generic.ListView):
    context_object_name = "all_friend_requests"
    template_name = "app/friend_requests_list.html"

    def get_queryset(self):
        return self.request.user.profile.incoming_friend_requests.all()

    def post(self, request):
        logged_in_author = self.request.user.profile
        accepted_friend_requests = request.POST.getlist('accepted_friend_requests')

        for new_friend_id in accepted_friend_requests:
            new_friend = Author.objects.get(id=new_friend_id)

            if new_friend.node.local:
                logged_in_author.accept_friend_request(new_friend)
            else:
                r = new_friend.node.post_friend_request(request, logged_in_author, new_friend)

                if 200 <= r.status_code < 300:
                    # Success!
                    logged_in_author.accept_friend_request(new_friend)
                else:
                    r.raise_for_status()

        logged_in_author.save()

        return HttpResponseRedirect(reverse("app:friend-requests-list"))

Prompt:
Put in a raise for status for now

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from social.app.models.author import Author

class FriendRequestsListView(generic.ListView):
    context_object_name = "all_friend_requests"
    template_name = "app/friend_requests_list.html"

    def get_queryset(self):
        return self.request.user.profile.incoming_friend_requests.all()

    def post(self, request):
        logged_in_author = self.request.user.profile
        accepted_friend_requests = request.POST.getlist('accepted_friend_requests')

        for new_friend_id in accepted_friend_requests:
            new_friend = Author.objects.get(id=new_friend_id)

            if new_friend.node.local:
                logged_in_author.accept_friend_request(new_friend)
            else:
                r = new_friend.node.post_friend_request(request, logged_in_author, new_friend)

                if 200 <= r.status_code < 300:
                    # Success!
                    logged_in_author.accept_friend_request(new_friend)
                else:
                    # This one didn't work. Oh well! No easy way to show an error without ruining other accepts
                    pass

        logged_in_author.save()

        return HttpResponseRedirect(reverse("app:friend-requests-list"))


import requests
MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv"
DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv"
MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv"

def get_events(is_iq: bool=False) -> list:
    """Get a list of iq events or edr events.

    Args:
        is_iq: True for vex iq tournaments, False for vex edr(default).

    Returns:
        A 2D array of the events.

    """
    data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1]
    if is_iq:
        return [match.split(",") for match in data if u"re-viqc" in match]
    else:
        return [match.split(",") for match in data if u"re-vrc" in match]

def get_divisions(event_id: str) -> list:
    """Get a list of the divisions of an event.

    Args:
        event_id: The id of the event.

    Returns:
        A 2D array of the divisions.

    """
    data = requests.get(DIVISION_URL.format(event_id)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

def get_matches(event_id: str, division: str) -> list:
    """Get a list of the matches in a divisions of an event.

    Args:
        event_id: The id of the event.
        division: The division id.

    Returns:
        A 2D array of the matches.

    """
    data = requests.get(MATCH_URL.format(
        event_id, division)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

Add comments to vex via wrapper

Add comments to vex via wrapper

Response:
<REPLACE_OLD> get_events(iq=False):
 <REPLACE_NEW> get_events(is_iq: bool=False) -> list:
    """Get a list of iq events or edr events.

    Args:
        is_iq: True for vex iq tournaments, False for vex edr(default).

    Returns:
        A 2D array of the events.

    """
 <REPLACE_END> <REPLACE_OLD> iq:
 <REPLACE_NEW> is_iq:
 <REPLACE_END> <REPLACE_OLD> get_divisions(event_id):
 <REPLACE_NEW> get_divisions(event_id: str) -> list:
    """Get a list of the divisions of an event.

    Args:
        event_id: The id of the event.

    Returns:
        A 2D array of the divisions.

    """
 <REPLACE_END> <REPLACE_OLD> get_matches(event_id, division):
 <REPLACE_NEW> get_matches(event_id: str, division: str) -> list:
    """Get a list of the matches in a divisions of an event.

    Args:
        event_id: The id of the event.
        division: The division id.

    Returns:
        A 2D array of the matches.

    """
 <REPLACE_END> <|endoftext|> import requests
MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv"
DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv"
MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv"

def get_events(is_iq: bool=False) -> list:
    """Get a list of iq events or edr events.

    Args:
        is_iq: True for vex iq tournaments, False for vex edr(default).

    Returns:
        A 2D array of the events.

    """
    data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1]
    if is_iq:
        return [match.split(",") for match in data if u"re-viqc" in match]
    else:
        return [match.split(",") for match in data if u"re-vrc" in match]

def get_divisions(event_id: str) -> list:
    """Get a list of the divisions of an event.

    Args:
        event_id: The id of the event.

    Returns:
        A 2D array of the divisions.

    """
    data = requests.get(DIVISION_URL.format(event_id)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

def get_matches(event_id: str, division: str) -> list:
    """Get a list of the matches in a divisions of an event.

    Args:
        event_id: The id of the event.
        division: The division id.

    Returns:
        A 2D array of the matches.

    """
    data = requests.get(MATCH_URL.format(
        event_id, division)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

Prompt:
Add comments to vex via wrapper

import requests
MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv"
DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv"
MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv"

def get_events(iq=False):
    data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1]
    if iq:
        return [match.split(",") for match in data if u"re-viqc" in match]
    else:
        return [match.split(",") for match in data if u"re-vrc" in match]

def get_divisions(event_id):
    data = requests.get(DIVISION_URL.format(event_id)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]

def get_matches(event_id, division):
    data = requests.get(MATCH_URL.format(
        event_id, division)).text.split("\r\n")[1:-1]
    return [division.split(",") for division in data]


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

from django.db import migrations

from extra_countries.models import ExtraCountry

def add_currencies_with_countries(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Currency = apps.get_model("currencies", "Currency")

    for extra_country in ExtraCountry.objects.all():
        print("seeding currency for county: %s" % extra_country.country.name)
        # trying to find a currency with the same code first
        try:
            currency = Currency.objects.get(code=extra_country.country.currency)
        except Currency.DoesNotExist: # no such currency yet
            currency = Currency(code=extra_country.country.currency,
                                name=extra_country.country.currency_name)
            if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''):
                pass
            else:
                currency.save()
                currency.countries.add(extra_country.pk)

def reverse_data(apps, schema_editor):
    Currency = apps.get_model("currencies", "Currency")
    Currency.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('currencies', '0002_currency_countries'),
    ]

    operations = [
        migrations.RunPython(add_currencies_with_countries, reverse_data)
    ]

Response:
<INSERT> if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''):
                pass
            else:
                <INSERT_END> <INSERT>         <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations

from extra_countries.models import ExtraCountry

def add_currencies_with_countries(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Currency = apps.get_model("currencies", "Currency")

    for extra_country in ExtraCountry.objects.all():
        print("seeding currency for county: %s" % extra_country.country.name)
        # trying to find a currency with the same code first
        try:
            currency = Currency.objects.get(code=extra_country.country.currency)
        except Currency.DoesNotExist: # no such currency yet
            currency = Currency(code=extra_country.country.currency,
                                name=extra_country.country.currency_name)
            if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''):
                pass
            else:
                currency.save()
                currency.countries.add(extra_country.pk)

def reverse_data(apps, schema_editor):
    Currency = apps.get_model("currencies", "Currency")
    Currency.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('currencies', '0002_currency_countries'),
    ]

    operations = [
        migrations.RunPython(add_currencies_with_countries, reverse_data)
    ]

Prompt:
Fix currencies seeding, so it won't have empty currencies

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

from django.db import migrations

from extra_countries.models import ExtraCountry

def add_currencies_with_countries(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Currency = apps.get_model("currencies", "Currency")

    for extra_country in ExtraCountry.objects.all():
        print("seeding currency for county: %s" % extra_country.country.name)
        # trying to find a currency with the same code first
        try:
            currency = Currency.objects.get(code=extra_country.country.currency)
        except Currency.DoesNotExist: # no such currency yet
            currency = Currency(code=extra_country.country.currency,
                                name=extra_country.country.currency_name)
            currency.save()
        currency.countries.add(extra_country.pk)

def reverse_data(apps, schema_editor):
    Currency = apps.get_model("currencies", "Currency")
    Currency.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('currencies', '0002_currency_countries'),
    ]

    operations = [
        migrations.RunPython(add_currencies_with_countries, reverse_data)
    ]


Remove a line of debugging code

Remove a line of debugging code

Response:
<REPLACE_OLD> range(h)])

f = EuclidField((3, 3), (0, 0), [(1,1)])
 <REPLACE_NEW> range(h)])
 <REPLACE_END> <|endoftext|> from __future__ import division # for Python 2.x compatibility
import numpy

class EuclidField(object):
    p = 5.0
    r = 30.0
    @staticmethod
    def dist(x, y):
        return numpy.hypot(x[0]-y[0], x[1]-y[1])
    def __init__(self, size, dst, obstacles):
        w, h = size
        self.shape = (h, w)
        self.dst = dst
        self.obstacles = obstacles
    def __getitem__(self, q):
        i, j = q
        h, w = self.shape
        if not (i in range(h) and j in range(w)):
            raise IndexError
        base = self.dist(q, self.dst)
        k = 0.0
        p = self.p
        for obj in self.obstacles:
            dist_to_obj = self.dist(q, obj)
            if dist_to_obj <= p:
                k += (1/dist_to_obj - 1/p)**2
        return (1.0 + k) * base**2 + self.r*k
    def __array__(self):
        h, w = self.shape
        return numpy.array([[self[i, j] for j in range(w)] for i in range(h)])

Prompt:
Remove a line of debugging code

from __future__ import division # for Python 2.x compatibility
import numpy

class EuclidField(object):
    p = 5.0
    r = 30.0
    @staticmethod
    def dist(x, y):
        return numpy.hypot(x[0]-y[0], x[1]-y[1])
    def __init__(self, size, dst, obstacles):
        w, h = size
        self.shape = (h, w)
        self.dst = dst
        self.obstacles = obstacles
    def __getitem__(self, q):
        i, j = q
        h, w = self.shape
        if not (i in range(h) and j in range(w)):
            raise IndexError
        base = self.dist(q, self.dst)
        k = 0.0
        p = self.p
        for obj in self.obstacles:
            dist_to_obj = self.dist(q, obj)
            if dist_to_obj <= p:
                k += (1/dist_to_obj - 1/p)**2
        return (1.0 + k) * base**2 + self.r*k
    def __array__(self):
        h, w = self.shape
        return numpy.array([[self[i, j] for j in range(w)] for i in range(h)])

f = EuclidField((3, 3), (0, 0), [(1,1)])


import numpy
from thinc.api import HashEmbed

def test_init():
    model = HashEmbed(64, 1000).initialize()
    assert model.get_dim("nV") == 1000
    assert model.get_dim("nO") == 64
    assert model.get_param("E").shape == (1000, 64)

def test_seed_changes_bucket():
    model1 = HashEmbed(64, 1000, seed=2).initialize()
    model2 = HashEmbed(64, 1000, seed=1).initialize()
    arr = numpy.ones((1,), dtype="uint64")
    vector1 = model1.predict(arr)
    vector2 = model2.predict(arr)
    assert vector1.sum() != vector2.sum()

Fix off-by-one in HashEmbed test

Fix off-by-one in HashEmbed test

Response:
<REPLACE_OLD> (1001, <REPLACE_NEW> (1000, <REPLACE_END> <|endoftext|> import numpy
from thinc.api import HashEmbed

def test_init():
    model = HashEmbed(64, 1000).initialize()
    assert model.get_dim("nV") == 1000
    assert model.get_dim("nO") == 64
    assert model.get_param("E").shape == (1000, 64)

def test_seed_changes_bucket():
    model1 = HashEmbed(64, 1000, seed=2).initialize()
    model2 = HashEmbed(64, 1000, seed=1).initialize()
    arr = numpy.ones((1,), dtype="uint64")
    vector1 = model1.predict(arr)
    vector2 = model2.predict(arr)
    assert vector1.sum() != vector2.sum()

Prompt:
Fix off-by-one in HashEmbed test

import numpy
from thinc.api import HashEmbed

def test_init():
    model = HashEmbed(64, 1000).initialize()
    assert model.get_dim("nV") == 1000
    assert model.get_dim("nO") == 64
    assert model.get_param("E").shape == (1001, 64)

def test_seed_changes_bucket():
    model1 = HashEmbed(64, 1000, seed=2).initialize()
    model2 = HashEmbed(64, 1000, seed=1).initialize()
    arr = numpy.ones((1,), dtype="uint64")
    vector1 = model1.predict(arr)
    vector2 = model2.predict(arr)
    assert vector1.sum() != vector2.sum()


#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.4',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely',
                        'psycopg2',
                        'keyrings.alt',
                        'pandas >=0.19.1, <=0.19.1'])

Add pandas as required package

Add pandas as required package

Response:
<REPLACE_OLD> 'keyrings.alt'])
 <REPLACE_NEW> 'keyrings.alt',
                        'pandas >=0.19.1, <=0.19.1'])
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.4',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely',
                        'psycopg2',
                        'keyrings.alt',
                        'pandas >=0.19.1, <=0.19.1'])

Prompt:
Add pandas as required package

#! /usr/bin/env python

from setuptools import find_packages, setup

setup(name='oemof.db',
      version='0.0.4',
      description='The oemof database extension',
      namespace_package = ['oemof'],
      packages=find_packages(),
      package_dir={'oemof': 'oemof'},
      install_requires=['sqlalchemy >= 1.0',
                        'keyring >= 4.0',
                        'shapely',
                        'psycopg2',
                        'keyrings.alt'])


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
uData
'''
from __future__ import unicode_literals

__version__ = '1.6.0.dev'
__description__ = 'Open data portal'

Set base version to 1.6

Set base version to 1.6

Response:
<REPLACE_OLD> '1.5.1.dev'
__description__ <REPLACE_NEW> '1.6.0.dev'
__description__ <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
uData
'''
from __future__ import unicode_literals

__version__ = '1.6.0.dev'
__description__ = 'Open data portal'

Prompt:
Set base version to 1.6

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
uData
'''
from __future__ import unicode_literals

__version__ = '1.5.1.dev'
__description__ = 'Open data portal'


packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []

class packetHook(object):
	def __init__(self, pktType, pktSubtype):
		self.pktType = pktType
		self.pktSubtype = pktSubtype

	def __call__(self, f):
		global packetFunctions
		if (self.pktType, self.pktSubtype) not in packetFunctions:
			packetFunctions[(self.pktType, self.pktSubtype)] = []
		packetFunctions[(self.pktType, self.pktSubtype)].append(f)

class commandHook(object):
	"""docstring for commandHook"""
	def __init__(self, command):
		self.command = command

	def __call__(self, f):
		global commands
		commands[self.command] = f

def onStartHook(f):
	global onStart
	onStart.append(f)
	return f

def onConnectionHook(f):
	global onConnection
	onConnection.append(f)
	return f

def onConnectionLossHook(f):
	global onConnectionLoss
	onConnectionLoss.append(f)
	return f

Allow mutiple hooks for packets

Allow mutiple hooks for packets

Response:
<REPLACE_OLD> packetFunctions
		packetFunctions[(self.pktType, <REPLACE_NEW> packetFunctions
		if (self.pktType, self.pktSubtype) not in packetFunctions:
			packetFunctions[(self.pktType, <REPLACE_END> <REPLACE_OLD> f

class <REPLACE_NEW> []
		packetFunctions[(self.pktType, self.pktSubtype)].append(f)

class <REPLACE_END> <|endoftext|> packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []

class packetHook(object):
	def __init__(self, pktType, pktSubtype):
		self.pktType = pktType
		self.pktSubtype = pktSubtype

	def __call__(self, f):
		global packetFunctions
		if (self.pktType, self.pktSubtype) not in packetFunctions:
			packetFunctions[(self.pktType, self.pktSubtype)] = []
		packetFunctions[(self.pktType, self.pktSubtype)].append(f)

class commandHook(object):
	"""docstring for commandHook"""
	def __init__(self, command):
		self.command = command

	def __call__(self, f):
		global commands
		commands[self.command] = f

def onStartHook(f):
	global onStart
	onStart.append(f)
	return f

def onConnectionHook(f):
	global onConnection
	onConnection.append(f)
	return f

def onConnectionLossHook(f):
	global onConnectionLoss
	onConnectionLoss.append(f)
	return f

Prompt:
Allow mutiple hooks for packets

packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []

class packetHook(object):
	def __init__(self, pktType, pktSubtype):
		self.pktType = pktType
		self.pktSubtype = pktSubtype

	def __call__(self, f):
		global packetFunctions
		packetFunctions[(self.pktType, self.pktSubtype)] = f

class commandHook(object):
	"""docstring for commandHook"""
	def __init__(self, command):
		self.command = command

	def __call__(self, f):
		global commands
		commands[self.command] = f

def onStartHook(f):
	global onStart
	onStart.append(f)
	return f

def onConnectionHook(f):
	global onConnection
	onConnection.append(f)
	return f

def onConnectionLossHook(f):
	global onConnectionLoss
	onConnectionLoss.append(f)
	return f


#!/usr/bin/env python
from __future__ import print_function

from stompy.spatial import join_features
from optparse import OptionParser

try:
    from osgeo import ogr
except ImportError:
    import ogr

# # How to use this:
# ### Load shapefile
# ods = ogr.Open("/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped.shp")
# output = "/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped-merged.shp"
# orig_layer = ods.GetLayer(0)
# ## process it
# process_layer(orig_layer,output)

if __name__ == '__main__':

    parser = OptionParser(usage="usage: %prog [options] input.shp output.shp")
    parser.add_option("-p", "--poly",
                      help="create polygons from closed linestrings",
                      action="store_true",
                      dest='create_polygons',default=False)
    parser.add_option("-a", "--arc", dest="close_arc", default=False,
                      action="store_true",
                      help="close the largest open linestring with a circular arc")
    parser.add_option("-t","--tolerance", dest="tolerance", type="float", default=0.0,
                      metavar="DISTANCE",
                      help="Tolerance for joining two endpoints, in geographic units")
    parser.add_option("-m","--multiple", dest="single_feature", default=True,
                      action="store_false",metavar="SINGLE_FEATURE")

    (options, args) = parser.parse_args()
    input_shp,output_shp = args

    ods = ogr.Open(input_shp)
    layer = ods.GetLayer(0)

    join_features.process_layer(layer,output_shp,
                                create_polygons=options.create_polygons,close_arc=options.close_arc,
                                tolerance=options.tolerance,single_feature=options.single_feature)

Add CLI for joining lines to polygons

Add CLI for joining lines to polygons

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
from __future__ import print_function

from stompy.spatial import join_features
from optparse import OptionParser

try:
    from osgeo import ogr
except ImportError:
    import ogr

# # How to use this:
# ### Load shapefile
# ods = ogr.Open("/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped.shp")
# output = "/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped-merged.shp"
# orig_layer = ods.GetLayer(0)
# ## process it
# process_layer(orig_layer,output)

if __name__ == '__main__':

    parser = OptionParser(usage="usage: %prog [options] input.shp output.shp")
    parser.add_option("-p", "--poly",
                      help="create polygons from closed linestrings",
                      action="store_true",
                      dest='create_polygons',default=False)
    parser.add_option("-a", "--arc", dest="close_arc", default=False,
                      action="store_true",
                      help="close the largest open linestring with a circular arc")
    parser.add_option("-t","--tolerance", dest="tolerance", type="float", default=0.0,
                      metavar="DISTANCE",
                      help="Tolerance for joining two endpoints, in geographic units")
    parser.add_option("-m","--multiple", dest="single_feature", default=True,
                      action="store_false",metavar="SINGLE_FEATURE")

    (options, args) = parser.parse_args()
    input_shp,output_shp = args

    ods = ogr.Open(input_shp)
    layer = ods.GetLayer(0)

    join_features.process_layer(layer,output_shp,
                                create_polygons=options.create_polygons,close_arc=options.close_arc,
                                tolerance=options.tolerance,single_feature=options.single_feature)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from __future__ import print_function

from stompy.spatial import join_features
from optparse import OptionParser

try:
    from osgeo import ogr
except ImportError:
    import ogr

# # How to use this:
# ### Load shapefile
# ods = ogr.Open("/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped.shp")
# output = "/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/pacific_medium_shoreline-cropped-merged.shp"
# orig_layer = ods.GetLayer(0)
# ## process it
# process_layer(orig_layer,output)

if __name__ == '__main__':

    parser = OptionParser(usage="usage: %prog [options] input.shp output.shp")
    parser.add_option("-p", "--poly",
                      help="create polygons from closed linestrings",
                      action="store_true",
                      dest='create_polygons',default=False)
    parser.add_option("-a", "--arc", dest="close_arc", default=False,
                      action="store_true",
                      help="close the largest open linestring with a circular arc")
    parser.add_option("-t","--tolerance", dest="tolerance", type="float", default=0.0,
                      metavar="DISTANCE",
                      help="Tolerance for joining two endpoints, in geographic units")
    parser.add_option("-m","--multiple", dest="single_feature", default=True,
                      action="store_false",metavar="SINGLE_FEATURE")

    (options, args) = parser.parse_args()
    input_shp,output_shp = args

    ods = ogr.Open(input_shp)
    layer = ods.GetLayer(0)

    join_features.process_layer(layer,output_shp,
                                create_polygons=options.create_polygons,close_arc=options.close_arc,
                                tolerance=options.tolerance,single_feature=options.single_feature)

Prompt: Add CLI for joining lines to polygons


from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile

class UserProfileForm(ModelForm):
    first_name = CharField(label='First name', required=False)
    last_name = CharField(label='Last name', required=False)

    class Meta:
        model = UserProfile
        # Don't allow users edit someone else's user page,
        # or to whitelist themselves
        exclude = ('user', 'whitelisted',)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.is_bound:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name

    def save(self):
        first_name = self.cleaned_data.pop('first_name', None)
        last_name = self.cleaned_data.pop('last_name', None)
        profile = super(UserProfileForm, self).save()
        user = profile.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return profile

Response:
<REPLACE_OLD> required=False)

 <REPLACE_NEW> required=False)

 <REPLACE_END> <REPLACE_OLD> 'whitelisted',)

 <REPLACE_NEW> 'whitelisted',)

 <REPLACE_END> <REPLACE_OLD> self.instance:
 <REPLACE_NEW> self.is_bound:
 <REPLACE_END> <REPLACE_OLD> profile <REPLACE_NEW> profile
 <REPLACE_END> <|endoftext|> from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile

class UserProfileForm(ModelForm):
    first_name = CharField(label='First name', required=False)
    last_name = CharField(label='Last name', required=False)

    class Meta:
        model = UserProfile
        # Don't allow users edit someone else's user page,
        # or to whitelist themselves
        exclude = ('user', 'whitelisted',)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.is_bound:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name

    def save(self):
        first_name = self.cleaned_data.pop('first_name', None)
        last_name = self.cleaned_data.pop('last_name', None)
        profile = super(UserProfileForm, self).save()
        user = profile.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return profile

Prompt:
Fix profile creation. (Need tests badly).
from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile

class UserProfileForm(ModelForm):
    first_name = CharField(label='First name', required=False)
    last_name = CharField(label='Last name', required=False)

    class Meta:
        model = UserProfile
        # Don't allow users edit someone else's user page,
        # or to whitelist themselves
        exclude = ('user', 'whitelisted',)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name

    def save(self):
        first_name = self.cleaned_data.pop('first_name', None)
        last_name = self.cleaned_data.pop('last_name', None)
        profile = super(UserProfileForm, self).save()
        user = profile.user
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return profile


from setuptools import find_packages, setup

import versioneer

setup(
    name="bmipy",
    version=versioneer.get_version(),
    description="Basic Model Interface for Python",
    author="Eric Hutton",
    author_email="huttone@colorado.edu",
    url="http://csdms.colorado.edu",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Physics",
    ],
    setup_requires=["setuptools"],
    install_requires=["numpy"],
    packages=find_packages(),
    cmdclass=versioneer.get_cmdclass(),
)

Add numpy as an install requirement.

Add numpy as an install requirement.

Response:
<INSERT> install_requires=["numpy"],
    <INSERT_END> <|endoftext|> from setuptools import find_packages, setup

import versioneer

setup(
    name="bmipy",
    version=versioneer.get_version(),
    description="Basic Model Interface for Python",
    author="Eric Hutton",
    author_email="huttone@colorado.edu",
    url="http://csdms.colorado.edu",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Physics",
    ],
    setup_requires=["setuptools"],
    install_requires=["numpy"],
    packages=find_packages(),
    cmdclass=versioneer.get_cmdclass(),
)

Prompt:
Add numpy as an install requirement.

from setuptools import find_packages, setup

import versioneer

setup(
    name="bmipy",
    version=versioneer.get_version(),
    description="Basic Model Interface for Python",
    author="Eric Hutton",
    author_email="huttone@colorado.edu",
    url="http://csdms.colorado.edu",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Physics",
    ],
    setup_requires=["setuptools"],
    packages=find_packages(),
    cmdclass=versioneer.get_cmdclass(),
)


# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

def readfile(fname):
    with open(os.path.join(os.path.dirname(__file__), fname)) as f:
        return f.read()

setup(
    name="imagesort",
    version="0.2.0",
    packages=find_packages(),
    install_requires=[
        'ExifRead>=1.4.0',
    ],
    include_package_data=True,

    author="Børge Lanes",
    author_email="borge.lanes@gmail.com",
    description=('Organize image files by date taken'),
    long_description=readfile("README.rst"),
    license="MIT",
    keywords="media",
    url="https://github.com/leinz/imagesort",

    entry_points={
        'console_scripts': [
            'imagesort = imagesort.imagesort:main',
        ]
    },

    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Topic :: Multimedia',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
    ],
)

Mark package as OS independent

Mark package as OS independent

Response:
<REPLACE_OLD> POSIX',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: MacOS :: MacOS X',
 <REPLACE_NEW> OS Independent',
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

def readfile(fname):
    with open(os.path.join(os.path.dirname(__file__), fname)) as f:
        return f.read()

setup(
    name="imagesort",
    version="0.2.0",
    packages=find_packages(),
    install_requires=[
        'ExifRead>=1.4.0',
    ],
    include_package_data=True,

    author="Børge Lanes",
    author_email="borge.lanes@gmail.com",
    description=('Organize image files by date taken'),
    long_description=readfile("README.rst"),
    license="MIT",
    keywords="media",
    url="https://github.com/leinz/imagesort",

    entry_points={
        'console_scripts': [
            'imagesort = imagesort.imagesort:main',
        ]
    },

    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Topic :: Multimedia',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
    ],
)

Prompt:
Mark package as OS independent

# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

def readfile(fname):
    with open(os.path.join(os.path.dirname(__file__), fname)) as f:
        return f.read()

setup(
    name="imagesort",
    version="0.2.0",
    packages=find_packages(),
    install_requires=[
        'ExifRead>=1.4.0',
    ],
    include_package_data=True,

    author="Børge Lanes",
    author_email="borge.lanes@gmail.com",
    description=('Organize image files by date taken'),
    long_description=readfile("README.rst"),
    license="MIT",
    keywords="media",
    url="https://github.com/leinz/imagesort",

    entry_points={
        'console_scripts': [
            'imagesort = imagesort.imagesort:main',
        ]
    },

    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: MacOS :: MacOS X',
        'Topic :: Multimedia',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
    ],
)


"""Convert Exportify csv Spotify playlists to yaml."""
import os
import glob
import pandas
import yaml

csv_files = glob.glob("*.csv")

for playlist_file in csv_files:
    playlist_name, _ = os.path.splitext(playlist_file)
    yaml_file = 'yaml/{}.yaml'.format(playlist_name)
    print("- {}".format(yaml_file))

    playlist = pandas.read_csv(playlist_file)
    playlist_dict = playlist.to_dict('index')

    with open(yaml_file, 'w') as fp:
        fp.write('#\n# {}\n#\n'.format(playlist_name))
        yaml.safe_dump(playlist_dict, fp)

Convert a Spotify playylist from Exportify to yaml

Response:
<INSERT> """Convert Exportify csv Spotify playlists to yaml."""
import os
import glob
import pandas
import yaml

csv_files = glob.glob("*.csv")

for playlist_file in csv_files:
 <INSERT_END> <INSERT>   playlist_name, _ = os.path.splitext(playlist_file)
    yaml_file = 'yaml/{}.yaml'.format(playlist_name)
    print("- {}".format(yaml_file))

    playlist = pandas.read_csv(playlist_file)
    playlist_dict = playlist.to_dict('index')

    with open(yaml_file, 'w') as fp:
        fp.write('#\n# {}\n#\n'.format(playlist_name))
        yaml.safe_dump(playlist_dict, fp)
 <INSERT_END> <|endoftext|> """Convert Exportify csv Spotify playlists to yaml."""
import os
import glob
import pandas
import yaml

csv_files = glob.glob("*.csv")

for playlist_file in csv_files:
    playlist_name, _ = os.path.splitext(playlist_file)
    yaml_file = 'yaml/{}.yaml'.format(playlist_name)
    print("- {}".format(yaml_file))

    playlist = pandas.read_csv(playlist_file)
    playlist_dict = playlist.to_dict('index')

    with open(yaml_file, 'w') as fp:
        fp.write('#\n# {}\n#\n'.format(playlist_name))
        yaml.safe_dump(playlist_dict, fp)

Prompt: Convert a Spotify playylist from Exportify to yaml


from pprint import pprint, pformat
import datetime
import itertools
import os

from sgmock import Fixture
from sgmock import TestCase

_shotgun_server = os.environ.get('SHOTGUN', 'mock')
if _shotgun_server == 'mock':
    from sgmock import Shotgun, ShotgunError, Fault
else:
    from shotgun_api3 import ShotgunError, Fault
    import shotgun_api3_registry
    def Shotgun():
        return shotgun_api3_registry.connect('sgsession.tests', server=_shotgun_server)

from sgsession import Session, Entity

from sgfs import SGFS

def mini_uuid():
    return os.urandom(4).encode('hex')

def timestamp():
    return datetime.datetime.now().strftime('%Y%m%d%H%M%S')

def minimal(entity):
    return dict(type=entity['type'], id=entity['id'])

Response:
<REPLACE_OLD> os
import itertools

from <REPLACE_NEW> itertools
import os

from <REPLACE_END> <REPLACE_OLD> TestCase

if 'USE_SHOTGUN' in os.environ:
 <REPLACE_NEW> TestCase

_shotgun_server = os.environ.get('SHOTGUN', 'mock')
if _shotgun_server == 'mock':
    from sgmock import Shotgun, ShotgunError, Fault
else:
 <REPLACE_END> <REPLACE_OLD> server='testing')
else:
    from sgmock import Shotgun, ShotgunError, Fault

from <REPLACE_NEW> server=_shotgun_server)

from <REPLACE_END> <|endoftext|> from pprint import pprint, pformat
import datetime
import itertools
import os

from sgmock import Fixture
from sgmock import TestCase

_shotgun_server = os.environ.get('SHOTGUN', 'mock')
if _shotgun_server == 'mock':
    from sgmock import Shotgun, ShotgunError, Fault
else:
    from shotgun_api3 import ShotgunError, Fault
    import shotgun_api3_registry
    def Shotgun():
        return shotgun_api3_registry.connect('sgsession.tests', server=_shotgun_server)

from sgsession import Session, Entity

from sgfs import SGFS

def mini_uuid():
    return os.urandom(4).encode('hex')

def timestamp():
    return datetime.datetime.now().strftime('%Y%m%d%H%M%S')

def minimal(entity):
    return dict(type=entity['type'], id=entity['id'])

Prompt:
Change the way we test the real Shotgun server
from pprint import pprint, pformat
import datetime
import os
import itertools

from sgmock import Fixture
from sgmock import TestCase

if 'USE_SHOTGUN' in os.environ:
    from shotgun_api3 import ShotgunError, Fault
    import shotgun_api3_registry
    def Shotgun():
        return shotgun_api3_registry.connect('sgsession.tests', server='testing')
else:
    from sgmock import Shotgun, ShotgunError, Fault

from sgsession import Session, Entity

from sgfs import SGFS

def mini_uuid():
    return os.urandom(4).encode('hex')

def timestamp():
    return datetime.datetime.now().strftime('%Y%m%d%H%M%S')

def minimal(entity):
    return dict(type=entity['type'], id=entity['id'])


from flask_jwt_extended import current_user
from flask_restful import Resource
from marshmallow import fields, Schema

from scuevals_api.auth import auth_required
from scuevals_api.models import Permission, OfficialUserType, db
from scuevals_api.utils import use_args

class OfficialUserTypeSchema(Schema):
    email = fields.Str(required=True)
    type = fields.Str(required=True)

    class Meta:
        strict = True

class OfficialUserTypeResource(Resource):
    @auth_required(Permission.UpdateOfficialUserTypes)
    @use_args({'official_user_types': fields.List(fields.Nested(OfficialUserTypeSchema), required=True)},
              locations=('json',))
    def post(self, args):

        for out in args['official_user_types']:
            db.session.merge(OfficialUserType(
                email=out['email'].lower(),
                type=out['type'],
                university_id=current_user.university_id
            ))

        db.session.commit()
        return {'result': 'success', 'updated_count': len(args['official_user_types'])}, 200

Response:
<REPLACE_OLD> email=out['email'],
 <REPLACE_NEW> email=out['email'].lower(),
 <REPLACE_END> <|endoftext|> from flask_jwt_extended import current_user
from flask_restful import Resource
from marshmallow import fields, Schema

from scuevals_api.auth import auth_required
from scuevals_api.models import Permission, OfficialUserType, db
from scuevals_api.utils import use_args

class OfficialUserTypeSchema(Schema):
    email = fields.Str(required=True)
    type = fields.Str(required=True)

    class Meta:
        strict = True

class OfficialUserTypeResource(Resource):
    @auth_required(Permission.UpdateOfficialUserTypes)
    @use_args({'official_user_types': fields.List(fields.Nested(OfficialUserTypeSchema), required=True)},
              locations=('json',))
    def post(self, args):

        for out in args['official_user_types']:
            db.session.merge(OfficialUserType(
                email=out['email'].lower(),
                type=out['type'],
                university_id=current_user.university_id
            ))

        db.session.commit()
        return {'result': 'success', 'updated_count': len(args['official_user_types'])}, 200

Prompt:
Make sure official user type emails are lower case

from flask_jwt_extended import current_user
from flask_restful import Resource
from marshmallow import fields, Schema

from scuevals_api.auth import auth_required
from scuevals_api.models import Permission, OfficialUserType, db
from scuevals_api.utils import use_args

class OfficialUserTypeSchema(Schema):
    email = fields.Str(required=True)
    type = fields.Str(required=True)

    class Meta:
        strict = True

class OfficialUserTypeResource(Resource):
    @auth_required(Permission.UpdateOfficialUserTypes)
    @use_args({'official_user_types': fields.List(fields.Nested(OfficialUserTypeSchema), required=True)},
              locations=('json',))
    def post(self, args):

        for out in args['official_user_types']:
            db.session.merge(OfficialUserType(
                email=out['email'],
                type=out['type'],
                university_id=current_user.university_id
            ))

        db.session.commit()
        return {'result': 'success', 'updated_count': len(args['official_user_types'])}, 200


class Color(object):
    def __init__(self, *args):
        if len(args) == 4:
            r, g, b, a = args
        else:
            raise NotImplementedError("implement me")
        self.r = r
        self.g = g
        self.b = b
        self.a = a

Make blitting work (the basics anyway)

Make blitting work (the basics anyway)

Response:
<INSERT>
class Color(object):
 <INSERT_END> <INSERT>   def __init__(self, *args):
        if len(args) == 4:
            r, g, b, a = args
        else:
            raise NotImplementedError("implement me")
        self.r = r
        self.g = g
        self.b = b
        self.a = a
 <INSERT_END> <|endoftext|>
class Color(object):
    def __init__(self, *args):
        if len(args) == 4:
            r, g, b, a = args
        else:
            raise NotImplementedError("implement me")
        self.r = r
        self.g = g
        self.b = b
        self.a = a

Prompt: Make blitting work (the basics anyway)


import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *

class GuiTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        TestBase.setUp(self)

    @no_debug_info_test
    def test_reproducer_generate_invalid_invocation(self):
        self.expect("gui blub", error=True,
                    substrs=["the gui command takes no arguments."])

Add test for invalid gui command

[lldb][NFC] Add test for invalid gui command

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@370647 91177308-0d34-0410-b5e6-96231b3b80d8

Response:
<INSERT> import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *

class GuiTestCase(TestBase):

 <INSERT_END> <INSERT>   mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        TestBase.setUp(self)

    @no_debug_info_test
    def test_reproducer_generate_invalid_invocation(self):
        self.expect("gui blub", error=True,
                    substrs=["the gui command takes no arguments."])
 <INSERT_END> <|endoftext|> import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *

class GuiTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        TestBase.setUp(self)

    @no_debug_info_test
    def test_reproducer_generate_invalid_invocation(self):
        self.expect("gui blub", error=True,
                    substrs=["the gui command takes no arguments."])

Prompt:
[lldb][NFC] Add test for invalid gui command

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@370647 91177308-0d34-0410-b5e6-96231b3b80d8


from __future__ import with_statement

from nose.tools import (
    eq_ as eq,
    )

from fs.test.util import (
    maketemp,
    assert_raises,
    )

import errno
import os

import fs

def test_mkdir():
    tmp = maketemp()
    fs.path(tmp).child('foo').mkdir()
    foo = os.path.join(tmp, 'foo')
    assert os.path.isdir(foo)

def test_mkdir_bad_exists():
    tmp = maketemp()
    p = fs.path(tmp).child('foo')
    with p.open('w') as f:
        f.write('bar')
    e = assert_raises(
        OSError,
        p.mkdir,
        )
    eq(e.errno, errno.EEXIST)

Add more tests for mkdir.

Add more tests for mkdir.

Response:
<INSERT> from __future__ import with_statement

from nose.tools import (
 <INSERT_END> <INSERT>   eq_ as eq,
    )

from fs.test.util import (
    maketemp,
    assert_raises,
    )

import errno
import os

import fs

def test_mkdir():
    tmp = maketemp()
    fs.path(tmp).child('foo').mkdir()
    foo = os.path.join(tmp, 'foo')
    assert os.path.isdir(foo)

def test_mkdir_bad_exists():
    tmp = maketemp()
    p = fs.path(tmp).child('foo')
    with p.open('w') as f:
        f.write('bar')
    e = assert_raises(
        OSError,
        p.mkdir,
        )
    eq(e.errno, errno.EEXIST)
 <INSERT_END> <|endoftext|> from __future__ import with_statement

from nose.tools import (
    eq_ as eq,
    )

from fs.test.util import (
    maketemp,
    assert_raises,
    )

import errno
import os

import fs

def test_mkdir():
    tmp = maketemp()
    fs.path(tmp).child('foo').mkdir()
    foo = os.path.join(tmp, 'foo')
    assert os.path.isdir(foo)

def test_mkdir_bad_exists():
    tmp = maketemp()
    p = fs.path(tmp).child('foo')
    with p.open('w') as f:
        f.write('bar')
    e = assert_raises(
        OSError,
        p.mkdir,
        )
    eq(e.errno, errno.EEXIST)

Prompt: Add more tests for mkdir.


from setuptools import setup, find_packages

import populous

requirements = [
    "click",
    "cached-property",
]

setup(
    name="populous",
    version=populous.__version__,
    url=populous.__url__,
    description=populous.__doc__,
    author=populous.__author__,
    license=populous.__license__,
    long_description="TODO",
    packages=find_packages(),
    install_requires=requirements,
    entry_points={
        'console_scripts': [
            'populous = populous.__main__:cli'
        ]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Topic :: Utilities",
    ],
    keywords='populous populate database',
)

Add cached-property to the dependencies

Add cached-property to the dependencies

Response:
<REPLACE_OLD> "click",
]

setup(
 <REPLACE_NEW> "click",
    "cached-property",
]

setup(
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

import populous

requirements = [
    "click",
    "cached-property",
]

setup(
    name="populous",
    version=populous.__version__,
    url=populous.__url__,
    description=populous.__doc__,
    author=populous.__author__,
    license=populous.__license__,
    long_description="TODO",
    packages=find_packages(),
    install_requires=requirements,
    entry_points={
        'console_scripts': [
            'populous = populous.__main__:cli'
        ]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Topic :: Utilities",
    ],
    keywords='populous populate database',
)

Prompt:
Add cached-property to the dependencies

from setuptools import setup, find_packages

import populous

requirements = [
    "click",
]

setup(
    name="populous",
    version=populous.__version__,
    url=populous.__url__,
    description=populous.__doc__,
    author=populous.__author__,
    license=populous.__license__,
    long_description="TODO",
    packages=find_packages(),
    install_requires=requirements,
    entry_points={
        'console_scripts': [
            'populous = populous.__main__:cli'
        ]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Topic :: Utilities",
    ],
    keywords='populous populate database',
)


import os
from setuptools import find_packages
from setuptools import setup
import sys

sys.path.insert(0, os.path.abspath('lib'))

exec(open('lib/ansiblereview/version.py').read())

setup(
    name='ansible-review',
    version=__version__,
    description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
    keywords='ansible, code review',
    author='Will Thames',
    author_email='will@thames.id.au',
    url='https://github.com/willthames/ansible-review',
    package_dir={'': 'lib'},
    packages=find_packages('lib'),
    zip_safe=False,
    install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff', 'flake8'],
    scripts=['bin/ansible-review'],
    classifiers=[
        'License :: OSI Approved :: MIT License',
    ],
    test_suite="test"
)

Add flake8 to installation dependencies

Add flake8 to installation dependencies

Response:
<REPLACE_OLD> 'unidiff'],
 <REPLACE_NEW> 'unidiff', 'flake8'],
 <REPLACE_END> <|endoftext|> import os
from setuptools import find_packages
from setuptools import setup
import sys

sys.path.insert(0, os.path.abspath('lib'))

exec(open('lib/ansiblereview/version.py').read())

setup(
    name='ansible-review',
    version=__version__,
    description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
    keywords='ansible, code review',
    author='Will Thames',
    author_email='will@thames.id.au',
    url='https://github.com/willthames/ansible-review',
    package_dir={'': 'lib'},
    packages=find_packages('lib'),
    zip_safe=False,
    install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff', 'flake8'],
    scripts=['bin/ansible-review'],
    classifiers=[
        'License :: OSI Approved :: MIT License',
    ],
    test_suite="test"
)

Prompt:
Add flake8 to installation dependencies

import os
from setuptools import find_packages
from setuptools import setup
import sys

sys.path.insert(0, os.path.abspath('lib'))

exec(open('lib/ansiblereview/version.py').read())

setup(
    name='ansible-review',
    version=__version__,
    description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
    keywords='ansible, code review',
    author='Will Thames',
    author_email='will@thames.id.au',
    url='https://github.com/willthames/ansible-review',
    package_dir={'': 'lib'},
    packages=find_packages('lib'),
    zip_safe=False,
    install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff'],
    scripts=['bin/ansible-review'],
    classifiers=[
        'License :: OSI Approved :: MIT License',
    ],
    test_suite="test"
)


# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha 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 General Public License
# along with Moksha.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>

class Consumer(object):
    """ A message consumer """
    topic = None

    def consume(self, message):
        raise NotImplementedError

Response:
<REPLACE_OLD> """
Consumers
=========

A `Consumer` <REPLACE_NEW> # This file <REPLACE_END> <REPLACE_OLD> a simple consumer <REPLACE_NEW> part <REPLACE_END> <REPLACE_OLD> messages.  Based on a given `routing_key`,
your consumer's :meth:`consume` method <REPLACE_NEW> Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it <REPLACE_END> <REPLACE_OLD> called <REPLACE_NEW> 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 General Public License
# along <REPLACE_END> <REPLACE_OLD> the message.

Example consumers:

 <REPLACE_NEW> Moksha. <REPLACE_END> <REPLACE_OLD>   -tapping into a koji build, and sending a notification?
    - hook into a given RSS feed and save data in a DB?

Adding a new consumer
---------------------

Adding a new Consumer to Moksha is as easy as adding it to the `[moksha.consumer]`
entry-point in your `setup.py` file::

    [moksha.consumer]
    myconsumer = myproject.module:MyConsumer

"""

class <REPLACE_NEW> If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>

class <REPLACE_END> <REPLACE_OLD> queue <REPLACE_NEW> """ A message consumer """
    topic <REPLACE_END> <REPLACE_OLD> None
 <REPLACE_NEW> None

 <REPLACE_END> <|endoftext|> # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha 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 General Public License
# along with Moksha.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>

class Consumer(object):
    """ A message consumer """
    topic = None

    def consume(self, message):
        raise NotImplementedError

Prompt:
Update our message Consumer api to consume a `topic`, not a `queue`.

"""
Consumers
=========

A `Consumer` is a simple consumer of messages.  Based on a given `routing_key`,
your consumer's :meth:`consume` method will be called with the message.

Example consumers:

    -tapping into a koji build, and sending a notification?
    - hook into a given RSS feed and save data in a DB?

Adding a new consumer
---------------------

Adding a new Consumer to Moksha is as easy as adding it to the `[moksha.consumer]`
entry-point in your `setup.py` file::

    [moksha.consumer]
    myconsumer = myproject.module:MyConsumer

"""

class Consumer(object):
    queue = None
    def consume(self, message):
        raise NotImplementedError