import sys
import argparse

from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError

def analyze(code, writer=sys.stdout):
    try:
        result = parse(code)
    except SQFParserError as e:
        writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
        return

    exceptions = sqf.analyser.analyze(result).exceptions
    for e in exceptions:
        writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))

def _main():
    parser = argparse.ArgumentParser(description="Static Analyser of SQF code")
    parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=None,
                        help='The full path of the file to be analyzed')

    args = parser.parse_args()

    if args.file is not None:
        code = args.file.read()
    else:
        code = sys.stdin.read()

    analyze(code)

if __name__ == "__main__":
    _main()

Response:
<REPLACE_OLD> parser.add_argument('filename', <REPLACE_NEW> parser.add_argument('file', <REPLACE_END> <REPLACE_OLD> args.filename <REPLACE_NEW> args.file <REPLACE_END> <DELETE> with open(args.filename) as file:
            <DELETE_END> <REPLACE_OLD> file.read()
 <REPLACE_NEW> args.file.read()
 <REPLACE_END> <|endoftext|> import sys
import argparse

from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError

def analyze(code, writer=sys.stdout):
    try:
        result = parse(code)
    except SQFParserError as e:
        writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
        return

    exceptions = sqf.analyser.analyze(result).exceptions
    for e in exceptions:
        writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))

def _main():
    parser = argparse.ArgumentParser(description="Static Analyser of SQF code")
    parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=None,
                        help='The full path of the file to be analyzed')

    args = parser.parse_args()

    if args.file is not None:
        code = args.file.read()
    else:
        code = sys.stdin.read()

    analyze(code)

if __name__ == "__main__":
    _main()

Prompt:
Fix parsing file - FileType already read

import sys
import argparse

from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError

def analyze(code, writer=sys.stdout):
    try:
        result = parse(code)
    except SQFParserError as e:
        writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
        return

    exceptions = sqf.analyser.analyze(result).exceptions
    for e in exceptions:
        writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))

def _main():
    parser = argparse.ArgumentParser(description="Static Analyser of SQF code")
    parser.add_argument('filename', nargs='?', type=argparse.FileType('r'), default=None,
                        help='The full path of the file to be analyzed')

    args = parser.parse_args()

    if args.filename is not None:
        with open(args.filename) as file:
            code = file.read()
    else:
        code = sys.stdin.read()

    analyze(code)

if __name__ == "__main__":
    _main()


from .parser import HTMLTableParser

__author__ = 'Josua Schmid'
__version__ = '0.1.1'
__licence__ = 'AGPLv3'

Response:
<REPLACE_OLD> 'GPLv3'
 <REPLACE_NEW> 'AGPLv3'
 <REPLACE_END> <|endoftext|> from .parser import HTMLTableParser

__author__ = 'Josua Schmid'
__version__ = '0.1.1'
__licence__ = 'AGPLv3'

Prompt:
Correct license in module meta information

from .parser import HTMLTableParser

__author__ = 'Josua Schmid'
__version__ = '0.1.1'
__licence__ = 'GPLv3'


from chaco.tools.api import ScatterInspector
from numpy import zeros

class PeakSelectionTool(ScatterInspector):
    def _deselect(self, index=None):
        super(PeakSelectionTool, self)._deselect(index)
        self._update_mask()

    # override this method so that we only select one peak at a time
    def _select(self, index, append=False):
        super(PeakSelectionTool, self)._select(index, append)
        self._update_mask()

    def _update_mask(self):
        plot = self.component
        for name in ('index', 'value'):
            if not hasattr(plot, name):
                continue
            md = getattr(plot, name).metadata
            mask = zeros(getattr(plot, name).get_data().shape[0],
                         dtype=bool)
            mask[list(md[self.selection_metadata_name])]=True
            md['selection_masks'] = mask

Add missing custom tools file

Add missing custom tools file

Response:
<REPLACE_OLD>  <REPLACE_NEW> from chaco.tools.api import ScatterInspector
from numpy import zeros

class PeakSelectionTool(ScatterInspector):
    def _deselect(self, index=None):
        super(PeakSelectionTool, self)._deselect(index)
        self._update_mask()

    # override this method so that we only select one peak at a time
    def _select(self, index, append=False):
        super(PeakSelectionTool, self)._select(index, append)
        self._update_mask()

    def _update_mask(self):
        plot = self.component
        for name in ('index', 'value'):
            if not hasattr(plot, name):
                continue
            md = getattr(plot, name).metadata
            mask = zeros(getattr(plot, name).get_data().shape[0],
                         dtype=bool)
            mask[list(md[self.selection_metadata_name])]=True
            md['selection_masks'] = mask <REPLACE_END> <|endoftext|> from chaco.tools.api import ScatterInspector
from numpy import zeros

class PeakSelectionTool(ScatterInspector):
    def _deselect(self, index=None):
        super(PeakSelectionTool, self)._deselect(index)
        self._update_mask()

    # override this method so that we only select one peak at a time
    def _select(self, index, append=False):
        super(PeakSelectionTool, self)._select(index, append)
        self._update_mask()

    def _update_mask(self):
        plot = self.component
        for name in ('index', 'value'):
            if not hasattr(plot, name):
                continue
            md = getattr(plot, name).metadata
            mask = zeros(getattr(plot, name).get_data().shape[0],
                         dtype=bool)
            mask[list(md[self.selection_metadata_name])]=True
            md['selection_masks'] = mask

Prompt: Add missing custom tools file


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert a rosbag file to legacy lidar binary format.
"""

"""LIDAR datatype format is:
    (
        timestamp (long),
        flag (bool saved as int),
        accelerometer[3] (double),
        gps[3] (double),
        distance[LIDAR_NUM_ANGLES] (long),
    )

    'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag

def print_bag(bag):
    topics = ['/scan', '/flagbutton_pressed']
    for message in bag.read_messages(topics=topics):
        print(message)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(('Usage: {} <rosbag> [<outfile>] \n\n'
               'Print contents of rosbag file. If <outfile> is provided, \n'
               'write contents of rosbag file to <outfile> in the legacy \n'
               'lidar binary format.').format(__file__))
        sys.exit(1)

    outfile = None
    filename = sys.argv[1]

    if len(sys.argv) == 3:
        outfile = sys.argv[2]

    with rosbag.Bag(filename) as bag:
        print_bag(bag)

    sys.exit()

Response:
<REPLACE_OLD> decode_bag(bag):
 <REPLACE_NEW> print_bag(bag):
 <REPLACE_END> <DELETE> return [message <DELETE_END> <REPLACE_OLD> bag.read_messages(topics=topics)]

if <REPLACE_NEW> bag.read_messages(topics=topics):
        print(message)

if <REPLACE_END> <REPLACE_OLD> print(decode_bag(bag))

 <REPLACE_NEW> print_bag(bag)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert a rosbag file to legacy lidar binary format.
"""

"""LIDAR datatype format is:
    (
        timestamp (long),
        flag (bool saved as int),
        accelerometer[3] (double),
        gps[3] (double),
        distance[LIDAR_NUM_ANGLES] (long),
    )

    'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag

def print_bag(bag):
    topics = ['/scan', '/flagbutton_pressed']
    for message in bag.read_messages(topics=topics):
        print(message)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(('Usage: {} <rosbag> [<outfile>] \n\n'
               'Print contents of rosbag file. If <outfile> is provided, \n'
               'write contents of rosbag file to <outfile> in the legacy \n'
               'lidar binary format.').format(__file__))
        sys.exit(1)

    outfile = None
    filename = sys.argv[1]

    if len(sys.argv) == 3:
        outfile = sys.argv[2]

    with rosbag.Bag(filename) as bag:
        print_bag(bag)

    sys.exit()

Prompt:
Print out bag contents for lidar and button topics

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert a rosbag file to legacy lidar binary format.
"""

"""LIDAR datatype format is:
    (
        timestamp (long),
        flag (bool saved as int),
        accelerometer[3] (double),
        gps[3] (double),
        distance[LIDAR_NUM_ANGLES] (long),
    )

    'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag

def decode_bag(bag):
    topics = ['/scan', '/flagbutton_pressed']
    return [message for message in bag.read_messages(topics=topics)]

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(('Usage: {} <rosbag> [<outfile>] \n\n'
               'Print contents of rosbag file. If <outfile> is provided, \n'
               'write contents of rosbag file to <outfile> in the legacy \n'
               'lidar binary format.').format(__file__))
        sys.exit(1)

    outfile = None
    filename = sys.argv[1]

    if len(sys.argv) == 3:
        outfile = sys.argv[2]

    with rosbag.Bag(filename) as bag:
        print(decode_bag(bag))

    sys.exit()


from django.shortcuts import render
from django.views.generic.edit import FormView

from . import forms

# Create your views here.
def logout(request):
    return render(request, 'passwordless/logout.html')

def authn(request, token):
    return render(request, 'passwordless/authn.html')

class LoginView(FormView):
    template_name = 'passwordless/login.html'
    form_class = forms.LoginForm
    success_url = '/'

    def form_valid(self, form):
        form.send_email()

        return super().form_valid(form)

class RegisterView(LoginView):
    template_name = 'passwordless/register.html'
    form_class = forms.RegistrationForm

    def form_valid(self, form):
        form.create_user()

        return super().form_valid(form)

Response:
<REPLACE_OLD> RegisterView(FormView):
 <REPLACE_NEW> RegisterView(LoginView):
 <REPLACE_END> <REPLACE_OLD> forms.RegistrationForm
    success_url = '/'

 <REPLACE_NEW> forms.RegistrationForm

 <REPLACE_END> <REPLACE_OLD> form.create_user()
        form.send_email()

 <REPLACE_NEW> form.create_user()

 <REPLACE_END> <|endoftext|> from django.shortcuts import render
from django.views.generic.edit import FormView

from . import forms

# Create your views here.
def logout(request):
    return render(request, 'passwordless/logout.html')

def authn(request, token):
    return render(request, 'passwordless/authn.html')

class LoginView(FormView):
    template_name = 'passwordless/login.html'
    form_class = forms.LoginForm
    success_url = '/'

    def form_valid(self, form):
        form.send_email()

        return super().form_valid(form)

class RegisterView(LoginView):
    template_name = 'passwordless/register.html'
    form_class = forms.RegistrationForm

    def form_valid(self, form):
        form.create_user()

        return super().form_valid(form)

Prompt:
Refactor RegisterView as subclass of LoginView

They share much of the work, they should share the code as well

from django.shortcuts import render
from django.views.generic.edit import FormView

from . import forms

# Create your views here.
def logout(request):
    return render(request, 'passwordless/logout.html')

def authn(request, token):
    return render(request, 'passwordless/authn.html')

class LoginView(FormView):
    template_name = 'passwordless/login.html'
    form_class = forms.LoginForm
    success_url = '/'

    def form_valid(self, form):
        form.send_email()

        return super().form_valid(form)

class RegisterView(FormView):
    template_name = 'passwordless/register.html'
    form_class = forms.RegistrationForm
    success_url = '/'

    def form_valid(self, form):
        form.create_user()
        form.send_email()

        return super().form_valid(form)


# Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.

# The app name will be used in several places.
APP_NAME = 'Yelp Love'

APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'

LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>'

# Flask's secret key, used to encrypt the session cookie.
# Set this to any random string and make sure not to share this!
SECRET_KEY = 'YOUR_SECRET_HERE'

# Use default theme
THEME = 'default'

# Every employee needs a reference to a Google Account. This reference is based on the users
# Google Account email address and created when employee data is imported: we take the *username*
# and this DOMAIN
DOMAIN = 'example.com'

# Name of the S3 bucket used to import employee data from a file named employees.json
# Check out /import/employees.json.example to see how this file should look like.
S3_BUCKET = 'employees'

Response:
<REPLACE_OLD> <love@PROJECT_ID.appspot.com>'

# <REPLACE_NEW> <love@PROJECT_ID.appspotmail.com>'

# <REPLACE_END> <|endoftext|> # Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.

# The app name will be used in several places.
APP_NAME = 'Yelp Love'

APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'

LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>'

# Flask's secret key, used to encrypt the session cookie.
# Set this to any random string and make sure not to share this!
SECRET_KEY = 'YOUR_SECRET_HERE'

# Use default theme
THEME = 'default'

# Every employee needs a reference to a Google Account. This reference is based on the users
# Google Account email address and created when employee data is imported: we take the *username*
# and this DOMAIN
DOMAIN = 'example.com'

# Name of the S3 bucket used to import employee data from a file named employees.json
# Check out /import/employees.json.example to see how this file should look like.
S3_BUCKET = 'employees'

Prompt:
Use appspotmail.com instead of appspot.com for email sender

# Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.

# The app name will be used in several places.
APP_NAME = 'Yelp Love'

APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'

LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspot.com>'

# Flask's secret key, used to encrypt the session cookie.
# Set this to any random string and make sure not to share this!
SECRET_KEY = 'YOUR_SECRET_HERE'

# Use default theme
THEME = 'default'

# Every employee needs a reference to a Google Account. This reference is based on the users
# Google Account email address and created when employee data is imported: we take the *username*
# and this DOMAIN
DOMAIN = 'example.com'

# Name of the S3 bucket used to import employee data from a file named employees.json
# Check out /import/employees.json.example to see how this file should look like.
S3_BUCKET = 'employees'


#! /usr/bin/env python

# Last Change: Sun Sep 14 03:00 PM 2008 J

import numpy as np

from c_lpc import levinson as c_levinson

def levinson(r, order, axis = -1):
    """Levinson-Durbin recursion, to efficiently solve symmetric linear systems
    with toeplitz structure.

    Arguments
    ---------
        r : array-like
            input array to invert (since the matrix is symmetric Toeplitz, the
            corresponding pxp matrix is defined by p items only). Generally the
            autocorrelation of the signal for linear prediction coefficients
            estimation. The first item must be a non zero real, and corresponds
            to the autocorelation at lag 0 for linear prediction.
        order : int
            order of the recursion. For order p, you will get p+1 coefficients.
        axis : int, optional
            axis over which the algorithm is applied. -1 by default.

    Returns
    --------
        a : array-like
            the solution of the inversion (see notes).
        e : array-like
            the prediction error.
        k : array-like
            reflection coefficients.

    Notes
    -----
    Levinson is a well-known algorithm to solve the Hermitian toeplitz
    equation:

                       _          _
        -R[1] = R[0]   R[1]   ... R[p-1]    a[1]
         :      :      :          :      *  :
         :      :      :          _      *  :
        -R[p] = R[p-1] R[p-2] ... R[0]      a[p]
                       _
    with respect to a (  is the complex conjugate). Using the special symmetry
    in the matrix, the inversion can be done in O(p^2) instead of O(p^3).

    """
    if axis != -1:
        r = np.swapaxes(r, -1)
    a, e, k = c_levinson(r, order)
    if axis != -1:
        a = np.swapaxes(a, -1)
        e = np.swapaxes(e, -1)
        k = np.swapaxes(k, -1)
    return a, e, k

Add python interface around C implementation of levinson.

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

# Last Change: Sun Sep 14 03:00 PM 2008 J

import numpy as np

from c_lpc import levinson as c_levinson

def levinson(r, order, axis = -1):
    """Levinson-Durbin recursion, to efficiently solve symmetric linear systems
    with toeplitz structure.

    Arguments
    ---------
        r : array-like
            input array to invert (since the matrix is symmetric Toeplitz, the
            corresponding pxp matrix is defined by p items only). Generally the
            autocorrelation of the signal for linear prediction coefficients
            estimation. The first item must be a non zero real, and corresponds
            to the autocorelation at lag 0 for linear prediction.
        order : int
            order of the recursion. For order p, you will get p+1 coefficients.
        axis : int, optional
            axis over which the algorithm is applied. -1 by default.

    Returns
    --------
        a : array-like
            the solution of the inversion (see notes).
        e : array-like
            the prediction error.
        k : array-like
            reflection coefficients.

    Notes
    -----
    Levinson is a well-known algorithm to solve the Hermitian toeplitz
    equation:

                       _          _
        -R[1] = R[0]   R[1]   ... R[p-1]    a[1]
         :      :      :          :      *  :
         :      :      :          _      *  :
        -R[p] = R[p-1] R[p-2] ... R[0]      a[p]
                       _
    with respect to a (  is the complex conjugate). Using the special symmetry
    in the matrix, the inversion can be done in O(p^2) instead of O(p^3).

    """
    if axis != -1:
        r = np.swapaxes(r, -1)
    a, e, k = c_levinson(r, order)
    if axis != -1:
        a = np.swapaxes(a, -1)
        e = np.swapaxes(e, -1)
        k = np.swapaxes(k, -1)
    return a, e, k
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python

# Last Change: Sun Sep 14 03:00 PM 2008 J

import numpy as np

from c_lpc import levinson as c_levinson

def levinson(r, order, axis = -1):
    """Levinson-Durbin recursion, to efficiently solve symmetric linear systems
    with toeplitz structure.

    Arguments
    ---------
        r : array-like
            input array to invert (since the matrix is symmetric Toeplitz, the
            corresponding pxp matrix is defined by p items only). Generally the
            autocorrelation of the signal for linear prediction coefficients
            estimation. The first item must be a non zero real, and corresponds
            to the autocorelation at lag 0 for linear prediction.
        order : int
            order of the recursion. For order p, you will get p+1 coefficients.
        axis : int, optional
            axis over which the algorithm is applied. -1 by default.

    Returns
    --------
        a : array-like
            the solution of the inversion (see notes).
        e : array-like
            the prediction error.
        k : array-like
            reflection coefficients.

    Notes
    -----
    Levinson is a well-known algorithm to solve the Hermitian toeplitz
    equation:

                       _          _
        -R[1] = R[0]   R[1]   ... R[p-1]    a[1]
         :      :      :          :      *  :
         :      :      :          _      *  :
        -R[p] = R[p-1] R[p-2] ... R[0]      a[p]
                       _
    with respect to a (  is the complex conjugate). Using the special symmetry
    in the matrix, the inversion can be done in O(p^2) instead of O(p^3).

    """
    if axis != -1:
        r = np.swapaxes(r, -1)
    a, e, k = c_levinson(r, order)
    if axis != -1:
        a = np.swapaxes(a, -1)
        e = np.swapaxes(e, -1)
        k = np.swapaxes(k, -1)
    return a, e, k

Prompt: Add python interface around C implementation of levinson.


#!/usr/bin/env python
# encoding: utf-8
"""
HARPS-e2ds-to-order.py

Created by Jonathan Whitmore on 2011-10-14.
Copyright (c) 2011. All rights reserved.
"""

import sys
import os
import argparse
import pyfits as pf
import numpy as np

help_message = '''
Takes reduced HARPS***e2ds_A.fits data and reads the header to output a fits file that has the wavelength per pixel per order.
'''

class Usage(Exception):
  def __init__(self, msg):
    self.msg = msg

def main(argv=None):
  parser = argparse.ArgumentParser(description='Process input file.')
  parser.add_argument('f', type=str, help='input a filename')
  args = parser.parse_args()
  inputfile = vars(args)['f']
  outputFITSfile = str('order_' + inputfile)
  hdu = pf.open(inputfile)
  print len(hdu[0].data)
  polynomialOrder = hdu[0].header['HIERARCH ESO DRS CAL TH DEG LL']
  orders = hdu[0].header['HIERARCH ESO DRS CAL LOC NBO']
  coefficients = (polynomialOrder + 1) * orders # number of coefficients in the file
  whatever = []
  for x in xrange(coefficients):
    whatever.append(hdu[0].header['HIERARCH ESO DRS CAL TH COEFF LL' + str(x)])
  A = {}
  for y in xrange(0,len(whatever),polynomialOrder+1):
    A[y/(polynomialOrder+1)] = whatever[y:y+polynomialOrder+1]
  for order in range(orders):
    print "order: ", order
    wavelength = []
    for pixel in xrange(len(hdu[0].data[order])):
      temp = 0.0
      for x in range(polynomialOrder):
        temp += A[order][x] * pixel ** x
      wavelength.append(temp)
    pf.append(outputFITSfile, np.array([np.array(wavelength), hdu[0].data[order], np.sqrt(np.abs(hdu[0].data[order]))]))

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

Order by order of HARPS data

Order by order of HARPS data

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# encoding: utf-8
"""
HARPS-e2ds-to-order.py

Created by Jonathan Whitmore on 2011-10-14.
Copyright (c) 2011. All rights reserved.
"""

import sys
import os
import argparse
import pyfits as pf
import numpy as np

help_message = '''
Takes reduced HARPS***e2ds_A.fits data and reads the header to output a fits file that has the wavelength per pixel per order.
'''

class Usage(Exception):
  def __init__(self, msg):
    self.msg = msg

def main(argv=None):
  parser = argparse.ArgumentParser(description='Process input file.')
  parser.add_argument('f', type=str, help='input a filename')
  args = parser.parse_args()
  inputfile = vars(args)['f']
  outputFITSfile = str('order_' + inputfile)
  hdu = pf.open(inputfile)
  print len(hdu[0].data)
  polynomialOrder = hdu[0].header['HIERARCH ESO DRS CAL TH DEG LL']
  orders = hdu[0].header['HIERARCH ESO DRS CAL LOC NBO']
  coefficients = (polynomialOrder + 1) * orders # number of coefficients in the file
  whatever = []
  for x in xrange(coefficients):
    whatever.append(hdu[0].header['HIERARCH ESO DRS CAL TH COEFF LL' + str(x)])
  A = {}
  for y in xrange(0,len(whatever),polynomialOrder+1):
    A[y/(polynomialOrder+1)] = whatever[y:y+polynomialOrder+1]
  for order in range(orders):
    print "order: ", order
    wavelength = []
    for pixel in xrange(len(hdu[0].data[order])):
      temp = 0.0
      for x in range(polynomialOrder):
        temp += A[order][x] * pixel ** x
      wavelength.append(temp)
    pf.append(outputFITSfile, np.array([np.array(wavelength), hdu[0].data[order], np.sqrt(np.abs(hdu[0].data[order]))]))

if __name__ == "__main__":
  sys.exit(main())
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# encoding: utf-8
"""
HARPS-e2ds-to-order.py

Created by Jonathan Whitmore on 2011-10-14.
Copyright (c) 2011. All rights reserved.
"""

import sys
import os
import argparse
import pyfits as pf
import numpy as np

help_message = '''
Takes reduced HARPS***e2ds_A.fits data and reads the header to output a fits file that has the wavelength per pixel per order.
'''

class Usage(Exception):
  def __init__(self, msg):
    self.msg = msg

def main(argv=None):
  parser = argparse.ArgumentParser(description='Process input file.')
  parser.add_argument('f', type=str, help='input a filename')
  args = parser.parse_args()
  inputfile = vars(args)['f']
  outputFITSfile = str('order_' + inputfile)
  hdu = pf.open(inputfile)
  print len(hdu[0].data)
  polynomialOrder = hdu[0].header['HIERARCH ESO DRS CAL TH DEG LL']
  orders = hdu[0].header['HIERARCH ESO DRS CAL LOC NBO']
  coefficients = (polynomialOrder + 1) * orders # number of coefficients in the file
  whatever = []
  for x in xrange(coefficients):
    whatever.append(hdu[0].header['HIERARCH ESO DRS CAL TH COEFF LL' + str(x)])
  A = {}
  for y in xrange(0,len(whatever),polynomialOrder+1):
    A[y/(polynomialOrder+1)] = whatever[y:y+polynomialOrder+1]
  for order in range(orders):
    print "order: ", order
    wavelength = []
    for pixel in xrange(len(hdu[0].data[order])):
      temp = 0.0
      for x in range(polynomialOrder):
        temp += A[order][x] * pixel ** x
      wavelength.append(temp)
    pf.append(outputFITSfile, np.array([np.array(wavelength), hdu[0].data[order], np.sqrt(np.abs(hdu[0].data[order]))]))

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

Prompt: Order by order of HARPS data


from setuptools import setup, find_packages

setup(
    name='ckanext-archiver',
    version='0.1',
    packages=find_packages(),
    install_requires=[
        'celery==2.4.2',
        'kombu==2.1.3',
        'kombu-sqlalchemy==1.1.0',
        'SQLAlchemy>=0.6.6',
        'requests==0.6.4',
        'messytables>=0.1.4',
        'flask==0.8'  # flask needed for tests
    ],
    author='Open Knowledge Foundation',
    author_email='info@okfn.org',
    description='Archive ckan resources',
    long_description='Archive ckan resources',
    license='MIT',
    url='http://ckan.org/wiki/Extensions',
    download_url='',
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
    entry_points='''
    [paste.paster_command]
    archiver = ckanext.archiver.commands:Archiver

    [ckan.plugins]
    archiver = ckanext.archiver.plugin:ArchiverPlugin

    [ckan.celery_task]
    tasks = ckanext.archiver.celery_import:task_imports
    '''
)

Response:
<REPLACE_OLD> 'celery==2.4.5',
        'kombu==1.5.1',
 <REPLACE_NEW> 'celery==2.4.2',
        'kombu==2.1.3',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='ckanext-archiver',
    version='0.1',
    packages=find_packages(),
    install_requires=[
        'celery==2.4.2',
        'kombu==2.1.3',
        'kombu-sqlalchemy==1.1.0',
        'SQLAlchemy>=0.6.6',
        'requests==0.6.4',
        'messytables>=0.1.4',
        'flask==0.8'  # flask needed for tests
    ],
    author='Open Knowledge Foundation',
    author_email='info@okfn.org',
    description='Archive ckan resources',
    long_description='Archive ckan resources',
    license='MIT',
    url='http://ckan.org/wiki/Extensions',
    download_url='',
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
    entry_points='''
    [paste.paster_command]
    archiver = ckanext.archiver.commands:Archiver

    [ckan.plugins]
    archiver = ckanext.archiver.plugin:ArchiverPlugin

    [ckan.celery_task]
    tasks = ckanext.archiver.celery_import:task_imports
    '''
)

Prompt:
Change celery and kombu requirements to match ckanext-datastorer

from setuptools import setup, find_packages

setup(
    name='ckanext-archiver',
    version='0.1',
    packages=find_packages(),
    install_requires=[
        'celery==2.4.5',
        'kombu==1.5.1',
        'kombu-sqlalchemy==1.1.0',
        'SQLAlchemy>=0.6.6',
        'requests==0.6.4',
        'messytables>=0.1.4',
        'flask==0.8'  # flask needed for tests
    ],
    author='Open Knowledge Foundation',
    author_email='info@okfn.org',
    description='Archive ckan resources',
    long_description='Archive ckan resources',
    license='MIT',
    url='http://ckan.org/wiki/Extensions',
    download_url='',
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
    entry_points='''
    [paste.paster_command]
    archiver = ckanext.archiver.commands:Archiver

    [ckan.plugins]
    archiver = ckanext.archiver.plugin:ArchiverPlugin

    [ckan.celery_task]
    tasks = ckanext.archiver.celery_import:task_imports
    '''
)


# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function

import unittest
import sys

from oscrypto import trust_list
from asn1crypto.x509 import Certificate

if sys.version_info < (3,):
    byte_cls = str
else:
    byte_cls = bytes

class TrustListTests(unittest.TestCase):

    def test_extract_from_system(self):
        certs = trust_list.extract_from_system()
        self.assertIsInstance(certs, list)
        self.assertLess(10, len(certs))
        for cert in certs:
            self.assertIsInstance(cert, byte_cls)
            _ = Certificate.load(cert).native

Response:
<INSERT> self.assertLess(10, len(certs))
        <INSERT_END> <|endoftext|> # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function

import unittest
import sys

from oscrypto import trust_list
from asn1crypto.x509 import Certificate

if sys.version_info < (3,):
    byte_cls = str
else:
    byte_cls = bytes

class TrustListTests(unittest.TestCase):

    def test_extract_from_system(self):
        certs = trust_list.extract_from_system()
        self.assertIsInstance(certs, list)
        self.assertLess(10, len(certs))
        for cert in certs:
            self.assertIsInstance(cert, byte_cls)
            _ = Certificate.load(cert).native

Prompt:
Add more sanity checks to the trust list test

# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function

import unittest
import sys

from oscrypto import trust_list
from asn1crypto.x509 import Certificate

if sys.version_info < (3,):
    byte_cls = str
else:
    byte_cls = bytes

class TrustListTests(unittest.TestCase):

    def test_extract_from_system(self):
        certs = trust_list.extract_from_system()
        self.assertIsInstance(certs, list)
        for cert in certs:
            self.assertIsInstance(cert, byte_cls)
            _ = Certificate.load(cert).native


#!/usr/bin/env python
from distutils.core import setup

setup(
    name='django-payfast',
    version='0.2.2',
    author='Mikhail Korobov',
    author_email='kmike84@gmail.com',

    packages=['payfast', 'payfast.south_migrations'],

    url='http://bitbucket.org/kmike/django-payfast/',
    download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
    license = 'MIT license',
    description = 'A pluggable Django application for integrating payfast.co.za payment system.',
    long_description = open('README.rst').read().decode('utf8'),

    classifiers=(
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ),
)

Response:
<REPLACE_OLD> Python',
 <REPLACE_NEW> Python :: 2.7',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from distutils.core import setup

setup(
    name='django-payfast',
    version='0.2.2',
    author='Mikhail Korobov',
    author_email='kmike84@gmail.com',

    packages=['payfast', 'payfast.south_migrations'],

    url='http://bitbucket.org/kmike/django-payfast/',
    download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
    license = 'MIT license',
    description = 'A pluggable Django application for integrating payfast.co.za payment system.',
    long_description = open('README.rst').read().decode('utf8'),

    classifiers=(
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ),
)

Prompt:
Package classifiers: Explicitly target Python 2.7

#!/usr/bin/env python
from distutils.core import setup

setup(
    name='django-payfast',
    version='0.2.2',
    author='Mikhail Korobov',
    author_email='kmike84@gmail.com',

    packages=['payfast', 'payfast.south_migrations'],

    url='http://bitbucket.org/kmike/django-payfast/',
    download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
    license = 'MIT license',
    description = 'A pluggable Django application for integrating payfast.co.za payment system.',
    long_description = open('README.rst').read().decode('utf8'),

    classifiers=(
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ),
)


# encoding: utf-8
from comics.aggregator.crawler import ComicsKingdomCrawlerBase
from comics.core.comic_data import ComicDataBase

class ComicData(ComicDataBase):
    name = 'Hägar the Horrible'
    language = 'en'
    url = 'https://www.comicskingdom.com/hagar-the-horrible'
    rights = 'Chris Browne'

class Crawler(ComicsKingdomCrawlerBase):
    history_capable_days = 6
    schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
    time_zone = 'US/Eastern'

    def crawl(self, pub_date):
        return self.crawl_helper('hagar-the-horrible', pub_date)

Add crawler for "Hägar the Horrible"

Add crawler for "Hägar the Horrible"

Response:
<INSERT> # encoding: utf-8
from comics.aggregator.crawler import ComicsKingdomCrawlerBase
from comics.core.comic_data import ComicDataBase

class ComicData(ComicDataBase):
 <INSERT_END> <INSERT>   name = 'Hägar the Horrible'
    language = 'en'
    url = 'https://www.comicskingdom.com/hagar-the-horrible'
    rights = 'Chris Browne'

class Crawler(ComicsKingdomCrawlerBase):
    history_capable_days = 6
    schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
    time_zone = 'US/Eastern'

    def crawl(self, pub_date):
        return self.crawl_helper('hagar-the-horrible', pub_date)
 <INSERT_END> <|endoftext|> # encoding: utf-8
from comics.aggregator.crawler import ComicsKingdomCrawlerBase
from comics.core.comic_data import ComicDataBase

class ComicData(ComicDataBase):
    name = 'Hägar the Horrible'
    language = 'en'
    url = 'https://www.comicskingdom.com/hagar-the-horrible'
    rights = 'Chris Browne'

class Crawler(ComicsKingdomCrawlerBase):
    history_capable_days = 6
    schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
    time_zone = 'US/Eastern'

    def crawl(self, pub_date):
        return self.crawl_helper('hagar-the-horrible', pub_date)

Prompt: Add crawler for "Hägar the Horrible"


from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required

from django_auto_filter.views_django_auto_filter_new import DjangoAutoFilterNew
from djangoautoconf.model_utils.model_attr_utils import model_enumerator
from ufs_tools.string_tools import class_name_to_low_case

def add_filter_to_url_for(urlpatterns, models):
    for model in model_enumerator(models):
        urlpatterns += patterns('', url(r'^models/%s/' % class_name_to_low_case(model.__name__),
                                        DjangoAutoFilterNew.as_view(model=model)))

def get_filter_urls(models, template_name=None):
    url_list = []
    for model in model_enumerator(models):
        param_dict = {"model": model}
        if template_name is not None:
            param_dict["template_name"] = template_name
        url_list.append(url(r'^model/%s/' % class_name_to_low_case(model.__name__),
                            login_required(DjangoAutoFilterNew.as_view(**param_dict))))

    p = patterns('', *url_list)
    return p

Response:
<REPLACE_OLD> DjangoAutoFilterNew.as_view(model_class=model)))

def <REPLACE_NEW> DjangoAutoFilterNew.as_view(model=model)))

def <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required

from django_auto_filter.views_django_auto_filter_new import DjangoAutoFilterNew
from djangoautoconf.model_utils.model_attr_utils import model_enumerator
from ufs_tools.string_tools import class_name_to_low_case

def add_filter_to_url_for(urlpatterns, models):
    for model in model_enumerator(models):
        urlpatterns += patterns('', url(r'^models/%s/' % class_name_to_low_case(model.__name__),
                                        DjangoAutoFilterNew.as_view(model=model)))

def get_filter_urls(models, template_name=None):
    url_list = []
    for model in model_enumerator(models):
        param_dict = {"model": model}
        if template_name is not None:
            param_dict["template_name"] = template_name
        url_list.append(url(r'^model/%s/' % class_name_to_low_case(model.__name__),
                            login_required(DjangoAutoFilterNew.as_view(**param_dict))))

    p = patterns('', *url_list)
    return p

Prompt:
Fix attribute from model_class to model issue.

from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required

from django_auto_filter.views_django_auto_filter_new import DjangoAutoFilterNew
from djangoautoconf.model_utils.model_attr_utils import model_enumerator
from ufs_tools.string_tools import class_name_to_low_case

def add_filter_to_url_for(urlpatterns, models):
    for model in model_enumerator(models):
        urlpatterns += patterns('', url(r'^models/%s/' % class_name_to_low_case(model.__name__),
                                        DjangoAutoFilterNew.as_view(model_class=model)))

def get_filter_urls(models, template_name=None):
    url_list = []
    for model in model_enumerator(models):
        param_dict = {"model": model}
        if template_name is not None:
            param_dict["template_name"] = template_name
        url_list.append(url(r'^model/%s/' % class_name_to_low_case(model.__name__),
                            login_required(DjangoAutoFilterNew.as_view(**param_dict))))

    p = patterns('', *url_list)
    return p


import base64
import datetime
import os
import pickle

from lxml import etree
import redis

from django.core.management.base import BaseCommand
from django.conf import settings

from humfrey.update.longliving.updater import Updater

class Command(BaseCommand):
    def handle(self, *args, **options):
        config_filename = os.path.abspath(args[0])
        trigger = args[1] if len(args) > 1 else 'manual'

        with open(config_filename, 'r') as f:
            config_file = etree.parse(f)

        dataset_name = config_file.xpath('meta/name')[0].text

        client = redis.client.Redis(**settings.REDIS_PARAMS)

        client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
            'config_filename': config_filename,
            'name': dataset_name,
            'trigger': trigger,
            'queued_at': datetime.datetime.now(),
        })))

if __name__ == '__main__':
    import sys
    Command().handle(*sys.argv[1:])

Response:
<INSERT> trigger = args[1] if len(args) > 1 else 'manual'
        <INSERT_END> <REPLACE_OLD> 'manual',
 <REPLACE_NEW> trigger,
 <REPLACE_END> <REPLACE_OLD> })))

 <REPLACE_NEW> })))

if __name__ == '__main__':
    import sys
    Command().handle(*sys.argv[1:]) <REPLACE_END> <|endoftext|> import base64
import datetime
import os
import pickle

from lxml import etree
import redis

from django.core.management.base import BaseCommand
from django.conf import settings

from humfrey.update.longliving.updater import Updater

class Command(BaseCommand):
    def handle(self, *args, **options):
        config_filename = os.path.abspath(args[0])
        trigger = args[1] if len(args) > 1 else 'manual'

        with open(config_filename, 'r') as f:
            config_file = etree.parse(f)

        dataset_name = config_file.xpath('meta/name')[0].text

        client = redis.client.Redis(**settings.REDIS_PARAMS)

        client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
            'config_filename': config_filename,
            'name': dataset_name,
            'trigger': trigger,
            'queued_at': datetime.datetime.now(),
        })))

if __name__ == '__main__':
    import sys
    Command().handle(*sys.argv[1:])

Prompt:
Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.

import base64
import datetime
import os
import pickle

from lxml import etree
import redis

from django.core.management.base import BaseCommand
from django.conf import settings

from humfrey.update.longliving.updater import Updater

class Command(BaseCommand):
    def handle(self, *args, **options):
        config_filename = os.path.abspath(args[0])

        with open(config_filename, 'r') as f:
            config_file = etree.parse(f)

        dataset_name = config_file.xpath('meta/name')[0].text

        client = redis.client.Redis(**settings.REDIS_PARAMS)

        client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
            'config_filename': config_filename,
            'name': dataset_name,
            'trigger': 'manual',
            'queued_at': datetime.datetime.now(),
        })))


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

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

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

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    # TODO: put package requirements here
]

test_requirements = [
    'coverage',
]

setup(
    name='pic2map',
    version='0.1.0',
    description="Display pictures location in a map",
    long_description=readme + '\n\n' + history,
    author="Javier Collado",
    author_email='jcollado@nowsecure.com',
    url='https://github.com/jcollado/pic2map',
    packages=[
        'pic2map',
    ],
    package_dir={'pic2map':
                 'pic2map'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='picture map location',
    entry_points={
        'console_scripts': [
            'pic2map = pic2map.cli:main',
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

Add entry point for the CLI script

Add entry point for the CLI script

Response:
<INSERT> entry_points={
        'console_scripts': [
            'pic2map = pic2map.cli:main',
        ]
    },
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

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

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    # TODO: put package requirements here
]

test_requirements = [
    'coverage',
]

setup(
    name='pic2map',
    version='0.1.0',
    description="Display pictures location in a map",
    long_description=readme + '\n\n' + history,
    author="Javier Collado",
    author_email='jcollado@nowsecure.com',
    url='https://github.com/jcollado/pic2map',
    packages=[
        'pic2map',
    ],
    package_dir={'pic2map':
                 'pic2map'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='picture map location',
    entry_points={
        'console_scripts': [
            'pic2map = pic2map.cli:main',
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

Prompt:
Add entry point for the CLI script

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

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

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

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    # TODO: put package requirements here
]

test_requirements = [
    'coverage',
]

setup(
    name='pic2map',
    version='0.1.0',
    description="Display pictures location in a map",
    long_description=readme + '\n\n' + history,
    author="Javier Collado",
    author_email='jcollado@nowsecure.com',
    url='https://github.com/jcollado/pic2map',
    packages=[
        'pic2map',
    ],
    package_dir={'pic2map':
                 'pic2map'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='picture map location',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC

class ZMQInteractiveShell(InteractiveShell):
    """A subclass of InteractiveShell for ZMQ."""

    def system(self, cmd):
        cmd = self.var_expand(cmd, depth=2)
        sys.stdout.flush()
        sys.stderr.flush()
        p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        for line in p.stdout.read().split('\n'):
            if len(line) > 0:
                print line
        for line in p.stderr.read().split('\n'):
            if len(line) > 0:
                print line
        return p.wait()

InteractiveShellABC.register(ZMQInteractiveShell)

Response:
<INSERT>        sys.stdout.flush()
        sys.stderr.flush()
 <INSERT_END> <|endoftext|> import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC

class ZMQInteractiveShell(InteractiveShell):
    """A subclass of InteractiveShell for ZMQ."""

    def system(self, cmd):
        cmd = self.var_expand(cmd, depth=2)
        sys.stdout.flush()
        sys.stderr.flush()
        p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        for line in p.stdout.read().split('\n'):
            if len(line) > 0:
                print line
        for line in p.stderr.read().split('\n'):
            if len(line) > 0:
                print line
        return p.wait()

InteractiveShellABC.register(ZMQInteractiveShell)

Prompt:
Add flushing to stdout/stderr in system calls.

import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC

class ZMQInteractiveShell(InteractiveShell):
    """A subclass of InteractiveShell for ZMQ."""

    def system(self, cmd):
        cmd = self.var_expand(cmd, depth=2)
        p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        for line in p.stdout.read().split('\n'):
            if len(line) > 0:
                print line
        for line in p.stderr.read().split('\n'):
            if len(line) > 0:
                print line
        return p.wait()

InteractiveShellABC.register(ZMQInteractiveShell)


import bandicoot as bc
from os.path import dirname, abspath, join

if __name__ == '__main__':
    empty_user = bc.User()
    empty_user.attributes['empty'] = True
    empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
    bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), empty_path)

    sample_user = bc.tests.generate_user.sample_user()
    sample_path = join(dirname(abspath(__file__)), 'samples/sample_user_all_metrics.json')
    bc.io.to_json(bc.utils.all(sample_user, summary='extended', groupby=None, flatten=True), sample_path)

Add a simple command to generate automatic regressions

Response:
<INSERT> import bandicoot as bc
from os.path import dirname, abspath, join

if __name__ == '__main__':
 <INSERT_END> <INSERT>   empty_user = bc.User()
    empty_user.attributes['empty'] = True
    empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
    bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), empty_path)

    sample_user = bc.tests.generate_user.sample_user()
    sample_path = join(dirname(abspath(__file__)), 'samples/sample_user_all_metrics.json')
    bc.io.to_json(bc.utils.all(sample_user, summary='extended', groupby=None, flatten=True), sample_path)
 <INSERT_END> <|endoftext|> import bandicoot as bc
from os.path import dirname, abspath, join

if __name__ == '__main__':
    empty_user = bc.User()
    empty_user.attributes['empty'] = True
    empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
    bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), empty_path)

    sample_user = bc.tests.generate_user.sample_user()
    sample_path = join(dirname(abspath(__file__)), 'samples/sample_user_all_metrics.json')
    bc.io.to_json(bc.utils.all(sample_user, summary='extended', groupby=None, flatten=True), sample_path)

Prompt: Add a simple command to generate automatic regressions


from spyc.graph import Vertex, find_cycle, topological_sort

class CircularDependency(Exception):
    pass

class Scheduler(object):

    def __init__(self):
        self.specs = {}

    def ensure(self, spec):
        """Require that ``spec`` is satisfied."""
        if spec.key() in self.specs:
            self.specs[spec.key()].data.merge(spec)
        else:
            self.specs[spec.key()] = Vertex(spec)

    def depend(self, first, next):
        """Specify that ``first`` depends on ``next``.

        This also has the effect of invoking ``ensure`` on both resources.
        """
        first.schedule(self)
        next.schedule(self)
        self.specs[first.key()].edges.add(self.specs[next.key()])

    def apply(self):
        verticies = set(self.specs.values())
        cycle = find_cycle(verticies)
        if cycle is not None:
            raise CircularDependency(cycle)
        for v in topological_sort(verticies):
            v.data.apply()

Response:
<INSERT> CircularDependency(Exception):
    pass

class <INSERT_END> <REPLACE_OLD> assert False  # TODO proper checking
 <REPLACE_NEW> raise CircularDependency(cycle)
 <REPLACE_END> <|endoftext|> from spyc.graph import Vertex, find_cycle, topological_sort

class CircularDependency(Exception):
    pass

class Scheduler(object):

    def __init__(self):
        self.specs = {}

    def ensure(self, spec):
        """Require that ``spec`` is satisfied."""
        if spec.key() in self.specs:
            self.specs[spec.key()].data.merge(spec)
        else:
            self.specs[spec.key()] = Vertex(spec)

    def depend(self, first, next):
        """Specify that ``first`` depends on ``next``.

        This also has the effect of invoking ``ensure`` on both resources.
        """
        first.schedule(self)
        next.schedule(self)
        self.specs[first.key()].edges.add(self.specs[next.key()])

    def apply(self):
        verticies = set(self.specs.values())
        cycle = find_cycle(verticies)
        if cycle is not None:
            raise CircularDependency(cycle)
        for v in topological_sort(verticies):
            v.data.apply()

Prompt:
Raise a more useful error for circular deps.

from spyc.graph import Vertex, find_cycle, topological_sort

class Scheduler(object):

    def __init__(self):
        self.specs = {}

    def ensure(self, spec):
        """Require that ``spec`` is satisfied."""
        if spec.key() in self.specs:
            self.specs[spec.key()].data.merge(spec)
        else:
            self.specs[spec.key()] = Vertex(spec)

    def depend(self, first, next):
        """Specify that ``first`` depends on ``next``.

        This also has the effect of invoking ``ensure`` on both resources.
        """
        first.schedule(self)
        next.schedule(self)
        self.specs[first.key()].edges.add(self.specs[next.key()])

    def apply(self):
        verticies = set(self.specs.values())
        cycle = find_cycle(verticies)
        if cycle is not None:
            assert False  # TODO proper checking
        for v in topological_sort(verticies):
            v.data.apply()


# -*- coding: utf-8 -*-
'''
url-shortener
==============

An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.

.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views

__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'

log_file = app.config['LOG_FILE']

if not app.debug and log_file is not None:
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

app.run()

Response:
<REPLACE_OLD> Rusin'

if <REPLACE_NEW> Rusin'

log_file = app.config['LOG_FILE']

if <REPLACE_END> <REPLACE_OLD> app.debug:
 <REPLACE_NEW> app.debug and log_file is not None:
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
'''
url-shortener
==============

An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.

.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views

__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'

log_file = app.config['LOG_FILE']

if not app.debug and log_file is not None:
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

app.run()

Prompt:
Make application use log file if its name is not None

# -*- coding: utf-8 -*-
'''
url-shortener
==============

An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.

.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views

__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'

if not app.debug:
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

app.run()


# The Fiona data tool.

if __name__ == '__main__':

    import argparse
    import fiona
    import json
    import pprint
    import sys

    parser = argparse.ArgumentParser(
        description="Serialize a file to GeoJSON or view its description")
    parser.add_argument('-i', '--info',
        action='store_true',
        help='View pretty printed description information only')
    parser.add_argument('-j', '--json',
        action='store_true',
        help='Output description as indented JSON')
    parser.add_argument('filename', help="data file name")
    args = parser.parse_args()

    with fiona.open(args.filename, 'r') as col:
        if args.info:
            if args.json:
                meta = col.meta.copy()
                meta.update(name=args.filename)
                print(json.dumps(meta, indent=2))
            else:
                print("\nDescription of: %r" % col)
                print("\nCoordinate reference system (col.crs):")
                pprint.pprint(meta['crs'])
                print("\nFormat driver (col.driver):")
                pprint.pprint(meta['driver'])
                print("\nData description (col.schema):")
                pprint.pprint(meta['schema'])
        else:
            collection = {'type': 'FeatureCollection'}
            collection['features'] = list(col)
            print(json.dumps(collection, indent=2))

Change record output to strict GeoJSON.

Response:
<REPLACE_OLD> print(json.dumps(list(col), <REPLACE_NEW> collection = {'type': 'FeatureCollection'}
            collection['features'] = list(col)
            print(json.dumps(collection, <REPLACE_END> <|endoftext|> # The Fiona data tool.

if __name__ == '__main__':

    import argparse
    import fiona
    import json
    import pprint
    import sys

    parser = argparse.ArgumentParser(
        description="Serialize a file to GeoJSON or view its description")
    parser.add_argument('-i', '--info',
        action='store_true',
        help='View pretty printed description information only')
    parser.add_argument('-j', '--json',
        action='store_true',
        help='Output description as indented JSON')
    parser.add_argument('filename', help="data file name")
    args = parser.parse_args()

    with fiona.open(args.filename, 'r') as col:
        if args.info:
            if args.json:
                meta = col.meta.copy()
                meta.update(name=args.filename)
                print(json.dumps(meta, indent=2))
            else:
                print("\nDescription of: %r" % col)
                print("\nCoordinate reference system (col.crs):")
                pprint.pprint(meta['crs'])
                print("\nFormat driver (col.driver):")
                pprint.pprint(meta['driver'])
                print("\nData description (col.schema):")
                pprint.pprint(meta['schema'])
        else:
            collection = {'type': 'FeatureCollection'}
            collection['features'] = list(col)
            print(json.dumps(collection, indent=2))

Prompt:
Change record output to strict GeoJSON.

Meaning features in a FeatureCollection.

# The Fiona data tool.

if __name__ == '__main__':

    import argparse
    import fiona
    import json
    import pprint
    import sys

    parser = argparse.ArgumentParser(
        description="Serialize a file to GeoJSON or view its description")
    parser.add_argument('-i', '--info',
        action='store_true',
        help='View pretty printed description information only')
    parser.add_argument('-j', '--json',
        action='store_true',
        help='Output description as indented JSON')
    parser.add_argument('filename', help="data file name")
    args = parser.parse_args()

    with fiona.open(args.filename, 'r') as col:
        if args.info:
            if args.json:
                meta = col.meta.copy()
                meta.update(name=args.filename)
                print(json.dumps(meta, indent=2))
            else:
                print("\nDescription of: %r" % col)
                print("\nCoordinate reference system (col.crs):")
                pprint.pprint(meta['crs'])
                print("\nFormat driver (col.driver):")
                pprint.pprint(meta['driver'])
                print("\nData description (col.schema):")
                pprint.pprint(meta['schema'])
        else:
            print(json.dumps(list(col), indent=2))


#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#

"""This module exports the Bemlint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Bemlint(NodeLinter):
    """Provides an interface to bemlint."""

    name = 'bemlint'
    cmd = 'bemlint @ ${args}'
    config_file = ('--config', '.bemlint.json')
    regex = (
        r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
        r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
        r'(?P<message>.+)'
    )
    multiline = False
    line_col_base = (1, 1)
    error_stream = util.STREAM_BOTH
    tempfile_suffix = 'bem'

    defaults = {
        'selector': 'text.html',
        '--format': 'compact',
    }

    # the following attributes are marked useless for SL4
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'

Response:
<REPLACE_OLD> syntax <REPLACE_NEW> name <REPLACE_END> <REPLACE_OLD> ('html', 'html+tt2', 'html+tt3')
 <REPLACE_NEW> 'bemlint'
 <REPLACE_END> <REPLACE_OLD> ('bemlint', '@', '--format', 'compact')
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'
 <REPLACE_NEW> 'bemlint @ ${args}'
 <REPLACE_END> <REPLACE_OLD> 'bem'
 <REPLACE_NEW> 'bem'

    defaults = {
        'selector': 'text.html',
        '--format': 'compact',
    }

    # the following attributes are marked useless for SL4
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'
 <REPLACE_END> <|endoftext|>
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#

"""This module exports the Bemlint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Bemlint(NodeLinter):
    """Provides an interface to bemlint."""

    name = 'bemlint'
    cmd = 'bemlint @ ${args}'
    config_file = ('--config', '.bemlint.json')
    regex = (
        r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
        r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
        r'(?P<message>.+)'
    )
    multiline = False
    line_col_base = (1, 1)
    error_stream = util.STREAM_BOTH
    tempfile_suffix = 'bem'

    defaults = {
        'selector': 'text.html',
        '--format': 'compact',
    }

    # the following attributes are marked useless for SL4
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'

Prompt:
Fix compatibility for SublimeLinter 4.12.0

Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>

#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#

"""This module exports the Bemlint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Bemlint(NodeLinter):
    """Provides an interface to bemlint."""

    syntax = ('html', 'html+tt2', 'html+tt3')
    cmd = ('bemlint', '@', '--format', 'compact')
    version_args = '--version'
    version_re = r'v(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.4.5'
    config_file = ('--config', '.bemlint.json')
    regex = (
        r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
        r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
        r'(?P<message>.+)'
    )
    multiline = False
    line_col_base = (1, 1)
    error_stream = util.STREAM_BOTH
    tempfile_suffix = 'bem'


import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys

from dogen.plugins.repo import Repo
from dogen.generator import Generator

class TestPackage(unittest.TestCase):
    def setUp(self):
        self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
        self.descriptor = tempfile.NamedTemporaryFile(delete=False)
        self.target_dir = os.path.join(self.workdir, "target")
        self.log = mock.Mock()

    def teardown(self):
        shutil.rmtree(self.workdir)

    def write_config(self, config):
        with self.descriptor as f:
            f.write(config.encode())

    def prepare_dogen(self, repo_files_dir=None):
        args = argparse.Namespace(path=self.descriptor.name, output=self.target_dir, without_sources=None,
                                  template=None, scripts_path=None, additional_script=None,
                                  skip_ssl_verification=None, repo_files_dir=repo_files_dir)
        self.dogen = Generator(self.log, args, [Repo])

    def test_custom_repo_files_should_add_two(self):
        open(os.path.join(self.workdir, "fedora.repo"), 'a').close()
        open(os.path.join(self.workdir, "test.repo"), 'a').close()

        self.write_config("release: '1'\nversion: '1'\ncmd:\n - whoami\nfrom: scratch\nname: someimage\npackages:\n - wget")
        self.prepare_dogen(self.workdir)
        self.dogen.run()

        self.assertIsNotNone(self.dogen.cfg)
        self.assertIsNotNone(self.dogen.cfg.get('packages'))
        self.assertIsInstance(self.dogen.cfg.get('packages'), list)
        self.assertIn("wget", self.dogen.cfg.get('packages'))

        dockerfile = open(os.path.join(self.target_dir, "Dockerfile")).read()

        sys.stderr.write("\t\t\tDEBUGDEBUG\n{}\n".format(dockerfile))
        self.assertTrue(re.match(r'.*yum install[^\n]+wget', dockerfile, re.DOTALL))
        self.assertTrue(re.match(r'.*rpm -q +wget', dockerfile, re.DOTALL))

Add a test for package generation

Add a test for package generation

Response:
<REPLACE_OLD>  <REPLACE_NEW> import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys

from dogen.plugins.repo import Repo
from dogen.generator import Generator

class TestPackage(unittest.TestCase):
    def setUp(self):
        self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
        self.descriptor = tempfile.NamedTemporaryFile(delete=False)
        self.target_dir = os.path.join(self.workdir, "target")
        self.log = mock.Mock()

    def teardown(self):
        shutil.rmtree(self.workdir)

    def write_config(self, config):
        with self.descriptor as f:
            f.write(config.encode())

    def prepare_dogen(self, repo_files_dir=None):
        args = argparse.Namespace(path=self.descriptor.name, output=self.target_dir, without_sources=None,
                                  template=None, scripts_path=None, additional_script=None,
                                  skip_ssl_verification=None, repo_files_dir=repo_files_dir)
        self.dogen = Generator(self.log, args, [Repo])

    def test_custom_repo_files_should_add_two(self):
        open(os.path.join(self.workdir, "fedora.repo"), 'a').close()
        open(os.path.join(self.workdir, "test.repo"), 'a').close()

        self.write_config("release: '1'\nversion: '1'\ncmd:\n - whoami\nfrom: scratch\nname: someimage\npackages:\n - wget")
        self.prepare_dogen(self.workdir)
        self.dogen.run()

        self.assertIsNotNone(self.dogen.cfg)
        self.assertIsNotNone(self.dogen.cfg.get('packages'))
        self.assertIsInstance(self.dogen.cfg.get('packages'), list)
        self.assertIn("wget", self.dogen.cfg.get('packages'))

        dockerfile = open(os.path.join(self.target_dir, "Dockerfile")).read()

        sys.stderr.write("\t\t\tDEBUGDEBUG\n{}\n".format(dockerfile))
        self.assertTrue(re.match(r'.*yum install[^\n]+wget', dockerfile, re.DOTALL))
        self.assertTrue(re.match(r'.*rpm -q +wget', dockerfile, re.DOTALL))
 <REPLACE_END> <|endoftext|> import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys

from dogen.plugins.repo import Repo
from dogen.generator import Generator

class TestPackage(unittest.TestCase):
    def setUp(self):
        self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
        self.descriptor = tempfile.NamedTemporaryFile(delete=False)
        self.target_dir = os.path.join(self.workdir, "target")
        self.log = mock.Mock()

    def teardown(self):
        shutil.rmtree(self.workdir)

    def write_config(self, config):
        with self.descriptor as f:
            f.write(config.encode())

    def prepare_dogen(self, repo_files_dir=None):
        args = argparse.Namespace(path=self.descriptor.name, output=self.target_dir, without_sources=None,
                                  template=None, scripts_path=None, additional_script=None,
                                  skip_ssl_verification=None, repo_files_dir=repo_files_dir)
        self.dogen = Generator(self.log, args, [Repo])

    def test_custom_repo_files_should_add_two(self):
        open(os.path.join(self.workdir, "fedora.repo"), 'a').close()
        open(os.path.join(self.workdir, "test.repo"), 'a').close()

        self.write_config("release: '1'\nversion: '1'\ncmd:\n - whoami\nfrom: scratch\nname: someimage\npackages:\n - wget")
        self.prepare_dogen(self.workdir)
        self.dogen.run()

        self.assertIsNotNone(self.dogen.cfg)
        self.assertIsNotNone(self.dogen.cfg.get('packages'))
        self.assertIsInstance(self.dogen.cfg.get('packages'), list)
        self.assertIn("wget", self.dogen.cfg.get('packages'))

        dockerfile = open(os.path.join(self.target_dir, "Dockerfile")).read()

        sys.stderr.write("\t\t\tDEBUGDEBUG\n{}\n".format(dockerfile))
        self.assertTrue(re.match(r'.*yum install[^\n]+wget', dockerfile, re.DOTALL))
        self.assertTrue(re.match(r'.*rpm -q +wget', dockerfile, re.DOTALL))

Prompt: Add a test for package generation


from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow

LOCK_USER = 'lock_user'
STATUS = '_status'

class ItemLock():
    def __init__(self, data_layer):
        self.data_layer = data_layer

    def lock(self, filter, user, etag):
        item_model = ItemModel(self.data_layer)
        item = item_model.find_one(filter)
        if item and self._can_lock(item, user):
            # filter[ETAG] = etag
            updates = {LOCK_USER: user, 'lock_time': utcnow()}
            item_model.update(filter, updates)
            item[LOCK_USER] = user
        else:
            raise SuperdeskError('Item locked by another user')
        return item

    def unlock(self, filter, user, etag):
        item_model = ItemModel()
        filter[LOCK_USER] = user
        filter[ETAG] = etag
        item = item_model.find_one(filter)
        if item:
            update = {LOCK_USER: None}
            item_model.update(filter, update)

    def _can_lock(self, item, user):
        # TODO: implement
        return True

Set timestamp on item lock operation

Set timestamp on item lock operation

Response:
<REPLACE_OLD> SuperdeskError

LOCK_USER <REPLACE_NEW> SuperdeskError
from superdesk.utc import utcnow

LOCK_USER <REPLACE_END> <REPLACE_OLD> user}
 <REPLACE_NEW> user, 'lock_time': utcnow()}
 <REPLACE_END> <|endoftext|> from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow

LOCK_USER = 'lock_user'
STATUS = '_status'

class ItemLock():
    def __init__(self, data_layer):
        self.data_layer = data_layer

    def lock(self, filter, user, etag):
        item_model = ItemModel(self.data_layer)
        item = item_model.find_one(filter)
        if item and self._can_lock(item, user):
            # filter[ETAG] = etag
            updates = {LOCK_USER: user, 'lock_time': utcnow()}
            item_model.update(filter, updates)
            item[LOCK_USER] = user
        else:
            raise SuperdeskError('Item locked by another user')
        return item

    def unlock(self, filter, user, etag):
        item_model = ItemModel()
        filter[LOCK_USER] = user
        filter[ETAG] = etag
        item = item_model.find_one(filter)
        if item:
            update = {LOCK_USER: None}
            item_model.update(filter, update)

    def _can_lock(self, item, user):
        # TODO: implement
        return True

Prompt:
Set timestamp on item lock operation

from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError

LOCK_USER = 'lock_user'
STATUS = '_status'

class ItemLock():
    def __init__(self, data_layer):
        self.data_layer = data_layer

    def lock(self, filter, user, etag):
        item_model = ItemModel(self.data_layer)
        item = item_model.find_one(filter)
        if item and self._can_lock(item, user):
            # filter[ETAG] = etag
            updates = {LOCK_USER: user}
            item_model.update(filter, updates)
            item[LOCK_USER] = user
        else:
            raise SuperdeskError('Item locked by another user')
        return item

    def unlock(self, filter, user, etag):
        item_model = ItemModel()
        filter[LOCK_USER] = user
        filter[ETAG] = etag
        item = item_model.find_one(filter)
        if item:
            update = {LOCK_USER: None}
            item_model.update(filter, update)

    def _can_lock(self, item, user):
        # TODO: implement
        return True


from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot

class ChatterBotView(View):

    chatterbot = ChatBot(
        settings.CHATTERBOT['NAME'],
        storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
        input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter',
        output_adapter='chatterbot.adapters.output.OutputFormatAdapter',
        output_format='json'
    )

    def post(self, request, *args, **kwargs):
        input_statement = request.POST.get('text')

        response_data = self.chatterbot.get_response(input_statement)

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def patch(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def delete(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

Response:
<REPLACE_OLD> settings

class <REPLACE_NEW> settings
from chatterbot import ChatBot

class <REPLACE_END> <INSERT>    chatterbot = ChatBot(
        settings.CHATTERBOT['NAME'],
        storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
        input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter',
        output_adapter='chatterbot.adapters.output.OutputFormatAdapter',
        output_format='json'
    )

 <INSERT_END> <REPLACE_OLD> settings.CHATTERBOT.get_response(input_statement)

 <REPLACE_NEW> self.chatterbot.get_response(input_statement)

 <REPLACE_END> <|endoftext|> from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot

class ChatterBotView(View):

    chatterbot = ChatBot(
        settings.CHATTERBOT['NAME'],
        storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
        input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter',
        output_adapter='chatterbot.adapters.output.OutputFormatAdapter',
        output_format='json'
    )

    def post(self, request, *args, **kwargs):
        input_statement = request.POST.get('text')

        response_data = self.chatterbot.get_response(input_statement)

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def patch(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def delete(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

Prompt:
Initialize ChatterBot in django view module instead of settings.

from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings

class ChatterBotView(View):

    def post(self, request, *args, **kwargs):
        input_statement = request.POST.get('text')

        response_data = settings.CHATTERBOT.get_response(input_statement)

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def patch(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)

    def delete(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
        }

        # Return a method not allowed response
        return JsonResponse(data, status=405)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('routes', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='route',
            name='slug',
            field=models.SlugField(max_length=255, help_text='The url fragment at this point in the Route hierarchy.', default=''),
        ),
    ]

Add missing migration to routes app

Add missing migration to routes app

Response:
<INSERT> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('routes', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='route',
            name='slug',
            field=models.SlugField(max_length=255, help_text='The url fragment at this point in the Route hierarchy.', default=''),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('routes', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='route',
            name='slug',
            field=models.SlugField(max_length=255, help_text='The url fragment at this point in the Route hierarchy.', default=''),
        ),
    ]

Prompt: Add missing migration to routes app


from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.22',
        'future>=0.16,<0.18',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<2.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)

Response:
<REPLACE_OLD> 'requests>=2.4.2,<2.21',
 <REPLACE_NEW> 'requests>=2.4.2,<2.22',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.22',
        'future>=0.16,<0.18',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<2.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)

Prompt:
Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22

Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.21.0)

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

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.21',
        'future>=0.16,<0.18',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<2.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)


#!/usr/bin/python
#coding: utf-8
import requests
import re
import time
from time import gmtime, strftime

class GenNowPlayingID(object):
	"""docstring for ClassName"""
	def __init__(self):
		#super(ClassName, self).__init__()
		# self.arg = arg
		pass

	def GenNowPlayingIdList(self):
		page = requests.get('https://movie.douban.com/nowplaying/beijing/')
		content=page.text.encode("utf-8")
		pattern=re.compile(r'(?<=id=")\d+(?="\n)')
		result=pattern.findall(content)

		currentTime = strftime("%Y%m%d_%H:%M:%S", time.localtime(time.time()))
		print currentTime
		filename = './nowplaying_id/' + currentTime + '.id'
		fp = open(filename,'w')

		for iterm in result:
			fp.write(iterm+"\n")
		fp.close()

if __name__=="__main__":
	genNowPlayingID = GenNowPlayingID()
	genNowPlayingID.GenNowPlayingIdList()

Write the nowplaying movie id to file

Write the nowplaying movie id to file

Response:
<REPLACE_OLD> re
if __name__=="__main__":
	page <REPLACE_NEW> re
import time
from time import gmtime, strftime

class GenNowPlayingID(object):
	"""docstring for ClassName"""
	def __init__(self):
		#super(ClassName, self).__init__()
		# self.arg <REPLACE_END> <REPLACE_OLD> requests.get('https://movie.douban.com/nowplaying/beijing/')
	content=page.text.encode("utf-8")
	pattern=re.compile(r'(?<=id=")\d+(?="\n)')
	result=pattern.findall(content)
	for <REPLACE_NEW> arg
		pass

	def GenNowPlayingIdList(self):
		page = requests.get('https://movie.douban.com/nowplaying/beijing/')
		content=page.text.encode("utf-8")
		pattern=re.compile(r'(?<=id=")\d+(?="\n)')
		result=pattern.findall(content)

		currentTime = strftime("%Y%m%d_%H:%M:%S", time.localtime(time.time()))
		print currentTime
		filename = './nowplaying_id/' + currentTime + '.id'
		fp = open(filename,'w')

		for <REPLACE_END> <REPLACE_OLD> result:
		print iterm

 <REPLACE_NEW> result:
			fp.write(iterm+"\n")
		fp.close()

if __name__=="__main__":
	genNowPlayingID = GenNowPlayingID()
	genNowPlayingID.GenNowPlayingIdList()

 <REPLACE_END> <|endoftext|> #!/usr/bin/python
#coding: utf-8
import requests
import re
import time
from time import gmtime, strftime

class GenNowPlayingID(object):
	"""docstring for ClassName"""
	def __init__(self):
		#super(ClassName, self).__init__()
		# self.arg = arg
		pass

	def GenNowPlayingIdList(self):
		page = requests.get('https://movie.douban.com/nowplaying/beijing/')
		content=page.text.encode("utf-8")
		pattern=re.compile(r'(?<=id=")\d+(?="\n)')
		result=pattern.findall(content)

		currentTime = strftime("%Y%m%d_%H:%M:%S", time.localtime(time.time()))
		print currentTime
		filename = './nowplaying_id/' + currentTime + '.id'
		fp = open(filename,'w')

		for iterm in result:
			fp.write(iterm+"\n")
		fp.close()

if __name__=="__main__":
	genNowPlayingID = GenNowPlayingID()
	genNowPlayingID.GenNowPlayingIdList()

Prompt:
Write the nowplaying movie id to file

#!/usr/bin/python
#coding: utf-8
import requests
import re
if __name__=="__main__":
	page = requests.get('https://movie.douban.com/nowplaying/beijing/')
	content=page.text.encode("utf-8")
	pattern=re.compile(r'(?<=id=")\d+(?="\n)')
	result=pattern.findall(content)
	for iterm in result:
		print iterm


from django.apps import AppConfig

class OstinatoBlogConfig(AppConfig):
    name = 'ostinato.blog'
    label = 'ostinato_blog'
    verbose_name = 'Ostinato Blog Engine'

Correct app label of ostinato_blog

Correct app label of ostinato_blog

Response:
<REPLACE_OLD> 'ost_blog'
 <REPLACE_NEW> 'ostinato_blog'
 <REPLACE_END> <|endoftext|> from django.apps import AppConfig

class OstinatoBlogConfig(AppConfig):
    name = 'ostinato.blog'
    label = 'ostinato_blog'
    verbose_name = 'Ostinato Blog Engine'

Prompt:
Correct app label of ostinato_blog

from django.apps import AppConfig

class OstinatoBlogConfig(AppConfig):
    name = 'ostinato.blog'
    label = 'ost_blog'
    verbose_name = 'Ostinato Blog Engine'


from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

def isValidUserName(username):
	try:
		User.objects.get(username=username)
	except User.DoesNotExist:
		return
	raise ValidationError('The username "%s" is already taken.' % username)

class RegistrationForm(UserCreationForm):

	username = forms.CharField(label='username',
							max_length=30,
							required=True, validators=[isValidUserName])
	class Meta:
		model = User
		fields = ('username','first_name', 'last_name', 'email',)

	def save(self, commit=True):
		new_user = super(RegistrationForm, self).save(commit=False)

		new_user.is_active = False

		if commit:
			new_user.save()

		return new_user

Response:
<REPLACE_OLD> django.core <REPLACE_NEW> django.core.exceptions <REPLACE_END> <REPLACE_OLD> validators
from <REPLACE_NEW> ValidationError
from <REPLACE_END> <REPLACE_OLD> UserCreationForm

class <REPLACE_NEW> UserCreationForm

def isValidUserName(username):
	try:
		User.objects.get(username=username)
	except User.DoesNotExist:
		return
	raise ValidationError('The username "%s" is already taken.' % username)

class <REPLACE_END> <REPLACE_OLD> forms.CharField(label='username',
							max_length=30,
							required=True,) #validators=[self.isValidUserName])
	class <REPLACE_NEW> forms.CharField(label='username',
							max_length=30,
							required=True, validators=[isValidUserName])
	class <REPLACE_END> <REPLACE_OLD> 'email',)

#	def isValidUserName(self, field_data, all_data):
#		try:
#			User.objects.get(username=field_data)
#		except User.DoesNotExist:
#			return
#		raise validators.ValidationError('The username "%s" is already taken.' % field_data)

	def <REPLACE_NEW> 'email',)

	def <REPLACE_END> <REPLACE_OLD> new_user
 <REPLACE_NEW> new_user

 <REPLACE_END> <|endoftext|> from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

def isValidUserName(username):
	try:
		User.objects.get(username=username)
	except User.DoesNotExist:
		return
	raise ValidationError('The username "%s" is already taken.' % username)

class RegistrationForm(UserCreationForm):

	username = forms.CharField(label='username',
							max_length=30,
							required=True, validators=[isValidUserName])
	class Meta:
		model = User
		fields = ('username','first_name', 'last_name', 'email',)

	def save(self, commit=True):
		new_user = super(RegistrationForm, self).save(commit=False)

		new_user.is_active = False

		if commit:
			new_user.save()

		return new_user

Prompt:
Implement validation to the username field.

from django import forms
from django.core import validators
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):

	username = forms.CharField(label='username',
							max_length=30,
							required=True,) #validators=[self.isValidUserName])
	class Meta:
		model = User
		fields = ('username','first_name', 'last_name', 'email',)

#	def isValidUserName(self, field_data, all_data):
#		try:
#			User.objects.get(username=field_data)
#		except User.DoesNotExist:
#			return
#		raise validators.ValidationError('The username "%s" is already taken.' % field_data)

	def save(self, commit=True):
		new_user = super(RegistrationForm, self).save(commit=False)

		new_user.is_active = False

		if commit:
			new_user.save()

		return new_user


# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop

def get_shop_from_host(host):
    """
    Try to find a shop that matches a `host`
    e.g: shop.domain.com, domain.com, localhost:8000

    :type host str
    """
    shop = Shop.objects.filter(domain=host).first()

    if not shop and ":" in host:
        shop = Shop.objects.filter(domain=host.rsplit(":")[0]).first()

    if not shop:
        subdomain = host.split(".")[0]
        shop = Shop.objects.filter(domain=subdomain).first()

    return shop

Response:
<INSERT> shop and ":" in host:
        shop = Shop.objects.filter(domain=host.rsplit(":")[0]).first()

    if not <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop

def get_shop_from_host(host):
    """
    Try to find a shop that matches a `host`
    e.g: shop.domain.com, domain.com, localhost:8000

    :type host str
    """
    shop = Shop.objects.filter(domain=host).first()

    if not shop and ":" in host:
        shop = Shop.objects.filter(domain=host.rsplit(":")[0]).first()

    if not shop:
        subdomain = host.split(".")[0]
        shop = Shop.objects.filter(domain=subdomain).first()

    return shop

Prompt:
Make handle ports better when choosing shop

Refs EE-235

# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop

def get_shop_from_host(host):
    """
    Try to find a shop that matches a `host`
    e.g: shop.domain.com, domain.com, localhost:8000

    :type host str
    """
    shop = Shop.objects.filter(domain=host).first()

    if not shop:
        subdomain = host.split(".")[0]
        shop = Shop.objects.filter(domain=subdomain).first()

    return shop


# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals

from django.db import migrations, models
try:
    import django.contrib.auth.validators
    extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
    extra_kwargs = {}

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0013_profile_event_reminder_time'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'},
                                   help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
                                   max_length=150, unique=True, verbose_name='username', **extra_kwargs),
        ),
    ]

Response:
<REPLACE_OLD> unicode_literals

import django.contrib.auth.validators
from <REPLACE_NEW> unicode_literals

from <REPLACE_END> <REPLACE_OLD> models

class <REPLACE_NEW> models
try:
    import django.contrib.auth.validators
    extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
    extra_kwargs = {}

class <REPLACE_END> <REPLACE_OLD> exists.'}, <REPLACE_NEW> exists.'},
                                   <REPLACE_END> <REPLACE_OLD> only.', <REPLACE_NEW> only.',
                                   <REPLACE_END> <REPLACE_OLD> validators=[django.contrib.auth.validators.ASCIIUsernameValidator()], verbose_name='username'),
 <REPLACE_NEW> verbose_name='username', **extra_kwargs),
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals

from django.db import migrations, models
try:
    import django.contrib.auth.validators
    extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
    extra_kwargs = {}

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0013_profile_event_reminder_time'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'},
                                   help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
                                   max_length=150, unique=True, verbose_name='username', **extra_kwargs),
        ),
    ]

Prompt:
Fix backward compatibility of migrations

# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals

import django.contrib.auth.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0013_profile_event_reminder_time'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.ASCIIUsernameValidator()], verbose_name='username'),
        ),
    ]